Skip to content

Instantly share code, notes, and snippets.

@andrei-tofan
Created May 13, 2017 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrei-tofan/228c0b4e5bfe5745c799c6024a205fb5 to your computer and use it in GitHub Desktop.
Save andrei-tofan/228c0b4e5bfe5745c799c6024a205fb5 to your computer and use it in GitHub Desktop.
Run node.js express app under a low privilege user
var express = require('express')
var app = express()
/**
* After app starts, demote the app to a low privilege user
*/
function demote() {
if(process.platform != 'linux') {
return false;
}
const userid = require('userid');
const user_id = userid.uid(process.env.PROCESS_USER || 'www-data');
const group_id = userid.gid(process.env.PROCESS_GROUP || 'www-data');
process.setgid(group_id);
process.setuid(user_id);
return true;
}
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000, function () {
// switch to a low privilege user.
demote();
console.log('Example app listening on port 3000!')
})

Notes

The app needs root access only to open the http port, after that it can run under a low privilege user.

Reguirements

The userid module is required to get the user id. Unfortunatly it works only on the linux platform, you will have to add it under optionalDependencies.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment