Search code examples
javascripthtmlsecuritycsrfcsrf-protection

What is the sense of the CSRF-protection while using token in HTML


I'm new to the cybersecurity and CSRF.

I've read the most popular way of the CSRF-protection is placing the CSRF-token in HTML form or in the META tag for reading it in JavaScript for AJAX-actions.

But I don't understand what the sense of the hacker who use data from cookies at different sites can read the value of the CSRF token in HTML and use it sending a request to the site where the user logged in.

Explain it for me, please.


Solution

  • CSRF Token are invented to prevent actions on the server from outside of the ecosystem.

    In the web world, prevent posting a form (it can be any other action on the server) from out of the original site.

    You are asking how, so the simple technique to put hidden field inside the form with some generated token that the server can ensure that the Post request that it got came from the site's form and not from other place.

    For example, if I'm an attacker and your form doesn't has such a token I can create a form on my site that the action field will point to you server location.

    <form method="POST" action="http://your-site.com/transfer-mony.php">
       <input type="text" name="amount" value="100000" />
       <button>submit</button>
    </form>
    

    If you have a token and you server will validate it on each request, my post from my form will be rejected.

    So you asking, OK, I can go to the original site and copy that token, and that is it.

    So, basically, token should be a one time thing, they valid only for the next user action. Token can contain an user IP, and signed with private key, then if you copy my token to you, the server will reject the request, because the IP that within the token is not aligned with the IP of the client that sent the request.

    JWT, is one of those techniques

    The more common practice today (thanks to Angular), is that the server return a Cookie with the token, and the next request must have it on the Headers of the request.

    Pay attention, you your site has an XSS vulnerability you can basically bypass all CSRF mechanisms.

    I hope it was understandable, if not, you can ask at the comments.