Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTPS redirection for all routes node.js/express - Security concerns

I recently took a stab at setting up HTTPS on a node/express server. I have successfully managed to redirect all the routes to use https using the code below:

// force https redirect
var https_redirect = function(req, res, next) {
  if (req.secure) {
    if(env === 'development') {
      return res.redirect('https://localhost:3000' + req.url);
    } else {
      return res.redirect('https://' + req.headers.host + req.url);
    }
  } else {
    return next();
  }
};

app.get('*', function(req, res, next) {
  https_redirect(req, res, next);
});

This seems to be working fine. However, since I havent' dabbled into this before I have a couple of questions:

  1. Is this the ideal way to redirect from http to https?
  2. If a user uses the http route, prior to the redirect is it possible for anyone to use something like sslstrip to sniff out session info.

node: v0.8.2 ; express: v3.05

like image 959
los7world Avatar asked Apr 04 '13 14:04

los7world


2 Answers

function requireHTTPS(req, res, next) {
    if (!req.secure) {
        //FYI this should work for local development as well
        return res.redirect('https://' + req.get('host') + req.url);
    }
    next();
}

app.use(requireHTTPS);
app.get('/', routeHandlerHome);

The middleware approach will work because express will run the middleware in the order added, before it runs the router, and in general this kind of site-wide policy is cleaner as middleware vs. a wildcard route.

Regarding question 2 about sniffing session cookies, that must be addressed by marking the cookies as secure when you set them. If they haven't been marked secure, the browser will transmit them with HTTP requests as well, thus exposing them to sniffing.

like image 67
Peter Lyons Avatar answered Nov 01 '22 02:11

Peter Lyons


You can simply use your https_redirect function (though a bit modified) as a to automatically redirect all of your secure requests:

// force https redirect
var https_redirect = function () {
  return function(req, res, next) {
    if (req.secure) {
      if(env === 'development') {
        return res.redirect('https://localhost:3000' + req.url);
      } else {
        return res.redirect('https://' + req.headers.host + req.url);
      }
    } else {
      return next();
    }
  };
};
app.use(https_redirect());

app.get('/', routeHandlerHome);
like image 25
red Avatar answered Nov 01 '22 03:11

red