bsdcapsicum.rb/lib/capsicum.rb

81 lines
1.7 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
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
2024-06-25 03:48:14 +02:00
##
# 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
2024-06-25 03:48:14 +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
2024-06-25 03:48:14 +02:00
##
# @api private
def libc
@libc ||= Fiddle.dlopen Dir["/lib/libc.*"].first
end
2017-05-24 02:18:47 +02:00
end
2024-06-25 03:48:14 +02:00
module_function
##
2017-05-24 17:33:39 +02:00
# Check if we're in capability mode.
#
# @see cap_getmode(2)
2024-06-25 03:48:14 +02:00
# @raise [SystemCallError]
# Might raise a subclass of SystemCallError
# @return [Boolean]
# Returns true if the current process is in capability mode
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
2024-06-25 03:40:37 +02:00
alias_method :capability_mode?, :sandboxed?
2017-05-24 02:18:47 +02:00
2024-06-25 03:48:14 +02:00
##
# Enter capability mode
2017-05-24 17:33:39 +02:00
#
# @see cap_enter(2)
2024-06-25 03:48:14 +02:00
# @raise [SystemCallError]
# Might raise a subclass of SystemCallError
# @return [Boolean]
# Returns true when the current process is in capability mode
2017-05-24 02:18:47 +02:00
def enter!
2024-06-25 03:48:14 +02:00
if LibC.cap_enter == 0
true
2017-05-24 02:18:47 +02:00
else
raise SystemCallError.new("cap_enter", Fiddle.last_error)
2017-05-24 02:18:47 +02:00
end
end
2017-05-24 02:18:05 +02:00
end