1Safe(3pm)              Perl Programmers Reference Guide              Safe(3pm)
2
3
4

NAME

6       Safe - Compile and execute code in restricted compartments
7

SYNOPSIS

9         use Safe;
10
11         $compartment = new Safe;
12
13         $compartment->permit(qw(time sort :browse));
14
15         $result = $compartment->reval($unsafe_code);
16

DESCRIPTION

18       The Safe extension module allows the creation of compartments in which
19       perl code can be evaluated. Each compartment has
20
21       a new namespace
22               The "root" of the namespace (i.e. "main::") is changed to a
23               different package and code evaluated in the compartment cannot
24               refer to variables outside this namespace, even with run-time
25               glob lookups and other tricks.
26
27               Code which is compiled outside the compartment can choose to
28               place variables into (or share variables with) the
29               compartment's namespace and only that data will be visible to
30               code evaluated in the compartment.
31
32               By default, the only variables shared with compartments are the
33               "underscore" variables $_ and @_ (and, technically, the less
34               frequently used %_, the _ filehandle and so on). This is
35               because otherwise perl operators which default to $_ will not
36               work and neither will the assignment of arguments to @_ on
37               subroutine entry.
38
39       an operator mask
40               Each compartment has an associated "operator mask". Recall that
41               perl code is compiled into an internal format before execution.
42               Evaluating perl code (e.g. via "eval" or "do 'file'") causes
43               the code to be compiled into an internal format and then,
44               provided there was no error in the compilation, executed.  Code
45               evaluated in a compartment compiles subject to the
46               compartment's operator mask. Attempting to evaluate code in a
47               compartment which contains a masked operator will cause the
48               compilation to fail with an error. The code will not be
49               executed.
50
51               The default operator mask for a newly created compartment is
52               the ':default' optag.
53
54               It is important that you read the Opcode module documentation
55               for more information, especially for detailed definitions of
56               opnames, optags and opsets.
57
58               Since it is only at the compilation stage that the operator
59               mask applies, controlled access to potentially unsafe
60               operations can be achieved by having a handle to a wrapper
61               subroutine (written outside the compartment) placed into the
62               compartment. For example,
63
64                   $cpt = new Safe;
65                   sub wrapper {
66                     # vet arguments and perform potentially unsafe operations
67                   }
68                   $cpt->share('&wrapper');
69

WARNING

71       The Safe module does not implement an effective sandbox for evaluating
72       untrusted code with the perl interpreter.
73
74       Bugs in the perl interpreter that could be abused to bypass Safe
75       restrictions are not treated as vulnerabilities. See perlsecpolicy for
76       additional information.
77
78       The authors make no warranty, implied or otherwise, about the
79       suitability of this software for safety or security purposes.
80
81       The authors shall not in any case be liable for special, incidental,
82       consequential, indirect or other similar damages arising from the use
83       of this software.
84
85       Your mileage will vary. If in any doubt do not use it.
86

METHODS

