Restricted Execution

Ruby can execute programs with security checking turned on. The global variable $SAFE determines the level of the security check. The default safe level is 0, unless specified explicitly by the command-line option -T, or the Ruby script is run setuid or setgid.

$SAFE can be altered by assignment, but it isn’t possible to lower the value of it:

$SAFE=1                # upgrade the safe level
$SAFE=4                #  upgrade the safe level even higher
$SAFE=0                # SecurityError!  you can't do it

$SAFE is thread local; in other words, the value of $SAFE in a thread may be changed without affecting the value in other threads. Using this feature, threads can be sandboxed for untrusted programs.

Thread::start {        # starting "sandbox" thread
  $SAFE = 4            # for this thread only
  ...                  # untrusted code
}

Get Ruby in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.