krakenjs / lusca

Application security for express apps.
Other
1.78k stars 123 forks source link

CSRF Hooks #63

Open uptownhr opened 9 years ago

uptownhr commented 9 years ago

Is there a way to hook into to when a CSRF returns 404? I'd like to check in on the IP of the originating server to see if I can just block them.

jasisk commented 9 years ago

When csrf fails, we put an error into the typical express error handling pipeline. Feel free to read up on it in the express guide about error handling.

You could register a new error-handling middleware that does what you want. Something like this:

// ./lib/logCsrf.js
module.exports = function logCsrfFailuresGenerator() {
  return function logCsrfFailures(err, req, res, next) {
    if (res.statusCode === 403 && /csrf/i.test(err.message)) {
      // ... csrf failure -- do your logging here ...
    }
    next(err); // don't forget to proceed with the continuation!
  };
}

Then, in your config:

{
  // ...
  "middleware": {
    // ...
    "logCsrfFailures": {
      "enabled": true,
      "priority": 139, // just make sure it's before any error handlers that render!
      "module": "path:./lib/logCsrf"
    }
  }
}