Programming Perl

Programming PerlSearch this book
Previous: 7.2.50 Pod::Text - Convert POD Data to Formatted ASCII TextChapter 7
The Standard Perl Library
Next: 7.2.52 SDBM_File - Tied Access to SDBM Files
 

7.2.51 Safe - Create Safe Namespaces for Evaluating Perl Code

use Safe;
$cpt = new Safe;  # create a new safe compartment

The Safe extension module allows the creation of compartments in which untrusted Perl code can be evaluated. Each compartment provides a new namespace and has an associated operator mask.

The root of the namespace (that is, main::) is changed to a different package, and code evaluated in the compartment cannot refer to variables outside this namespace, even with run-time glob lookups and other tricks. Code that is compiled outside the compartment can choose to place variables into (or share variables with) the compartment's namespace, and only that data will be visible to code evaluated in the compartment.

By default, the only variables shared with compartments are the underscore variables $_ and @_ (and, technically, the much less frequently used %_, the _ filehandle and so on). This is because otherwise Perl operators that default to $_ would not work and neither would the assignment of arguments to @_ on subroutine entry.

Each compartment has an associated operator mask with which you can exclude particular Perl operators from the compartment. (The mask syntax is explained below.) Recall that Perl code is compiled into an internal format before execution. Evaluating Perl code (for example, via eval STRING or do FILE) causes the code to be compiled into an internal format and then, provided there was no error in the compilation, executed. Code evaluated in a compartment is compiled subject to the compartment's operator mask. Attempting to evaluate compartmentalized code that contains a masked operator will cause the compilation to fail with an error. The code will not be executed.

By default, the operator mask for a newly created compartment masks out all operations that give access to the system in some sense. This includes masking off operators such as system, open, chown, and shmget, but operators such as print, sysread, and <FILEHANDLE> are not masked off. These file operators are allowed since, in order for the code in the compartment to have access to a filehandle, the code outside the compartment must have explicitly placed the filehandle variable inside the compartment.

Since it is only at the compilation stage that the operator mask applies, controlled access to potentially unsafe operations can be achieved by having a handle to a wrapper subroutine (written outside the compartment) placed into the compartment. For example:

$cpt = new Safe;
sub wrapper {
    ;# vet arguments and perform potentially unsafe operations
}
$cpt->share('&wrapper');  # see share method below

An operator mask exists at user-level as a string of bytes of length MAXO, each of which is either 0x00 or 0x01. Here, MAXO is the number of operators in the current version of Perl. The subroutine MAXO (available for export by package Safe) returns the number of operators in the currently running Perl executable. The presence of a 0x01 byte at offset n of the string indicates that operator number n should be masked (that is, disallowed). The Safe extension makes available routines for converting from operator names to operator numbers (and vice versa) and for converting from a list of operator names to the corresponding mask (and vice versa).

7.2.51.1 Methods in class Safe

To create a new compartment, use:

$cpt = new Safe NAMESPACE, MASK;

where NAMESPACE is the root namespace to use for the compartment (defaults to Safe::Root000000000, auto-incremented for each new compartment). MASK is the operator mask to use. Both arguments are optional.

The following methods can then be used on the compartment object returned by the above constructor. The object argument is implicit in each case.

root(NAMESPACE)

A get-or-set method for the compartment's namespace. With the NAMESPACE argument present, it sets the root namespace for the compartment. With no NAMESPACE argument present, it returns the current root namespace of the compartment.

mask(MASK)

A get-or-set method for the compartment's operator mask. With the MASK argument present, it sets the operator mask for the compartment. With no MASK argument present, it returns the current operator mask of the compartment.

trap(OP, ...)

Sets bits in the compartment's operator mask corresponding to each operator named in the list of arguments. Each OP can be either the name of an operation or its number. See opcode.h or opcode.pl in the main Perl distribution for a canonical list of operator names.

untrap(OP, ...)

Resets bits in the compartment's operator mask corresponding to each operator named in the list of arguments. Each OP can be either the name of an operation or its number. See opcode.h or opcode.pl in the main Perl distribution for a canonical list of operator names.

share(VARNAME, ...)

Shares the variables in the argument list with the compartment. Each VARNAME must be a string containing the name of a variable with a leading type identifier included. Examples of legal variable names are $foo for a scalar, @foo for an array, %foo for a hash, &foo for a subroutine and *foo for a typeglob. (A typeglob results in the sharing of all symbol table entries associated with foo, including scalar, array, hash, subroutine, and filehandle.)

varglob(VARNAME)

Returns a typeglob for the symbol table entry of VARNAME in the package of the compartment. VARNAME must be the name of a variable without any leading type marker. For example:

$cpt = new Safe 'Root';
$Root::foo = "Hello world";
# Equivalent version which doesn't need to know $cpt's package name:
${$cpt->varglob('foo')} = "Hello world";
reval(STRING)

Evaluates STRING as Perl code inside the compartment. The code can only see the compartment's namespace (as returned by the root() method). Any attempt by code in STRING to use an operator which is in the compartment's mask will cause an error (at run-time of the main program, but at compile-time for the code in STRING). If the code in STRING includes an eval (and the eval operator is permitted) then the error can occur at run-time for STRING (although it is at compile-time for the eval within STRING). The error is of the form "%s trapped by operation mask operation...." If an operation is trapped in this way, then the code in STRING will not be executed. If such a trapped operation occurs, or if any other compile-time or return error occurs, then $@ is set to the error message, just as with an eval. If there is no error, then the method returns the value of the last expression evaluated, or a return statement may be used, just as with subroutines and eval.

rdo(FILENAME)

Evaluates the contents of file FILENAME inside the compartment. See the reval() method earlier for further details.

7.2.51.2 Subroutines in package Safe

The Safe package contains subroutines for manipulating operator names and operator masks. All are available for export by the package. The canonical list of operator names is contained in the array op_name defined and initialized in file opcode.h of the Perl source distribution.

ops_to_mask(OP, ...)

Takes a list of operator names and returns an operator mask with precisely those operators masked.

mask_to_ops(MASK)

Takes an operator mask and returns a list of operator names corresponding to those operators which are masked in MASK.

opcode(OP, ...)

Takes a list of operator names and returns the corresponding list of opcodes (which can then be used as byte offsets into a mask).

opname(OP, ...)

Takes a list of opcodes and returns the corresponding list of operator names.

fullmask

Returns a mask with all operators masked. It returns the string "\001" x MAXO().

emptymask

Returns a mask with all operators unmasked. It returns the string "\0" x MAXO(). This is useful if you want a compartment to make use of the name-space protection features but do not want the default restrictive mask.

MAXO

This returns the number of operators (hence the length of an operator mask).

op_mask

This returns the operator mask that is actually in effect at the time the invocation to the subroutine is compiled. This is probably not terribly useful.


Previous: 7.2.50 Pod::Text - Convert POD Data to Formatted ASCII TextProgramming PerlNext: 7.2.52 SDBM_File - Tied Access to SDBM Files
7.2.50 Pod::Text - Convert POD Data to Formatted ASCII TextBook Index7.2.52 SDBM_File - Tied Access to SDBM Files