Change even more code in "How to create static HTTP server in Node.JS" article

This commit is contained in:
Dorian Niemiec 2024-03-31 18:09:19 +02:00
parent 1bb02da4fc
commit 99c08a5aa7

View file

@ -146,8 +146,8 @@ But we have introduced path traversal vulnerability! (being able to access file
var port = 8080;
var server = http.createServer(function (req, res) {
var filename = "." + req.url;
filename = filename.replace(/\\/g,"/").replace(/\/\.\.?(?=\/|$)/g,"").replace(/\/+/g,"/"); //Poor mans URL sanitizer
if(req.url == "/") filename = "./index.html";
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") {
@ -184,8 +184,8 @@ That might work fine for HTML files, but if you try other files, there will be c
var port = 8080;
var server = http.createServer(function (req, res) {
var filename = "." + req.url;
filename = filename.replace(/\\/g,"/").replace(/\/\.\.?(?=\/|$)/g,"").replace(/\/+/g,"/"); //Poor mans URL sanitizer
if(req.url == "/") filename = "./index.html";
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) {
@ -224,8 +224,8 @@ But with query strings, it will fail. To prevent that, we'll be using WHATWG URL
var server = http.createServer(function (req, res) {
var urlObject = new URL(req.url, "http://localhost");
var filename = "." + urlObject.pathname;
filename = filename.replace(/\\/g,"/").replace(/\/\.\.?(?=\/|$)/g,"").replace(/\/+/g,"/"); //Poor mans URL sanitizer
if(req.url == "/") filename = "./index.html";
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) {
@ -274,8 +274,8 @@ It's nearly finished! But encoded URLs will not work. To fix that, we will use `
res.end("400 Bad Request");
return;
}
filename = filename.replace(/\\/g,"/").replace(/\/\.\.?(?=\/|$)/g,"").replace(/\/+/g,"/"); //Poor mans URL sanitizer
if(req.url == "/") filename = "./index.html";
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) {