Buy

JavaScript for PHP Geeks: ReactJS (with Symfony)

0%
Buy

With a Subscription, click any sentence in the script to jump to that part of the video!

Login Subscribe

We've gotta talk about one more thing: security. Specifically, CSRF attacks.

CSRF Attack?

Imagine if a malicious person built an HTML form on a totally different site, but set its action="" attribute to a URL on our site. Then, what if some user, like me, who is logged into our site, was tricked into submitting that form? Well, the form would submit, I would of course be authenticated, and the request would be successful! That's a problem! The malicious user was basically able to make a request to our site logged in as me! They could have done anything!

The other possible attack vector is if a malicious user runs JavaScript on their site that makes an AJAX call to our site. The result is exactly the same.

Do APIs Need Protection?

So, how can we protect against this in an API? The answer... you might not need to. If you follow two rules, then CSRF attacks are not possible.

Tip

Update: While this section may be true - especially if you add a CORS same-origin policy, relying on the Content-Type for CSRF protection is not recommended: new browsers may (and have) introduced new features that make this protection incomplete. The best practice is to use CSRF tokens, as we'll show!

First, disallow AJAX requests from all domains except for your domain. Actually, this is just how the Internet works: you can't make AJAX requests across domains. If you do need to allow other domains to make AJAX requests to your domain, you do that by setting CORS headers. If you're in this situation, just make sure to only allow specific domains you trust, not everyone. This first rule prevents bad AJAX calls.

For the second rule, look at our API: src/Controller/RepLogController. Find newRepLogAction(). Notice that the body of the request is JSON. This is the second rule for CSRF protection: only allow data to be sent to your server as JSON. This protects us from, for example, bad forms that submit to our site. Forms cannot submit their data as JSON.

If you follow these two rules - which you probably do - then you do not need to worry about CSRF. But, to be fully sure, we are going to add one more layer: we're going to force all requests to our API to have a Content-Type header set to application/json. By requiring that, there is no way for a bad request to be made to our site, unless we're allowing it with our CORS headers.

Oh, and important side note: CSRF attacks only affect you if you allow session-based authentication like we're doing, or HTTP basic authentication. If you require an API token, you're also good!

Creating the Event Susbcriber

We're going to require the Content-Type header by creating an event subscriber, so that we don't need to add this code in every controller. First, to speed things up, install MakerBundle:

composer require maker --dev

When that finishes, run:

php bin/console make:subscriber

Call it ApiCsrfValidationSubscriber. And, listen to the kernel.request event. Done! This made one change: it created a new class in src/EventSubscriber.

... lines 1 - 7
class ApiCsrfValidationSubscriber implements EventSubscriberInterface
{
public function onKernelRequest(GetResponseEvent $event)
{
// ...
}
public static function getSubscribedEvents()
{
return [
'kernel.request' => 'onKernelRequest',
];
}
}

Awesome! Because we're listening to kernel.request, the onKernelRequest() method will be called on every request, before the controller. At the top of the method, first say if !$event->isMasterRequest(), then return. That's an internal detail to make sure we only run this code for a real request.

... lines 1 - 9
public function onKernelRequest(GetResponseEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
... lines 15 - 21
}
... lines 23 - 31

Next, we do not need to require the Content-Type header for safe HTTP methods, like GET or HEAD, because, unless we do something awful in our code, these requests don't change anything on the server. Add $request = $event->getRequest(). Then, if $request->isMethodSafe(false), just return again.

... lines 1 - 15
$request = $event->getRequest();
// no validation needed on safe methods
if ($request->isMethodSafe(false)) {
return;
}
... lines 22 - 31

The false part isn't important: that's a flag for a backwards-compatibility layer.

Perfect! Next, we need to determine whether or not this request is to our api. We'll do that with a cool annotation trick. Then, we'll make sure the Content-Type header is set to application/json.

