shouya
shouya

Reputation: 3083

Call a function with root's permission in ruby?

I know in shell script I can do this:

#!/bin/sh

foo() {
    rm -rf /
}

foo # fail
sudo foo # succeed

For implementing this in ruby, I now use a individual script file to store those operations that need root privileges, and then call in the main script like system(['sudo', 'ruby', 'sudo_operations.rb', 'do_rm_rf_root']).

It would be much better if I can directly invoke the function without separating it out. For example, I wonder something like this:

def sudo(&method_needs_root_privilege)
    # ...
end

Then I can use that like:

sudo do
    puts ENV['UID'] # print 0
    system('rm -rf /') # successfully executed
end

Is there any gems that helps or any idea for implementing this?

Thanks in advance.

Upvotes: 1

Views: 339

Answers (1)

user149341
user149341

Reputation:

No. UID/GID only exist at the process level; functions cannot run as a different user (e.g, root) from the rest of a process.

While it is possible for a process to change its uid (using the set*id family of system calls), a process must already be running as root to do so.

Upvotes: 2

Related Questions