본문 바로가기
드림핵

[드림핵] command-injection-chatgpt 풀이

by jwcs 2023. 9. 24.
728x90

https://dreamhack.io/wargame/challenges/768

 

command-injection-chatgpt

특정 Host에 ping 패킷을 보내는 서비스입니다. Command Injection을 통해 플래그를 획득하세요. 플래그는 flag.py에 있습니다. chatGPT와 함께 풀어보세요! Reference Introduction of Webhacking

dreamhack.io

챗 지피티와 함께 풀어보자.

 

 

/

초기 화면이다. Ping 페이지가 보인다. Ping 페이지로 가보자.

 

/ping

아이피 주소를 넣을 수 있는 곳이 보인다. 코드를 보면서 이해해보자.

 

#!/usr/bin/env python3
import subprocess

from flask import Flask, request, render_template, redirect

from flag import FLAG

APP = Flask(__name__)


@APP.route('/')
def index():
    return render_template('index.html')


@APP.route('/ping', methods=['GET', 'POST'])
def ping():
    if request.method == 'POST':
        host = request.form.get('host')
        cmd = f'ping -c 3 {host}'
        try:
            output = subprocess.check_output(['/bin/sh', '-c', cmd], timeout=5)
            return render_template('ping_result.html', data=output.decode('utf-8'))
        except subprocess.TimeoutExpired:
            return render_template('ping_result.html', data='Timeout !')
        except subprocess.CalledProcessError:
            return render_template('ping_result.html', data=f'an error occurred while executing the command. -> {cmd}')

    return render_template('ping.html')


if __name__ == '__main__':
    APP.run(host='0.0.0.0', port=8000)

app.py 코드이다.

 

    if request.method == 'POST':
        host = request.form.get('host')
        cmd = f'ping -c 3 {host}'

우리가 입력한 주소가 ping -c 3 과 함께 cmd라는 변수에 저장된다.

 

output = subprocess.check_output(['/bin/sh', '-c', cmd], timeout=5)

subprocess 모듈은 Python에서 외부 프로세스를 생성하고 상호 작용하는 데 사용되는 라이브러리이다. 이 모듈을 사용하면 Python 스크립트에서 다른 프로그램을 실행하고 그 결과를 캡처하거나 표준 입력/출력/오류를 관리할 수 있다. subprocess 모듈은 시스템 명령을 실행하고 외부 프로그램과 상호 작용하는 데 매우 유용하다.

 

subprocess.check_output(): 명령을 실행하고 해당 명령의 출력을 캡처한다. 명령이 완료되면 출력을 반환한다. 명령이 성공적으로 완료되지 않으면 CalledProcessError 예외를 발생시킨다.

 

/bin/sh -c는 리눅스와 유닉스 기반 운영 체제에서 셸 스크립트나 명령어를 실행하는 방법 중 하나이다. 여기서 /bin/sh는 셸 실행기(binary shell)의 경로를 나타내며, -c는 셸에서 실행할 명령 또는 스크립트를 인수(argument)로 받는 옵션이다.

 

/bin/sh -c "echo Hello, World!"

예를 들면 이런 명령문을 실행시킬 수 있다.

 

종합해보면 subprocess 모듈을 통해 /bin/sh 명령을 내린다. 이 명령은 cmd에 담긴 내용을 내릴텐데, 이 내용은 ping 명령어이다. 이 뒤에 우리가 입력한 주소에 ping을 3번 날릴거다.

 

우리는 이제 취약점을 찾아야한다. 우리가 입력하는 부분에 입력값 검증이 이루어지고있지 않다. 따라서 8.8.8.8; ls;와 같이 입력하면 ping 명령 이후 ls 명령도 같이 출력해서 보여줄 것이다.

 

flag.py가 보인다. 이번엔 cat 명령어를 써서 flag.py를 가져오자.

 

8.8.8.8; cat flag.py;

 

짜자잔

 

취약점 분석

- 아이피 주소를 입력하는 곳의 입력값 검증이 이루어지지 않았다.

 

해결 방법

- 다른 명령어를 사용할 수 없도록 ; 와 같은 기호를 필터링을 걸어두는 것이 좋아보인다.

728x90
반응형

'드림핵' 카테고리의 다른 글

[드림핵] Tomcat Manager 풀이  (0) 2024.01.03
[드림핵] Type c-j 풀이  (0) 2023.09.30
[드림핵] Textbook-CBC 풀이  (0) 2023.09.16
[드림핵] ROT128 풀이  (0) 2023.09.11
[드림핵] Relative Path Overwrite 풀이  (0) 2023.09.01