88       To create a new compartment, use
89
90           $cpt = new Safe;
91
92       Optional argument is (NAMESPACE), where NAMESPACE is the root namespace
93       to use for the compartment (defaults to "Safe::Root0", incremented for
94       each new compartment).
95
96       Note that version 1.00 of the Safe module supported a second optional
97       parameter, MASK.  That functionality has been withdrawn pending deeper
98       consideration. Use the permit and deny methods described below.
99
100       The following methods can then be used on the compartment object
101       returned by the above constructor. The object argument is implicit in
102       each case.
103
104   permit (OP, ...)
105       Permit the listed operators to be used when compiling code in the
106       compartment (in addition to any operators already permitted).
107
108       You can list opcodes by names, or use a tag name; see "Predefined
109       Opcode Tags" in Opcode.
110
111   permit_only (OP, ...)
112       Permit only the listed operators to be used when compiling code in the
113       compartment (no other operators are permitted).
114
115   deny (OP, ...)
116       Deny the listed operators from being used when compiling code in the
117       compartment (other operators may still be permitted).
118
119   deny_only (OP, ...)
120       Deny only the listed operators from being used when compiling code in
121       the compartment (all other operators will be permitted, so you probably
122       don't want to use this method).
123
124   trap (OP, ...), untrap (OP, ...)
125       The trap and untrap methods are synonyms for deny and permit
126       respectfully.
127
128   share (NAME, ...)
129       This shares the variable(s) in the argument list with the compartment.
130       This is almost identical to exporting variables using the Exporter
131       module.
132
133       Each NAME must be the name of a non-lexical variable, typically with
134       the leading type identifier included. A bareword is treated as a
135       function name.
136
137       Examples of legal names are '$foo' for a scalar, '@foo' for an array,
138       '%foo' for a hash, '&foo' or 'foo' for a subroutine and '*foo' for a
139       glob (i.e.  all symbol table entries associated with "foo", including
140       scalar, array, hash, sub and filehandle).
141
142       Each NAME is assumed to be in the calling package. See share_from for
143       an alternative method (which "share" uses).
144
145   share_from (PACKAGE, ARRAYREF)
146       This method is similar to share() but allows you to explicitly name the
147       package that symbols should be shared from. The symbol names (including
148       type characters) are supplied as an array reference.
149
150           $safe->share_from('main', [ '$foo', '%bar', 'func' ]);
151
152       Names can include package names, which are relative to the specified
153       PACKAGE.  So these two calls have the same effect:
154
155           $safe->share_from('Scalar::Util', [ 'reftype' ]);
156           $safe->share_from('main', [ 'Scalar::Util::reftype' ]);
157
158   varglob (VARNAME)
159       This returns a glob reference for the symbol table entry of VARNAME in
160       the package of the compartment. VARNAME must be the name of a variable
161       without any leading type marker. For example:
162
163           ${$cpt->varglob('foo')} = "Hello world";
164
165       has the same effect as:
166
167           $cpt = new Safe 'Root';
168           $Root::foo = "Hello world";
169
170       but avoids the need to know $cpt's package name.
171
172   reval (STRING, STRICT)
173       This evaluates STRING as perl code inside the compartment.
174
175       The code can only see the compartment's namespace (as returned by the
176       root method). The compartment's root package appears to be the "main::"
177       package to the code inside the compartment.
178
179       Any attempt by the code in STRING to use an operator which is not
180       permitted by the compartment will cause an error (at run-time of the
181       main program but at compile-time for the code in STRING).  The error is
182       of the form "'%s' trapped by operation mask...".
183
184       If an operation is trapped in this way, then the code in STRING will
185       not be executed. If such a trapped operation occurs or any other
186       compile-time or return error, then $@ is set to the error message, just
187       as with an eval().
188
189       If there is no error, then the method returns the value of the last
190       expression evaluated, or a return statement may be used, just as with
191       subroutines and eval(). The context (list or scalar) is determined by
192       the caller as usual.
193
194       If the return value of reval() is (or contains) any code reference,
195       those code references are wrapped to be themselves executed always in
196       the compartment. See "wrap_code_refs_within".
197
198       The formerly undocumented STRICT argument sets strictness: if true 'use
199       strict;' is used, otherwise it uses 'no strict;'. Note: if STRICT is
200       omitted 'no strict;' is the default.
201
202       Some points to note:
203
204       If the entereval op is permitted then the code can use eval "..." to
205       'hide' code which might use denied ops. This is not a major problem
206       since when the code tries to execute the eval it will fail because the
207       opmask is still in effect. However this technique would allow clever,
208       and possibly harmful, code to 'probe' the boundaries of what is
209       possible.
210
211       Any string eval which is executed by code executing in a compartment,
212       or by code called from code executing in a compartment, will be eval'd
213       in the namespace of the compartment. This is potentially a serious
214       problem.
215
216       Consider a function foo() in package pkg compiled outside a compartment
217       but shared with it. Assume the compartment has a root package called
218       'Root'. If foo() contains an eval statement like eval '$foo = 1' then,
219       normally, $pkg::foo will be set to 1.  If foo() is called from the
220       compartment (by whatever means) then instead of setting $pkg::foo, the
221       eval will actually set $Root::pkg::foo.
222
223       This can easily be demonstrated by using a module, such as the Socket
224       module, which uses eval "..." as part of an AUTOLOAD function. You can
225       'use' the module outside the compartment and share an (autoloaded)
226       function with the compartment. If an autoload is triggered by code in
227       the compartment, or by any code anywhere that is called by any means
228       from the compartment, then the eval in the Socket module's AUTOLOAD
229       function happens in the namespace of the compartment. Any variables
230       created or used by the eval'd code are now under the control of the
231       code in the compartment.
232
233       A similar effect applies to all runtime symbol lookups in code called
234       from a compartment but not compiled within it.
235
236   rdo (FILENAME)
237       This evaluates the contents of file FILENAME inside the compartment.
238       It uses the same rules as perl's built-in "do" to locate the file,
239       poossibly using @INC.
240
241       See above documentation on the reval method for further details.
242
243   root (NAMESPACE)
244       This method returns the name of the package that is the root of the
245       compartment's namespace.
246
247       Note that this behaviour differs from version 1.00 of the Safe module
248       where the root module could be used to change the namespace. That
249       functionality has been withdrawn pending deeper consideration.
250
251   mask (MASK)
252       This is a get-or-set method for the compartment's operator mask.
253
254       With no MASK argument present, it returns the current operator mask of
255       the compartment.
256
257       With the MASK argument present, it sets the operator mask for the
258       compartment (equivalent to calling the deny_only method).
259
260   wrap_code_ref (CODEREF)
261       Returns a reference to an anonymous subroutine that, when executed,
262       will call CODEREF with the Safe compartment 'in effect'.  In other
263       words, with the package namespace adjusted and the opmask enabled.
264
265       Note that the opmask doesn't affect the already compiled code, it only
266       affects any further compilation that the already compiled code may try
267       to perform.
268
269       This is particularly useful when applied to code references returned
270       from reval().
271
272       (It also provides a kind of workaround for RT#60374: "Safe.pm sort {}
273       bug with -Dusethreads". See
274       <https://rt.perl.org/rt3//Public/Bug/Display.html?id=60374> for much
275       more detail.)
276
277   wrap_code_refs_within (...)
278       Wraps any CODE references found within the arguments by replacing each
279       with the result of calling "wrap_code_ref" on the CODE reference. Any
280       ARRAY or HASH references in the arguments are inspected recursively.
281
282       Returns nothing.
283

