質問

I'm trying to create a virtual bash in my node script that executes commands from within another user context.

var spawn = require('child_process').spawn;
var terminal = spawn('bash', [], { uid: 1001 });

terminal.stdout.on('data', function (data) {
    console.log('stdout: ' + data);
});

terminal.stderr.on('data', function (data) {
    console.log('stderr: ' + data);
});

terminal.on('close', function (code) {
    console.log('child process exited with code ' + code);
});

terminal.stdin.write('echo Hello $USER');
terminal.stdin.end();

After executing this as root the output allways is

Hello root

As you can see in my example I've passed a user id to the spawn, but this doesn't effect anything.

My desired output is (assumed uid 1001's username is 'foobar'):

Hello foobar

Is there a way to do this in node or even a "fake" where I can start a bash process with given user credentials?

役に立ちましたか?

解決

TL;DR: Your bash instance has in fact the permission of your foobar user, and the code you wrote is correct.

You can confirm this behavior if you run the following command, instead of bash:

terminal       = spawn('id', ['-a'], { uid: 1001 });

which should output this:

stdout: uid=1001(foobar)

Which you can compare to a standard child spawn, without the uid parameter:

terminal       = spawn('id', ['-a']);

which outputs:

stdout: uid=0(root)

Here is the relevant explanation, according to this question:

bash detects that it has been started SUID root (UID!=EUID) and uses its root power to throw this power away, resetting EUID to UID.

which means that when bash starts, it's SUID is root, and then it sets its USER variable to root. Only after that does it uses setuid.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top