<ppdoc>
<copyright>
Copyright (c) 2001 by Addison Wesley Longman, Inc. This material may
be distributed only subject to the terms and conditions set forth in
the Open Publication License, v1.0 or later (the latest version is
presently available at http://www.opencontent.org/openpub/).
<p/>
Distribution of substantively modified versions of this document is
prohibited without the explicit permission of the copyright holder.
<p/>
Distribution of the work or derivative of the work in any standard
(paper) book form is prohibited unless prior permission is obtained
from the copyright holder.
</copyright>
<chapter  ref="xref-000001" name="Locking Ruby in the Safe">
<p/>
Walter Webcoder has a great idea for a portal site: The Web Arithmetic
Page. Surrounded by all sorts of cool mathematical links and banner
ads that will make him rich is a simple central frame, containing a
text field and a button. Users type an arithmetic expression into the
field, press the button, and the answer is displayed. All the world's
calculators become obsolete overnight, and Walter cashes in and retires to
devote his life to his collection of car license plate numbers.
<p/>
Implementing the calculator is easy, thinks Walter. He accesses the
contents of the form field using Ruby's CGI library, and uses
the <tt>eval</tt> method to evaluate the string as an expression.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require 'cgi'

  cgi = CGI::new("html4")

  # Fetch the value of the form field "expression"
  expr = cgi["expression"].to_s
  
  begin
    result = eval(expr)
  rescue Exception => detail
    # handle bad expressions
  end
  
  # display result back to user...
]]></fullcode>
require<nbsp/>'cgi'
<p/>
cgi<nbsp/>=<nbsp/>CGI::new("html4")
<p/>
#<nbsp/>Fetch<nbsp/>the<nbsp/>value<nbsp/>of<nbsp/>the<nbsp/>form<nbsp/>field<nbsp/>"expression"
expr<nbsp/>=<nbsp/>cgi["expression"].to_s
<p/>
begin
<nbsp/><nbsp/>result<nbsp/>=<nbsp/>eval(expr)
rescue<nbsp/>Exception<nbsp/>=&gt;<nbsp/>detail
<nbsp/><nbsp/>#<nbsp/>handle<nbsp/>bad<nbsp/>expressions
end
<p/>
#<nbsp/>display<nbsp/>result<nbsp/>back<nbsp/>to<nbsp/>user...
</alltt>
</codefragment>
<p/>
Roughly seven seconds after Walter puts the application online, a
twelve-year-old from Waxahachie with glandular problems and no real
life types ``<tt>system("rm<nbsp/>*")</tt>'' into the form and, like his
application, Walter's dreams come tumbling down.
<p/>
Walter learned an important lesson: <em>All external data is
  dangerous. Don't let it close to interfaces that can modify your
  system.</em> In this case, the content of the form field was the
external data, and the call to <tt>eval</tt> was the security breach.
<p/>
Fortunately, Ruby provides support for reducing this risk. All
information from the outside world can be marked as
<em>tainted</em>. When running in a safe mode, potentially dangerous
methods will raise a <exception>SecurityError</exception> if passed a tainted object.
<section>Safe Levels</section>
<p/>
The variable <var>$SAFE</var> determines Ruby's level of paranoia.
Table 20.1 on page 257 gives details of the checks performed at
each safe level.
<p/>
<table>
<th>
  <td><b>$SAFE</b></td>
  <td><b>Constraints</b></td>
</th>
<tr>
  <td>0</td>
  <td>No checking of the use of externally supplied (tainted) data is
  performed. This is Ruby's default mode.</td>
</tr>
<tr>
  <td>&gt;= 1</td>
  <td>Ruby disallows the use of tainted data by potentially
  dangerous operations.</td>
</tr>
<tr>
  <td>&gt;= 2</td>
  <td>Ruby prohibits the loading of program files from globally
  writable locations.</td>
</tr>
<tr>
  <td>&gt;= 3</td>
  <td>All newly created objects are considered tainted.</td>
</tr>
<tr>
  <td>&gt;= 4</td>
  <td>Ruby effectively partitions the running program in two. Nontainted
  objects may not be modified. Typically, this will be used to create a 
  sandbox: the program sets up an environment using a lower
  <var>$SAFE</var> level, then resets <var>$SAFE</var> to 4 to prevent
  subsequent changes to that environment.</td>
</tr>
<bottomrule/></table>
<p/>
The default value of <var>$SAFE</var> is zero under most circumstances.
However, if a Ruby script is run <em>setuid</em> or
<em>setgid</em>,<footnote>A Unix script may be flagged to be run under a
  different user or group id than the person running it. This allows
  the script to have privileges that the user does not have; the
  script can access resources that the user would otherwise be
  prohibited from using.
  These scripts are called <em>setuid</em> or <em>setgid</em>.</footnote>
its safe
level is automatically set to 1. The safe level may also be set
using the <cmdopt>-T</cmdopt>
command-line option, and by assigning to
<var>$SAFE</var> within the program. It is not possible to lower the value
of <var>$SAFE</var> by assignment.
<p/>
The current value of <var>$SAFE</var> is inherited when new threads are
created. However, within each thread, the value of <var>$SAFE</var> may be
changed without affecting the value in other threads. This facility
may be used to implement secure ``sandboxes,'' areas where external
code may run safely without risking the rest of your application or
system. Do this by wrapping code that you load from a
file in its own, anonymous module.
This will protect your
program's namespace from any unintended alteration.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  f=open(fileName,"w")
  f.print ...   # write untrusted program into file.
  f.close
  Thread.start {
    $SAFE = 4
    load(fileName, true)
  }
]]></fullcode>
f=open(fileName,"w")
f.print<nbsp/>...<nbsp/><nbsp/><nbsp/>#<nbsp/>write<nbsp/>untrusted<nbsp/>program<nbsp/>into<nbsp/>file.
f.close
Thread.start<nbsp/>{
<nbsp/><nbsp/>$SAFE<nbsp/>=<nbsp/>4
<nbsp/><nbsp/>load(fileName,<nbsp/>true)
}
</alltt>
</codefragment>
<p/>
With a <var>$SAFE</var> level of 4, you can load <em>only</em> wrapped files.
See <mmm><file>kernel</file><front>Kernel</front><back>load</back><mref>load</mref></mmm> on page 418 for details.
<section>Tainted Objects</section>
<p/>
Any Ruby object derived from some external source (for example, a
string read from a file, or an environment variable) is automatically
marked as being tainted. If your program uses a tainted object to
derive a new object, then that new object will also be tainted, as
shown in the code below. Any
object with external data somewhere in its past will be tainted. This
tainting process is performed regardless of the current safe level. You
can inspect the tainted status of an object using
<cim><file>object</file><front>Object</front><back>tainted?</back><mref>tainted_qm</mref></cim>.
<p/>
<table cellpadding="5">
        <tr>
          <td><codefragment>
