Ruby Sudo

Give Ruby objects superuser privileges.

Based on dRuby and sudo.

Only tested with MRI 1.9 .

REQUIREMENTS

Your user must be allowed, in /etc/sudoers, to run ruby and kill commands as root.

A password will be required from the console, or not, depending on the NOPASSWD options in /etc/sudoers.

USAGE

DSL style

require 'fileutils'
require 'sudo'

include Sudo::DSL

# The String will be passed as options to sudo-ed Ruby interpreter
sudo_start "-rfileutils"

# only readable by root
puts sudo(File).read '/etc/shadow'

# write into the / 
sudo(FileUtils).mkdir_p '/TEST_DIR/SUB_DIR' 

# Stop the dRuby server (whish is running as root), as soon as you can
sudo_stop

Explicit creation of a Wrapper object, block given

require 'fileutils'
require 'sudo'

Sudo::Wrapper.run('-rfileutils) do |su|
  # here you use square brackets [] :
  # su is an object, not a (top-level) method.
  su[FileUtils].mkdir_p '/ONLY/ROOT/CAN/DO/THAT'
end
# Sockets and processes are closed automatically when the block exits

Explicit creation of a Wrapper object, without block

require 'mygem/myclass'
require 'sudo'

obj   = MyGem::MyClass.new

sudo  = Sudo::Wrapper.new(-rmygem/myclass -rmygem/myclass2)

sudo.start!

sudo[obj].method # will be run as root (well, a sudo-ed copy) 

# when you've done:
sudo.stop!

PRINCIPLES OF OPERATION

Spawns a sudo-ed Ruby process running a DRb server. Communication is done via a Unix socket (and, of course, permissions are set to 0600).

No long-running daemons involved, everything is created on demand.

Access control is entirely delegated to sudo.

TODO

  • sudo has a -A option to accept password via an external program (maybe graphical): support this feature.

  • more options in Sudo::Wrapper.new, maybe a Hash.

THANKS

Thanks to Tony Arcieri and Brian Candler for suggestions on ruby-talk.

AUTHOR

Copyright © 2010 Guido De Rosa.

Sponsored by VEMAR s.a.s.

LICENSE

Ruby’s.