36번째 문제 가보자고!
XSS(교차 사이트 스크립팅, Cross-Site Scripting) 취약점은 공격자가 악성 스크립트를 웹 페이지에 삽입하여 다른 사용자의 브라우저에서 실행되도록 하는 공격 기법입니다. XSS는 주로 다음과 같은 세 가지 유형으로 분류됩니다:
1. **저장형 XSS (Stored XSS)**:
- 악성 스크립트가 서버에 저장되어 다른 사용자에게 전달됩니다. 예를 들어, 사용자 입력을 검증하지 않고 데이터베이스에 저장하는 경우 발생할 수 있습니다. 이후 이 데이터가 웹 페이지에서 렌더링될 때, 스크립트가 실행됩니다.
2. **반사형 XSS (Reflected XSS)**:
- 공격자가 악성 링크를 클릭하도록 유도하면, 해당 링크가 요청된 페이지에 악성 스크립트가 포함됩니다. 서버는 사용자 입력을 검증하지 않고 바로 응답으로 반환하므로, 사용자의 브라우저에서 스크립트가 실행됩니다.
3. **DOM 기반 XSS (DOM-based XSS)**:
- 클라이언트 측 스크립트(예: JavaScript)가 URL의 파라미터나 DOM 조작을 통해 악성 코드를 실행하는 경우입니다. 서버의 응답과는 무관하게 클라이언트 측에서 발생합니다.
### XSS 공격의 피해
XSS 공격을 통해 공격자는 다음과 같은 행위를 할 수 있습니다:
- 사용자 세션 탈취
- 악성 코드 다운로드
- 사용자에게 피싱 사이트로 리다이렉트
- 웹 애플리케이션의 데이터를 수정하거나 삭제
### XSS 방어 방법
1. **입력 검증**: 사용자 입력을 철저히 검증하고 필터링하여 악성 스크립트가 포함되지 않도록 합니다.
2. **출력 인코딩**: HTML, JavaScript, URL 등 다양한 컨텍스트에 맞게 출력할 때 인코딩하여 악성 코드가 실행되지 않도록 합니다.
3. **CSP(Content Security Policy)**: CSP를 설정하여 스크립트의 출처를 제한함으로써 공격자가 악성 스크립트를 실행하는 것을 방지합니다.
4. **HTTPOnly 쿠키 사용**: 쿠키에 HTTPOnly 속성을 추가하여 JavaScript에서 접근할 수 없도록 설정합니다.
XSS 취약점은 웹 애플리케이션의 보안에 큰 영향을 미칠 수 있으므로, 이러한 공격을 예방하는 것은 매우 중요합니다.
아하 공격 기법이구나. 딱봐도 dom기반 xss가 우리가 오늘 문제를 해결하는 방법인 것 같다.
소스코드를 보자
#!/usr/bin/python3
from flask import Flask, request, render_template
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import urllib
import os
app = Flask(__name__)
app.secret_key = os.urandom(32)
try:
FLAG = open("./flag.txt", "r").read()
except:
FLAG = "[**FLAG**]"
def read_url(url, cookie={"name": "name", "value": "value"}):
cookie.update({"domain": "127.0.0.1"})
try:
service = Service(executable_path="/chromedriver")
options = webdriver.ChromeOptions()
for _ in [
"headless",
"window-size=1920x1080",
"disable-gpu",
"no-sandbox",
"disable-dev-shm-usage",
]:
options.add_argument(_)
driver = webdriver.Chrome(service=service, options=options)
driver.implicitly_wait(3)
driver.set_page_load_timeout(3)
driver.get("http://127.0.0.1:8000/")
driver.add_cookie(cookie)
driver.get(url)
except Exception as e:
driver.quit()
# return str(e)
return False
driver.quit()
return True
def check_xss(param, cookie={"name": "name", "value": "value"}):
url = f"http://127.0.0.1:8000/vuln?param={urllib.parse.quote(param)}"
return read_url(url, cookie)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/vuln")
def vuln():
param = request.args.get("param", "")
return param
@app.route("/flag", methods=["GET", "POST"])
def flag():
if request.method == "GET":
return render_template("flag.html")
elif request.method == "POST":
param = request.form.get("param")
if not check_xss(param, {"name": "flag", "value": FLAG.strip()}):
return '<script>alert("wrong??");history.go(-1);</script>'
return '<script>alert("good");history.go(-1);</script>'
memo_text = ""
@app.route("/memo")
def memo():
global memo_text
text = request.args.get("memo", "")
memo_text += text + "\n"
return render_template("memo.html", memo=memo_text)
app.run(host="0.0.0.0", port=8000)
지피티야 분석해줘
This Flask application demonstrates a potential Cross-Site Scripting (XSS) vulnerability, particularly in the `/flag` endpoint. Here’s a breakdown of how it works and how XSS might be exploited within it:
### Overview of the Application
1. **Basic Structure**:
- The application uses Flask to set up a web server and handle requests. It has routes for the main index page, a vulnerable endpoint (`/vuln`), a flag endpoint (`/flag`), and a memo feature (`/memo`).
페이지는 세개. /vuln 페이지를 취약하다고 표현했다.
2. **Cookie Handling**:
- The application attempts to use cookies for authentication or session management by sending a cookie when checking the XSS vulnerability.
xss취약점을 검사할때 쿠키를 전송하여 인증이나 세션관리를위해 쿠키를 사용하려고 시도함
3. **XSS Vulnerability**:
- The `/vuln` route takes a `param` parameter from the query string and returns it directly in the HTTP response without any sanitization or escaping. This means that if an attacker can manipulate the `param`, they can inject malicious scripts.
경로는 쿼리 문자열에서 매개변수를 /vuln가져와서 param어떠한 살균이나 이스케이핑 없이 HTTP 응답에 직접 반환합니다. 즉, 공격자가 를 조작할 수 있다면 param악성 스크립트를 삽입할 수 있다는 뜻입니다.
여기군. 여기서 악성 스크립트를 삽입하면 될 것 같다. 아마 악성 스크립트를 삽입하면 flag가 나올 확률이 높을 것같다.
4. **Flag Route**:
- The `/flag` route accepts a POST request containing a `param` and checks for XSS by calling `check_xss()`, which constructs a URL with the `param` included in it. It then attempts to read this URL using Selenium.
- If the `param` is safe and does not trigger an XSS, an alert saying "good" is shown. Otherwise, it shows "wrong??".
- 경로는 /flaga를 포함하는 POST 요청을 수락 param하고 XSS를 확인하기 위해 check_xss()를 호출하여 를 포함하는 URL을 구성합니다 param. 그런 다음 Selenium을 사용하여 이 URL을 읽으려고 시도합니다.
- 안전 param하고 XSS를 트리거하지 않으면 "good"이라는 경고가 표시됩니다. 그렇지 않으면 "wrong??"이 표시됩니다.
### Prevention Measures
To prevent XSS vulnerabilities in a web application, consider the following measures:
1. **Input Validation and Sanitization**:
- Always validate and sanitize user inputs to ensure that they do not contain any executable code.
-
- 항상 사용자 입력을 검증하고 정리하여 실행 가능한 코드가 포함되지 않았는지 확인하세요.
2. **Output Encoding**:
- Encode outputs properly based on the context (HTML, JavaScript, URL, etc.) to prevent browsers from interpreting it as code.
브라우저가 이를 코드로 해석하지 못하도록 컨텍스트(HTML, JavaScript, URL 등)에 따라 출력을 적절히 인코딩합니다.
3. **Content Security Policy (CSP)**:
- Implement a CSP to restrict the sources from which scripts can be loaded.
-
- 스크립트를 로드할 수 있는 소스를 제한하기 위해 CSP를 구현합니다.
- CSP(Content Security Policy)는 웹의 보안을 강화하기 위해 사용하는 HTTP 헤더입니다.
4. **Use Secure Cookies**:
- Mark cookies with `HttpOnly` and `Secure` flags where applicable to reduce the risk of them being accessed via JavaScript.
- JavaScript를 통해 쿠키에 액세스하는 위험을 줄이려면 해당되는 경우 쿠키에 HttpOnly및 플래그를 표시하세요.Secure
5. **Regular Security Audits**:
- Conduct regular security audits and use tools that can help identify XSS vulnerabilities.
- 정기적으로 보안 감사를 실시하고 XSS 취약점을 식별하는 데 도움이 되는 도구를 사용하세요.
흐으으음..일단 홈페이지를 들어가보자
결론적으로 우리가 해야할 것을 정리하면 이거다
flag 페이지에서 xss 파라미터를 조작하여 로컬호스트 환경에서 FLAG가 적힌 쿠키 값이 추가되면, 해당 쿠키값을 memo 페이지의 매개변수로 전달하고 memo 페이지에 FLAG를 작성하도록 한다.
출처:
https://mokpo.tistory.com/59
[MSS:티스토리]
여기 블로그 주인장분이 이 소스코드를 아주 정확하고 세세하게 분석해놓았다. 엄청난 지식과 내공이 느껴지는 글..!
공격 구문은 아래 블로그 글을 참고했다.
https://jhyuxxk.tistory.com/19
DreamHack 1단계 xss-1
DreamHack 1단계 xss-1 문제를 풀어보겠다. 접속을 하면 세 페이지가 나오는데, vuln 함수는 필터링이 없어서 xss 가 가능하다. memo 함수는 flag 에 입력한 값이 성공시 출력되는 페이지이다. 왜냐하면, me
jhyuxxk.tistory.com
'Dreamhack > Dreamhack Wargame (Challenge)' 카테고리의 다른 글
[38] IT 비전공자 [dreamhack]xss-2문제 풀기 (0) | 2024.10.17 |
---|---|
[37] IT 비전공자 [dreamhack]simple_sqli문제 풀기 (0) | 2024.10.16 |
[35] IT 비전공자 [dreamhack]session-basic문제 풀기 (0) | 2024.10.14 |
[34] IT 비전공자 [dreamhack]Broken Password문제 풀기 (0) | 2024.10.13 |
[33] IT 비전공자 [dreamhack]Path Finder문제 풀기 (0) | 2024.10.12 |