Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for root prvileges from the user in Ruby?

Tags:

ruby

sudo

root

I'm trying to write a program that requires root privileges, but whenever it runs it raises an permission error. Is there a better way to run programs as root without entering sudo 'example_script.rb' Also, is there a possibly a way to request `sudo' from inside a ruby script or to check to see if a user is running as sudo when using the program? Thanks!

like image 698
Practical1 Avatar asked Oct 10 '18 19:10

Practical1


2 Answers

You can check with Process.uid:

case (Process.uid)
when 0
  # We're root!
else
  $stderr.puts("You must run this with root privileges via sudo")
end

Remember to be extra super careful when writing scripts that run as root. Consider code like this:

system("convert #{image_path} #{target_path}")

This is a massive security vulnerability because none of the shell arguments are properly escaped.

A safer way:

system("convert", image_path, target_path)

You'll need to ensure that anything and everything you do with any user data of any kind, no matter how carefully you think you've screened it, is treated with extreme suspicion. This is especially true for any operations that can read or write files.

like image 122
tadman Avatar answered Oct 10 '22 12:10

tadman


It's best to ask the user to run the script as root or using sudo than to implicitly try to grab that privilege in the script. Here's an approach that asks the user to run as root or using sudo:

require 'etc'

if Etc.getpwuid.uid != 0
  puts "You need to run this script as root or using sudo"
  exit 1
else
  puts "Running in privileged mode"
  # Do stuff only superuser can do
end
like image 44
Mike Gorski Avatar answered Oct 10 '22 12:10

Mike Gorski