<fullcode><![CDATA[  # internal data
  # =============
  x1 = "a string"
  x1.tainted?
  
  x2 = x1[2, 4]
  x2.tainted?
  
  x1 =~ /([a-z])/
  $1.tainted?
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>#<nbsp/>internal<nbsp/>data</tt></td>
</tr>
<tr>
<td colspan="3"><tt>#<nbsp/>=============</tt></td>
</tr>
<tr>
<td colspan="3"><tt>x1<nbsp/>=<nbsp/>"a<nbsp/>string"</tt></td>
</tr>
<tr>
  <td><tt>x1.tainted?</tt></td>
  <td>&#187;</td>
  <td><tt>false</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt>x2<nbsp/>=<nbsp/>x1[2,<nbsp/>4]</tt></td>
</tr>
<tr>
  <td><tt>x2.tainted?</tt></td>
  <td>&#187;</td>
  <td><tt>false</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>x1<nbsp/>=~<nbsp/>/([a-z])/</tt></td>
  <td>&#187;</td>
  <td><tt>0</tt></td>
</tr>
<tr>
  <td><tt>$1.tainted?</tt></td>
  <td>&#187;</td>
  <td><tt>false</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
</td>
          <multicolsep/>
          <td><codefragment>
<fullcode><![CDATA[  # external data
  # =============
  y1 = ENV["HOME"]
  y1.tainted?
  
  y2 = y1[2, 4]
  y2.tainted?
  
  y1 =~ /([a-z])/
  $1.tainted?
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>#<nbsp/>external<nbsp/>data</tt></td>
</tr>
<tr>
<td colspan="3"><tt>#<nbsp/>=============</tt></td>
</tr>
<tr>
<td colspan="3"><tt>y1<nbsp/>=<nbsp/>ENV["HOME"]</tt></td>
</tr>
<tr>
  <td><tt>y1.tainted?</tt></td>
  <td>&#187;</td>
  <td><tt>true</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
<td colspan="3"><tt>y2<nbsp/>=<nbsp/>y1[2,<nbsp/>4]</tt></td>
</tr>
<tr>
  <td><tt>y2.tainted?</tt></td>
  <td>&#187;</td>
  <td><tt>true</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>y1<nbsp/>=~<nbsp/>/([a-z])/</tt></td>
  <td>&#187;</td>
  <td><tt>1</tt></td>
</tr>
<tr>
  <td><tt>$1.tainted?</tt></td>
  <td>&#187;</td>
  <td><tt>true</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
</td>
        </tr>
        </table>
<p/>
You can force any object to become tainted by invoking its
<meth>taint</meth> method. If the safe level is less than 3, you can
remove the taint from an object by invoking
<meth>untaint</meth>.<footnote>There are also some devious ways of doing
  this without using <meth>untaint</meth>. We'll leave it up to your
  darker side to find them.</footnote> This is clearly not something to do
lightly.
<p/>
Clearly, Walter should have run his CGI script at a safe level of
1. This would have raised an exception when the program tried to
pass form data to <meth>eval</meth>. Once this had happened, Walter would
have had
a number of choices. He could have chosen to implement a proper expression
parser, bypassing the risks inherent in using <meth>eval</meth>. However,
being lazy, it's more likely he'd have performed some simple sanity check on
the form data, and untaint it if it looked innocuous.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require 'cgi';

  $SAFE = 1
  
  cgi = CGI::new("html4")

  expr = cgi["field"].to_s

  if expr =~ %r{^[-+*/\d\seE.()]*$}
    expr.untaint
    result = eval(expr)
    # display result back to user...
  else
    # display error message...
  end
]]></fullcode>
require<nbsp/>'cgi';
<p/>
$SAFE<nbsp/>=<nbsp/>1
<p/>
cgi<nbsp/>=<nbsp/>CGI::new("html4")
<p/>
expr<nbsp/>=<nbsp/>cgi["field"].to_s
<p/>
if<nbsp/>expr<nbsp/>=~<nbsp/>%r{^-+*/\d\seE.()*$}
<nbsp/><nbsp/>expr.untaint
<nbsp/><nbsp/>result<nbsp/>=<nbsp/>eval(expr)
<nbsp/><nbsp/>#<nbsp/>display<nbsp/>result<nbsp/>back<nbsp/>to<nbsp/>user...
else
<nbsp/><nbsp/>#<nbsp/>display<nbsp/>error<nbsp/>message...
end
</alltt>
</codefragment>
<p/>
Personally, we think Walter's still taking undue risks. We'd probably
prefer to see a real parser here, but implementing one here has
nothing to teach us about tainting, so we'll move on.
<p/>
And remember---it's a dangerous world out there. Be careful.
<p/>
<figure type="table">
<p/>
  <caption>Definition of the safe levels</caption>  
  <dl><dt><var>$SAFE</var> &gt;= 1</dt><dd><ul>
    <li> The environment variables <tt>RUBYLIB</tt> and <tt>RUBYOPT</tt> are not
      processed, and the current directory is not added to the path.            
    </li><li> The command-line options <tt>-e</tt>, <tt>-i</tt>, <tt>-I</tt>, <tt>-r</tt>,
      <tt>-s</tt>, <tt>-S</tt>, and <tt>-x</tt> are
      not allowed.
    </li><li> Can't start processes from <tt>$PATH</tt> if any directory
      in it is world-writable.
    </li><li> Can't manipulate or chroot to a directory whose name is a tainted string.
    </li><li> Can't glob tainted strings.
    </li><li> Can't eval tainted strings.
    </li><li> Can't load or require a file whose name is a tainted string.
    </li><li> Can't manipulate or query the status of a file or pipe whose
      name is a tainted string.
    </li><li> Can't execute a system command or exec a program from a
      tainted string.
    </li><li> Can't pass <meth>trap</meth> a tainted string.
    </li></ul>    
<p/>
  </dd><dt><var>$SAFE</var> &gt;= 2</dt><dd><ul>
    <li> Can't change, make, or remove directories, or use chroot.
    </li><li> Can't load a file from a world-writable directory.
    </li><li> Can't load a file from a tainted filename starting with ~.
    </li><li> Can't use
      <cim><file>file</file><front>File</front><back>chmod</back><mref>chmod</mref></cim>,
      <cim><file>file</file><front>File</front><back>chown</back><mref>chown</mref></cim>,
      <cim><file>file</file><front>File</front><back>lstat</back><mref>lstat</mref></cim>,
      <ccm><file>file</file><front>File</front><back>stat</back><mref>stat</mref></ccm>,
      <cim><file>file</file><front>File</front><back>truncate</back><mref>truncate</mref></cim>,
      <ccm><file>file</file><front>File</front><back>umask</back><mref>umask</mref></ccm>,
      <cim><file>file</file><front>File</front><back>flock</back><mref>flock</mref></cim>,
      <cim><file>io</file><front>IO</front><back>ioctl</back><mref>ioctl</mref></cim>,
      <cim><file>io</file><front>IO</front><back>stat</back><mref>stat</mref></cim>,
      <mim><file>kernel</file><front>Kernel</front><back>fork</back><mref>fork</mref></mim>,
      <mim><file>kernel</file><front>Kernel</front><back>syscall</back><mref>syscall</mref></mim>,
      <mim><file>kernel</file><front>Kernel</front><back>trap</back><mref>trap</mref></mim>.
      <mmm><file>process</file><front>Process</front><back>setpgid</back><mref>setpgid</mref></mmm>,
      <mmm><file>process</file><front>Process</front><back>setsid</back><mref>setsid</mref></mmm>,
      <mmm><file>process</file><front>Process</front><back>setpriority</back><mref>setpriority</mref></mmm>, or
      <mmm><file>process</file><front>Process</front><back>egid=</back><mref>egid_eq</mref></mmm>.
    </li><li> Can't handle signals using <meth>trap</meth>.
    </li></ul>
<p/>
  </dd><dt><var>$SAFE</var> &gt;= 3</dt><dd><ul>
    <li> All objects are created tainted.
    </li><li> Can't untaint objects.
    </li></ul>
<p/>
  </dd><dt><var>$SAFE</var> &gt;= 4</dt><dd><ul>
    <li> Can't modify a nontainted array, hash, or string.
    </li><li> Can't modify a global variable.
    </li><li> Can't access instance variables of nontainted objects.
    </li><li> Can't change an environment variable.
    </li><li> Can't close or reopen nontainted files.
    </li><li> Can't freeze nontainted objects.
    </li><li> Can't change visibility of methods (private/public/protected).
    </li><li> Can't make an alias in a nontainted class or module.
    </li><li> Can't get meta information (such as method or variable lists).
    </li><li> Can't define, redefine, remove, or undef a method in a nontainted
      class or module.
    </li><li> Can't modify <classname>Object</classname>.
    </li><li> Can't remove instance variables or constants from nontainted
      objects.
    </li><li> Can't manipulate threads, terminate a thread other than the
      current, or set <tt>abort_on_exception</tt>.
    </li><li> Can't have thread local variables.
    </li><li> Can't raise an exception in a thread with a lower <tt>$SAFE</tt> value.
    </li><li> Can't move threads between ThreadGroups.
    </li><li> Can't invoke <meth>exit</meth>, <meth>exit!</meth>, or <meth>abort</meth>.
    </li><li> Can load only wrapped files, and can't include modules
      in nontainted classes and modules.
    </li><li> Can't convert symbol identifiers to object references.
    </li><li> Can't write to files or pipes.
    </li><li> Can't use <meth>autoload</meth>.
    </li><li> Can't taint objects.
    </li></ul>
  </dd></dl>
</figure>
<p/>
</chapter>
</ppdoc>
