Change regular expression for "poor mans" URL sanitizer

This commit is contained in:
Dorian Niemiec 2024-03-31 17:59:15 +02:00
parent eac2bc9799
commit 1bb02da4fc

View file

@ -147,7 +147,7 @@ But we have introduced path traversal vulnerability! (being able to access file
var server = http.createServer(function (req, res) {
var filename = "." + req.url;
if(req.url == "/") filename = "./index.html";
filename = filename.replace(/\\/g,"/").replace(/(?:\/|^)\.\.(?=(\/|$))/g,"$1").replace(/\/+/g,"/"); //Poor mans URL sanitizer
filename = filename.replace(/\\/g,"/").replace(/(?:\/|^)\.\.?(?=(\/|$))/g,"$1").replace(/\/+/g,"/"); //Poor mans URL sanitizer
fs.readFile(filename, function(err, data) {
if(err) {
if(err.code == "ENOENT") {
@ -185,7 +185,7 @@ That might work fine for HTML files, but if you try other files, there will be c
var server = http.createServer(function (req, res) {
var filename = "." + req.url;
if(req.url == "/") filename = "./index.html";
filename = filename.replace(/\\/g,"/").replace(/(?:\/|^)\.\.(?=(\/|$))/g,"$1").replace(/\/+/g,"/"); //Poor mans URL sanitizer
filename = filename.replace(/\\/g,"/").replace(/(?:\/|^)\.\.?(?=(\/|$))/g,"$1").replace(/\/+/g,"/"); //Poor mans URL sanitizer
var ext = path.extname(filename).substr(1); //path.extname gives "." character, so we're using substr(1) method.
fs.readFile(filename, function(err, data) {
if(err) {
@ -225,7 +225,7 @@ But with query strings, it will fail. To prevent that, we'll be using WHATWG URL
var urlObject = new URL(req.url, "http://localhost");
var filename = "." + urlObject.pathname;
if(req.url == "/") filename = "./index.html";
filename = filename.replace(/\\/g,"/").replace(/(?:\/|^)\.\.(?=(\/|$))/g,"$1").replace(/\/+/g,"/"); //Poor mans URL sanitizer
filename = filename.replace(/\\/g,"/").replace(/(?:\/|^)\.\.?(?=(\/|$))/g,"$1").replace(/\/+/g,"/"); //Poor mans URL sanitizer
var ext = path.extname(filename).substr(1); //path.extname gives "." character, so we're using substr(1) method.
fs.readFile(filename, function(err, data) {
if(err) {
@ -275,7 +275,7 @@ It's nearly finished! But encoded URLs will not work. To fix that, we will use `
return;
}
if(req.url == "/") filename = "./index.html";
filename = filename.replace(/\\/g,"/").replace(/(?:\/|^)\.\.(?=(\/|$))/g,"$1").replace(/\/+/g,"/"); //Poor mans URL sanitizer
filename = filename.replace(/\\/g,"/").replace(/(?:\/|^)\.\.?(?=(\/|$))/g,"$1").replace(/\/+/g,"/"); //Poor mans URL sanitizer
var ext = path.extname(filename).substr(1); //path.extname gives "." character, so we're using substr(1) method.
fs.readFile(filename, function(err, data) {
if(err) {