Prevent unsafe redirects

One Paragraph Explainer

When redirects are implemented in Node.js and/or Express, it’s important to perform input validation on the server-side. If an attacker discovers that you are not validating external, user-supplied input, they may exploit this vulnerability by posting specially-crafted links on forums, social media, and other public places to get users to click it.

Example: Unsafe express redirect using user input

  1. const express = require('express');
  2. const app = express();
  3. app.get('/login', (req, res, next) => {
  4. if (req.session.isAuthenticated()) {
  5. res.redirect(req.query.url);
  6. }
  7. });

The suggested fix to avoid unsafe redirects is to avoid relying on user input. If user input must be used, safe redirect whitelists can be used to avoid exposing the vulnerability.

Example: Safe redirect whitelist

  1. const whitelist = {
  2. 'https://google.com': 1
  3. };
  4. function getValidRedirect(url) {
  5. // check if the url starts with a single slash
  6. if (url.match(/^\/(?!\/)/)) {
  7. // Prepend our domain to make sure
  8. return 'https://example.com' + url;
  9. }
  10. // Otherwise check against a whitelist
  11. return whitelist[url] ? url : '/';
  12. }
  13. app.get('/login', (req, res, next) => {
  14. if (req.session.isAuthenticated()) {
  15. res.redirect(getValidRedirect(req.query.url));
  16. }
  17. });

What other bloggers say

From the blog by NodeSwat:

Fortunately the mitigation methods for this vulnerability are quite straightforward — don’t use unvalidated user input as the basis for redirect.

From the blog by Hailstone

However, if the server-side redirect logic does not validate data entering the url parameter, your users may end up on a site that looks exactly like yours (examp1e.com), but ultimately serves the needs of criminal hackers!