RISKS

285       This section is just an outline of some of the things code in a
286       compartment might do (intentionally or unintentionally) which can have
287       an effect outside the compartment.
288
289       Memory  Consuming all (or nearly all) available memory.
290
291       CPU     Causing infinite loops etc.
292
293       Snooping
294               Copying private information out of your system. Even something
295               as simple as your user name is of value to others. Much useful
296               information could be gleaned from your environment variables
297               for example.
298
299       Signals Causing signals (especially SIGFPE and SIGALARM) to affect your
300               process.
301
302               Setting up a signal handler will need to be carefully
303               considered and controlled.  What mask is in effect when a
304               signal handler gets called?  If a user can get an imported
305               function to get an exception and call the user's signal
306               handler, does that user's restricted mask get re-instated
307               before the handler is called?  Does an imported handler get
308               called with its original mask or the user's one?
309
310       State Changes
311               Ops such as chdir obviously effect the process as a whole and
312               not just the code in the compartment. Ops such as rand and
313               srand have a similar but more subtle effect.
314

AUTHOR

316       Originally designed and implemented by Malcolm Beattie.
317
318       Reworked to use the Opcode module and other changes added by Tim Bunce.
319
320       Currently maintained by the Perl 5 Porters, <perl5-porters@perl.org>.
321
322
323
324perl v5.36.0                      2022-08-30                         Safe(3pm)
Impressum