From c31d6fad25218ba4654df5e6fec01e9be86c1267 Mon Sep 17 00:00:00 2001 From: achingbrain Date: Mon, 3 Mar 2014 19:22:49 +0000 Subject: [PATCH 1/2] adds option to switch to a different user/group before starting a managed process --- bin/pm2 | 2 ++ lib/CLI.js | 4 ++++ lib/ProcessContainer.js | 10 ++++++++++ 3 files changed, 16 insertions(+) diff --git a/bin/pm2 b/bin/pm2 index 3f43f77c..dc31c03e 100755 --- a/bin/pm2 +++ b/bin/pm2 @@ -38,6 +38,8 @@ commander.version(pkg.version) function(val) { return val.split(' '); }) + .option('--run-as-user ', 'The user or uid to run a managed process as') + .option('--run-as-group ', 'The group or gid to run a managed process as') .usage('[cmd] app'); // diff --git a/lib/CLI.js b/lib/CLI.js index 448e39b4..237a5812 100644 --- a/lib/CLI.js +++ b/lib/CLI.js @@ -43,6 +43,10 @@ CLI.startFile = function(script) { appConf['pid_file'] = commander.pid; if (commander.cron) appConf['cron_restart'] = commander.cron; + if (commander.runAsUser) + appConf['run_as_user'] = commander.runAsUser; + if (commander.runAsGroup) + appConf['run_as_group'] = commander.runAsGroup; if (commander.executeCommand) appConf['exec_mode'] = 'fork_mode'; diff --git a/lib/ProcessContainer.js b/lib/ProcessContainer.js index 3bcdfb46..41d56c75 100644 --- a/lib/ProcessContainer.js +++ b/lib/ProcessContainer.js @@ -119,6 +119,16 @@ function exec(script, outFile, errFile) { } }); + // if we've been told to run as a different user or group (e.g. because they have fewer + // privileges), switch to that user before importing any third party application code. + if (process.env.run_as_group) { + process.setgid(process.env.run_as_group); + } + + if (process.env.run_as_user) { + process.setuid(process.env.run_as_user); + } + // Get the script & exec require(script); }); From af0caec104297674f0432e4df2b49e15af0c469b Mon Sep 17 00:00:00 2001 From: achingbrain Date: Tue, 4 Mar 2014 11:06:32 +0000 Subject: [PATCH 2/2] adds documentation for --run-as-user and --run-as-group --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 3a729489..e6b82b94 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,10 @@ $ pm2 start app.json # Start processes with options declared in a $ pm2 start app.js -i max -- -a 23 # Pass arguments after -- to app.js $ pm2 start app.js -i max -e err.log -o out.log # Will start and generate a configuration file + +$ pm2 --run-as-user foo start app.js # Start app.js as user foo instead of root (pm2 must be running as root) + +$ pm2 --run-as-user foo --run-as-group bar start app.js # Start app.js as foo:bar instead of root:root (pm2 must be running as root) ``` You can also execute app in other languages ([the fork mode](#a23)):