简体   繁体   English

在 Express 中拒绝访问 server.js

[英]Denying access to server.js in Express

I'm currently building a app which will be used in a production environment and I'm using Node & Express for that.我目前正在构建一个将在生产环境中使用的应用程序,为此我正在使用 Node & Express。

My concern is about the static file serving that I'm doing, because the server runs in the same directory ( dist/ ) with the command node server.js .我关心的是我正在做的静态文件服务,因为服务器与命令node server.js在同一目录 ( dist/ ) 中运行。

Obviously someone just could do <url>/server.js and Express will happily return the whole content of the file, which is not good for security, of course.显然有人可以做<url>/server.js并且 Express 会很乐意返回文件的全部内容,这当然不利于安全。

I've now implemented a basic check which should deny the access to this file, like so:我现在已经实现了一个基本检查,它应该拒绝访问这个文件,如下所示:

[...]

function denyServerJSAccess(req, res, next) {      
  if (req.originalUrl.indexOf('server.js') > -1) {
    console.log("Denied access")
    return res.sendStatus(403);
  } else {
    return next();
  }      
}
app.use(denyServerJSAccess);
app.use(express.static(__dirname + ""));

[...]

But is this sufficient?但这足够了吗?

Can a targeted attacked maybe craft a character that bypasses indexOf , but let's Express serve the file?目标攻击者能否制作一个绕过indexOf的字符,但让我们快速提供文件? That won't be any good, if yes.如果是的话,那不会有任何好处。

I've seen so many tricks in the past that people use to get around basic protections that I'm a little bit concerned, as this probably is a basic protection.过去我见过很多人们用来绕过基本保护的技巧,我有点担心,因为这可能基本保护。

What should I do in order to protect such files?我应该怎么做才能保护这些文件?

Thanks in advance.提前致谢。

There are two things here, first the line这里有两件事,第一行

app.use(express.static(__dirname + ""));

would expose everything that's in the directory server.js is in (this is probably your root directory).将公开目录server.js中的所有内容(这可能是您的根目录)。 So you would like to limit the path to所以你想限制路径

app.use(express.static(__dirname + '/path/to/public/resources'));

And secondly, put public resources only under path/to/public/resources .其次,将公共资源仅放在path/to/public/resources

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM