Safe(3perl)
โจ NAME โจ
Safe โ compile and execute code in restricted compartments. yup bestie, this is the Safe(3perl) page, and it's literally the "restricted compartments" queen ๐. It's giving security-ish vibes, but please read the WARNING before you get too comfy ๐
.
๐ธ SYNOPSIS ๐ธ
okay so the vibe is:
use Safe;
$compartment = new Safe;
$compartment->permit(qw(time sort :browse));
$result = $compartment->reval($unsafe_code);
๐ฆ DESCRIPTION ๐ฆ
okay so the Safe extension module lets you create compartments where perl code can be evaluated. Every compartment has:
- a new namespace โ the glow-up of namespaces, honestly
- The "root" of the namespace (i.e.
"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 which 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. sharing is caring, but make it controlled
- By default, the only variables shared with compartments are the "underscore" variables
$_and@_(and, technically, the less frequently used%_, the_filehandle and so on). Why? Because otherwise perl operators which default to$_will not work, and neither will the assignment of arguments to@_on subroutine entry. periodt ๐
- The "root" of the namespace (i.e.
- an operator mask โ the bouncer at the club door, but for ops
- Each compartment has an associated "operator mask". Recall that perl code is compiled into an internal format before execution. Evaluating perl code (e.g. via
"eval"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 compiles subject to the compartment's operator mask. Attempting to evaluate code in a compartment which contains a masked operator will cause the compilation to fail with an error. The code will not be executed. ๐ - The default operator mask for a newly created compartment is the
':default'optag. โจ - It is important that you read the
Opcodemodule documentation for more information, especially for detailed definitions of opnames, optags and opsets. ๐ - 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,
- Each compartment has an associated "operator mask". Recall that perl code is compiled into an internal format before execution. Evaluating perl code (e.g. via
$cpt = new Safe;
sub wrapper {
# vet arguments and perform potentially unsafe operations
}
$cpt->share('&wrapper');
โ ๏ธ WARNING โ ๏ธ
bestie, real talk: the Safe module does not implement an effective sandbox for evaluating untrusted code with the perl interpreter. ๐ซ
Bugs in the perl interpreter that could be abused to bypass Safe restrictions are not treated as vulnerabilities. See perlsecpolicy for additional information. ๐
The authors make no warranty, implied or otherwise, about the suitability of this software for safety or security purposes.
The authors shall not in any case be liable for special, incidental, consequential, indirect or other similar damages arising from the use of this software.
Your mileage will vary. If in any doubt do not use it. ๐
๐ METHODS ๐
okay so bestie, to make yourself a whole new compartment you literally just go:
$cpt = new Safe;
The optional argument is (NAMESPACE), and that's the root namespace your compartment is gonna live in (it defaults to Safe::Root0, and it gets incremented for every new compartment you make, so they're never fighting over the same name ๐).
โ ๏ธ lore drop, don't skip: version 1.00 of the Safe module supported a second optional parameter,MASK. That functionality has been withdrawn pending deeper consideration ๐ญ so it is not a thing anymore. Use thepermitanddenymethods described below instead, ok?
And then all the methods below can be used on the compartment object that constructor handed back to you. The object argument is implicit in every single case โ she's just there, you don't pass her again ๐ .
โจ permit (OP, ...) โจ
Permits the listed operators to be used when compiling code in the compartment โ and it's in addition to any operators that were already permitted, so it stacks, we love an additive queen.
You can list opcodes by names, or you can just use a tag name; see "Predefined Opcode Tags" in Opcode for the full menu ๐.
๐ permit_only (OP, ...) ๐
Permits only the listed operators to be used when compiling code in the compartment. That's it. No other operators are permitted. it's giving "you get these and nothing else, periodt".
๐ฆ deny (OP, ...) ๐ฆ
Denies the listed operators from being used when compiling code in the compartment. Other operators may still be permitted though, so this is the soft-block, not the full lockdown.
๐ฅ deny_only (OP, ...) ๐ฅ
Denies only the listed operators from being used when compiling code in the compartment โ which means all the other operators will be permitted. So like, yeah, it works exactly how it says, but you probably don't want to use this method ๐ญ it's the opposite of what you'd expect.
๐ trap (OP, ...), untrap (OP, ...) ๐
The trap and untrap methods are synonyms for deny and permit respectively (the original says "respectfully", which is iconic of it ๐ but yeah, respectively). Same vibe, different spelling.
๐ธ share (NAME, ...) ๐ธ
This shares the variable(s) in the argument list with the compartment. It's almost identical to exporting variables using the Exporter module โ like, spiritually the same move.
Each NAME must be the name of a non-lexical variable, typically with the leading type identifier included. A bareword is treated as a function name.
Examples of legal names are:
'$foo'for a scalar'@foo'for an array'%foo'for a hash'&foo'or'foo'for a subroutine'*foo'for a glob (i.e. all symbol table entries associated with"foo", including scalar, array, hash, sub and filehandle)
Each NAME is assumed to be in the calling package. See share_from for an alternative method (which "share" uses).
๐ share_from (PACKAGE, ARRAYREF) ๐
This method is similar to share() but it lets you explicitly name the package that symbols should be shared from. The symbol names (including type characters, don't forget those ๐
) are supplied as an array reference.
$safe->share_from('main', [ '$foo', '%bar', 'func' ]);
Names can include package names, which are relative to the specified PACKAGE. So these two calls have the exact same effect:
$safe->share_from('Scalar::Util', [ 'reftype' ]);
$safe->share_from('main', [ 'Scalar::Util::reftype' ]);
๐ซถ varglob (VARNAME) ๐ซถ
This returns a glob reference 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 (so no sigils, bestie, put them down).
For example:
${$cpt->varglob('foo')} = "Hello world";
has the same effect as:
$cpt = new Safe 'Root';
$Root::foo = "Hello world";
but it avoids the need to know $cpt's package name. Which is the whole point, and it's giving "no need to peek behind the curtain" โจ.
๐ reval (STRING, STRICT) ๐
This evaluates STRING as perl code inside the compartment. The moment of truth, the main character moment, etc.
The code can only see the compartment's namespace (as returned by the root method). And get this โ the compartment's root package appears to be the "main::" package to the code inside the compartment. Sneaky. Iconic.
Any attempt by the code in STRING to use an operator which is not permitted by the compartment will cause an error โ and note the timing: that's at run-time of the main program but at compile-time for the code in STRING. The error is of the form:
'%s' trapped by operation mask...
If an operation is trapped in this way, then the code in STRING will not be executed. If such a trapped operation occurs, or any other compile-time or return error happens, 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(). The context (list or scalar) is determined by the caller as usual.
If the return value of reval() is (or contains) any code reference, those code references are wrapped to be themselves executed always in the compartment. See "wrap_code_refs_within" for that.
The formerly undocumented STRICT argument sets strictness: if true, 'use strict;' is used, otherwise it uses 'no strict;'. Note: if STRICT is omitted, 'no strict;' is the default. So yeah, loosey-goosey unless you say otherwise ๐.
Some points to note ๐ซข:
The entereval op thing. If the entereval op is permitted, then the code can use eval "..." to 'hide' code which might use denied ops. This is not a major problem since when the code tries to execute the eval it will fail because the opmask is still in effect. However, this technique would allow clever, and possibly harmful, code to 'probe' the boundaries of what is possible. so like... noted, bestie.
The namespace thing. Any string eval which is executed by code executing in a compartment, or by code called from code executing in a compartment, will be eval'd in the namespace of the compartment. This is potentially a serious problem.
Consider a function foo() in package pkg compiled outside a compartment but shared with it. Assume the compartment has a root package called 'Root'. If foo() contains an eval statement like eval '$foo = 1' then, normally, $pkg::foo will be set to 1. If foo() is called from the compartment (by whatever means) then instead of setting $pkg::foo, the eval will actually set $Root::pkg::foo. ๐ญ the plot twist nobody asked for.
This can easily be demonstrated by using a module, such as the Socket module, which uses eval "..." as part of an AUTOLOAD function. You can 'use' the module outside the compartment and share an (autoloaded) function with the compartment. If an autoload is triggered by code in the compartment, or by any code anywhere that is called by any means from the compartment, then the eval in the Socket module's AUTOLOAD function happens in the namespace of the compartment. Any variables created or used by the eval'd code are now under the control of the code in the compartment. which is exactly as unhinged as it sounds ๐.
A similar effect applies to all runtime symbol lookups in code called from a compartment but not compiled within it.
๐ง rdo (FILENAME) ๐ง
This evaluates the contents of file FILENAME inside the compartment. It uses the same rules as perl's built-in "do" to locate the file, possibly using @INC.
See the documentation above on the reval method for further details, because it's the same energy with a filename ๐.
โญ root (NAMESPACE) โญ
This method returns the name of the package that is the root of the compartment's namespace.
Note that this behaviour differs from version 1.00 of the Safe module, where the root module could be used to change the namespace. That functionality has been withdrawn pending deeper consideration. rip to that feature, she's on a break ๐.
๐ mask (MASK) ๐
This is a get-or-set method for the compartment's operator mask. Two moods:
- With no MASK argument present, it returns the current operator mask of the compartment.
- With the MASK argument present, it sets the operator mask for the compartment (equivalent to calling the
deny_onlymethod).
๐
wrap_code_ref (CODEREF) ๐
Returns a reference to an anonymous subroutine that, when executed, will call CODEREF with the Safe compartment 'in effect'. In other words: with the package namespace adjusted and the opmask enabled. which is the whole dream honestly.
Note that the opmask doesn't affect the already compiled code โ it only affects any further compilation that the already compiled code may try to perform. So it's forward-looking only, no retroactive vibes ๐ฎ.
This is particularly useful when applied to code references returned from reval().
(It also provides a kind of workaround for RT#60374: "Safe.pm sort {} bug with -Dusethreads". See https://rt.perl.org/rt3//Public/Bug/Display.html?id=60374 for much more detail.) iykyk.
๐ฆ wrap_code_refs_within (...) ๐ฆ
Wraps any CODE references found within the arguments by replacing each one with the result of calling "wrap_code_ref" on the CODE reference. Any ARRAY or HASH references in the arguments are inspected recursively, because we go all the way down ๐.
Returns nothing. she does the work and leaves, no receipts.
๐ RISKS ๐
This section is just an outline of some of the things code in a compartment might do (intentionally or unintentionally) which can have an effect outside the compartment. read it, bestie, it's important.
๐ง Memory
Consuming all (or nearly all) available memory.
๐ฅ CPU
Causing infinite loops etc.
๐ Snooping
Copying private information out of your system. Even something as simple as your user name is of value to others. Much useful information could be gleaned from your environment variables, for example.
๐จ Signals
Causing signals (especially SIGFPE and SIGALRM) to affect your process.
Setting up a signal handler will need to be carefully considered and controlled. What mask is in effect when a signal handler gets called? If a user can get an imported function to get an exception and call the user's signal handler, does that user's restricted mask get re-instated before the handler is called? Does an imported handler get called with its original mask or the user's one? big questions, no easy answers ๐ณ.
๐ช State Changes
Ops such as chdir obviously effect the process as a whole and not just the code in the compartment. Ops such as rand and srand have a similar but more subtle effect.
๐ AUTHOR ๐
Originally designed and implemented by Malcolm Beattie.
Reworked to use the Opcode module and other changes added by Tim Bunce.
Currently maintained by the Perl 5 Porters, perl5-porters@perl.org.
and that's the whole page, bestie ๐ซถ this was Safe(3perl) from perl v5.44.0, dated 2026-10-17 โ go forth and compartmentalise responsibly, no cap ๐
โจ๐
๐ฆ where this page comes from
- arch rolling: perl 5.44.0-1 ยท Artistic-1.0-Perl AND GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms