Search code examples
rubyrootsudo

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


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!


Solution

  • 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.