Leave a comment!

  • 2019-04-29 weaverryan

    Hey Patrice Duchamps !

    Just an update on this. Someone else pointed out that these protections ay in fact *not* be enough as browsers have introeduced a feature (https://github.com/pillarjs... that indeed may allow application/json requests to be sent across JavaScript without preflight :/. And more broadly, browsers seem to think that relying on this is not sufficient. We're adding a note about this, and so, indeed, using CSRF tokens is best. We show how in this tutorial and there is also the wonderful bundle you linked to: https://github.com/dunglas/...

    Cheers!

  • 2019-04-19 Patrice Duchamps

    Hi Ryan,

    I have now re-read your post as well as your answer.

    > From my perspective, the protection is a combination of (A) disallowing cross-domain via XHR... which only leaves GET requests and POST requests initiated by a form. AND then (B) checking always for application/json Content-Type, which eliminates the form request.

    Yes, yes and yes, not sure what was happening inside my head. I forgot preflight requests would fire on cross-origin POST request WHEN Content-Type is 'application/json' (more precisely when it is NOT one of application/x-www-form-urlencoded, multipart/form-data, or text/plain). I totally forgot about preflight... thank you!

    So, yes, everything makes a lot of sense... apologies for the confusion and thank you so much for being so awesome.

    Based on my very first point, I would still rephrase the following:

    > First, disallow AJAX requests from all domains except for your domain. Actually, this is just how the Internet works: you can't make AJAX requests across domains.

    into the following:

    --> First, disallow AJAX requests from all domains except for your domain. Actually, this is just how the Internet works: you can't make AJAX requests across domains WHEN CONTENT-TYPE IS NOT ONE OF application/x-www-form-urlencoded, multipart/form-data, or text/plain.

    Because, technically, it is possible to send cross-origin POST XHR requests with any of these 3 content-types and even if you can't read the response, you can mutate state. I.e. there is no preflight for these as they are Simple Requests:
    https://developer.mozilla.o...

    P.S. For those that would still would want to submit via `application/x-www-form-urlencoded`, I found the DunglasAngularCsrfBundle after some digging!
    https://github.com/dunglas/...

  • 2019-04-16 weaverryan

    Hey Patrice Duchamps!

    Thanks for the post - seriously :). This was a tough chapter because it's security-related and I wanted to get it right. Now, I *really* want to make sure that I've got it right, with your help. So, I have a few questions:

    > However SOP is designed to prevent websites from reading credentialed responses from a third party but not to prevent from posting data. It is possible to mutate state on another website via XHRs without any problem

    How? I mean, I know one way: via form posts, which could be on the bad domain with an action=http://thegoodomain.example or even with the good domain form hidden in an iframe on the bad domain. But, there is no other way to make a request via XHR, or JSONP (other than a GET request) to another domain, unless that domain has allowed it via CORS, right?

    > The way data is represented is nothing to do with CSRF protection - using json does not protect users further. The risk here comes from the session-based authentication. An authenticated POST is an authenticated POST.. the way the data is represented is irrelevant for a CSRF defense.

    Actually, that's not entirely true :). As I mentioned above, there IS certainly an attack vector to make a POST request to another domain using a traditional HTML. But, HTML forms *always* submit with Content-Type: application/x-www-form-urlencoded or Content-Type: multipart/form-data. There is no way for the "bad" domain to add a form to their site and change this fact. So, if *our* API *always* checks for the Content-Type to be application/json (or really, *anything* other than the 2 that could be sent by a form), then it eliminates the CSRF attack from an embedded form.

    Let me know what you think or what I'm not thinking about. From my perspective, the protection is a combination of (A) disallowing cross-domain via XHR... which only leaves GET requests and POST requests initiated by a form. And then (B) checking always for application/json Content-Type, which eliminates the form request. The only thing remaining are GET requests from other domains, which is safe because the attacker can't read the response (assuming, of course, that you haven't done something crazy and "mutated" your server on a GET request). Here's a source I was referencing for this section: https://github.com/pillarjs...

    Cheers!

  • 2019-04-15 Patrice Duchamps

    Hi Ryan,

    I hope you’re excellent, it’s been a long time.

    We need to be careful here because I feel the information mentioned here is misguiding:

    > First, disallow AJAX requests from all domains except for your domain. Actually, this is just how the Internet works: you can't make AJAX requests across domains.

    It seems you are referring to the same-origin policy. However SOP is designed to prevent websites from reading credentialed responses from a third party but not to prevent from posting data. It is possible to mutate state on another website via XHRs without any problem, SOP only makes it impossible to read the response. Yes, we can make cross domain XHR requests, we are just not allowed to read responses (depending on the CORS policy in place). It is also possible to make that XHR credentialed using ‘withCredentials: true’.
    So here, with current tuto in place, we are subject to CSRF attacks.

    > This is the second rule for CSRF protection: only allow data to be sent to your server as JSON.

    The way data is represented is nothing to do with CSRF protection - using json does not protect users further. The risk here comes from the session-based authentication. An authenticated POST is an authenticated POST.. the way the data is represented is irrelevant for a CSRF defense.

    Protecting SPA against CSRF and XSS attacks is not easy, but here I believe both points would misguide users in thinking they are protected when they would not be.

    Just a heads up!

    P.S. I think it would be helpful to a lot of people if you covered a safe login authentication for an SPA which would be immune to CSRF login attacks, this is not easy to do, whether one uses session based authentication OR token based authentication.