home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    

Book Home Programming PerlSearch this book

32.37. Safe

use Safe;

$sandbox = Safe->new();             # anonymous sandbox
$sandbox = Safe->new("PackName");   # in that symbol table

# Enable or disable opcodes by group or name.
$sandbox->permit(qw(:base_core));
$sandbox->permit_only(qw(:base_core :base_loop :base_mem));
$sandbox->deny("die");

# like do(), but in the sandbox
$ok = $sandbox->rdo($filename);

# like do(), but in the sandbox
$ok = $sandbox->reval($code);       # without 'use strict'
$ok = $sandbox->reval($code, 1);    # with 'use strict'
The Safe module attempts to provide a restricted environment to protect the rest of the program from dangerous operations. It uses two different strategies to do this. Much as an anonymous FTP daemon's use of chroot(2) alters the view of the root of the filesystem, creating a compartment object with Safe->new("PackName") alters that compartment's view of its own namespace. The compartment now sees as its root symbol table (main::) the symbol table that the rest of the program sees as PackName::. What looks like Frobnitz:: on the inside of the compartment is really PackName::Frobnitz:: on the outside. If you don't give an argument to the constructor, a random new package name is selected for you.

The second and more important facility that a Safe compartment provides is a way to limit code that is deemed legal within an eval. You can tweak the allowable opcode set (legal Perl operations) using method calls on your Safe object. Two methods are available to compile code in a Safe compartment: rdo ("restricted do") for files and reval ("restricted eval") for strings. These are like do on a filename and eval on a string but execute in a restricted namespace with limited opcodes. The first argument is the filename or string to compile, and the optional second argument is whether the code should be compiled under use strict.

This module is scheduled for a rewrite (we intend to isolate the sandbox into a different interpreter thread for additional safety), so be sure to check the Safe manpage for updates. See also Chapter 23, "Security".



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.











??????????????@Mail.ru