bsdcapsicum.rb/lib/capsicum.rb

92 lines
2 KiB
Ruby
Raw Normal View History

2017-05-24 02:18:05 +02:00
require "capsicum/version"
require "fiddle"
2017-05-24 02:18:05 +02:00
module Capsicum
# @api private
2017-05-24 02:18:47 +02:00
module LibC
module_function
# Provides a Ruby interface for cap_enter(2)
# @return [Integer]
def cap_enter
Fiddle::Function.new(
libc["cap_enter"],
[],
Fiddle::Types::INT
).call
end
2017-05-24 02:18:47 +02:00
# Provides a Ruby interface for cap_getmode(2)
# @param [Fiddle::Pointer] uintp
# @return [Integer]
def cap_getmode(uintp)
Fiddle::Function.new(
libc["cap_getmode"],
[Fiddle::Types::INTPTR_T],
Fiddle::Types::INT
).call(uintp)
end
2017-05-24 02:18:47 +02:00
def libc
@libc ||= Fiddle.dlopen Dir["/lib/libc.*"].first
end
2017-05-24 02:18:47 +02:00
end
2017-05-24 17:33:39 +02:00
# Check if we're in capability mode.
#
# @see cap_getmode(2)
#
# @return [Boolean] true if we've entered capability mode
# @raise [Errno::ENOTCAPABLE] - Capsicum not enabled.
2017-05-24 02:18:47 +02:00
def sandboxed?
uintp = Fiddle::Pointer.malloc(Fiddle::SIZEOF_UINT)
ret = LibC.cap_getmode(uintp)
2017-05-24 02:18:47 +02:00
if ret == 0
uintp[0, Fiddle::SIZEOF_UINT].unpack('i') == [1]
2017-05-24 02:18:47 +02:00
else
raise SystemCallError.new("cap_getmode", Fiddle.last_error)
2017-05-24 02:18:47 +02:00
end
ensure
uintp.call_free
2017-05-24 02:18:47 +02:00
end
2017-05-24 17:33:39 +02:00
# Enter capability sandbox mode.
#
# @see cap_enter(2)
#
# @return [Boolean] true if we've entered capability mode.
# @raise [Errno::ENOTCAPABLE] - Capsicum not enabled.
2017-05-24 02:18:47 +02:00
def enter!
ret = LibC.cap_enter
if ret == 0
return true
else
raise SystemCallError.new("cap_enter", Fiddle.last_error)
2017-05-24 02:18:47 +02:00
end
end
2017-05-24 17:33:39 +02:00
# Run the block within a forked process in capability mode and wait for it to
# complete.
#
# @yield block to run within the forked child.
# @return [Process::Status] exit status of the forked child.
2017-05-24 02:18:47 +02:00
def within_sandbox
raise NotImplementedError, "fork() not supported" unless Process.respond_to? :fork
2017-05-24 02:18:47 +02:00
return enum_for(:within_sandbox) unless block_given?
pid = fork do
Capsicum.enter!
yield
end
Process.waitpid2(pid).last
end
module_function :sandboxed?
module_function :enter!
module_function :within_sandbox
2017-05-24 02:18:05 +02:00
end