如何限制节点对内部节点模块的访问

How do I limit the node repl's access to internal node modules?

本文关键字:模块 访问 内部节点 何限制 节点      更新时间:2023-09-26

在上一个问题中,我想出了如何从repl上下文中消除不需要的全局变量。但是,我发现 repl 可以在不使用 require 的情况下自动访问所有内部节点模块。我不知道如何禁用它。我什至尝试覆盖 repl 本身中的模块变量,但它不起作用。

> fs = "测试";
>

它仍显示fs原始值。这是非常不幸的,因为我正在尝试公开一个公共 repl,但它允许他们访问整个服务器。

有什么想法吗?

正如你所说,REPL可以访问核心模块。

(但是,经过检查,我能够用节点 0.10.20 覆盖它们,所以应该有一个解决方案)

> fs
> { Stats: [Function], …
> fs = 'hello';
> fs
'hello'

更好的方法是在创建 repl 实例之前覆盖repl._builtinLibs

var repl = require('repl');
repl._builtinLibs = [];
repl.start('> ');

此外,如果您不想公开 .save.load 等命令,将 repl 命令列入白名单是相当简单的。

var allowedReplCmds = ['.break', '.clear', '.help'];
var newRepl = repl.start('> ');
for (var key in newRepl.commands)
    if (!allowedReplCmds.contains(key))
        delete replInstance.commands[key];

注意:数组通常没有contains方法,所以我添加了一个。

Array.prototype.contains = function(v) {
    for(var i = 0; i < this.length; i++) {
        if(this[i] === v) return true;
    }
    return false;
};

如果要从 repl 实例的全局范围中删除变量,请参阅此问题。


请注意,向公众公开 REPL 是非常不安全的。

您可以轻松地使整个服务器崩溃

> setTimeout(function () { throw 'bye bye!'; }, 0);

REPL 不会捕获异步回调中发生的错误,并导致节点.js实例关闭。

您可以阻止服务器

> while(true) {};

最好的办法是使用 child_process、readline 和 vm 在单独的进程中编写自己的 REPL。这是一个起点:

师傅:

// master.js
var fork = require('child_process').fork;
// functions exposed to the repl
var replApi = {
  hello: function () {
    return 'world!';
  },
  unknown: function () {
    return 'unknown';
  }
};
function forkRepl() {
  var repl = fork('./child_repl');
  repl.on('message', function (command) {
    var fun = replApi[command] || replApi.unknown;
     repl.send(fun());
  });
  // restart the repl if it dies
  repl.on('exit', forkRepl);
}
forkRepl();

以及 repl 的单独流程:

// child_repl.js
var readline = require('readline'),
    vm = require('vm');
var context = vm.createContext({
  hello: function () {
    process.send('hello');
  }
});
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
rl.on('line', function (line) {
  vm.runInContext(line, context, 'repl.vm');
});
process.on('message', function (message) {
  console.log('master:', message);
});
rl.prompt();