I am looking for a way to drop process privileges and get them back after doing some operations. Usually it is done using the setresuid
system call, here is an example in Python, however it also works in C, Rust, Ruby & Go:
#!/usr/bin/env python3
# run this as root (i.e. through sudo)
import os
# switch to userid 1000
os.setresuid(1000, 1000, -1)
os.system("id")
# switch back to root
os.setresuid(0, 0, -1)
os.system("id")
As of Node 17, I could not find the setresuid
calls required in the API docs. Did I miss something or does Node just not implement those calls?
If so, is there another way to drop privileges and them back?
My current approach is simply doing the following, yet it will throw an EPERM error when I try to get back my root privileges...
#!/usr/bin/env node
// Note: Run with root privileges.
// Note: This does NOT work.
const process = require('process')
const { spawn } = require('child_process')
const gid = 1000
const uid = 1000
if (process.getuid && process.setuid) {
console.log(`Current uid: ${process.getuid()}`)
try {
process.seteuid(uid)
process.setuid(uid)
console.log(`New uid: ${process.getuid()}`)
} catch (err) {
console.log(`Failed to set uid: ${err}`)
}
try {
process.seteuid(0) // order does not matter here,
process.setuid(0) // won't work, no matter what's first.
console.log(`New uid: ${process.getuid()}`)
} catch (err) {
console.log(`Failed to set uid: ${err}`)
}
}