1Safe(3pm) Perl Programmers Reference Guide Safe(3pm)
2
3
4
6 Safe - Compile and execute code in restricted compartments
7
9 use Safe;
10
11 $compartment = new Safe;
12
13 $compartment->permit(qw(time sort :browse));
14
15 $result = $compartment->reval($unsafe_code);
16
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
71 The authors make no warranty, implied or otherwise, about the
72 suitability of this software for safety or security purposes.
73
74 The authors shall not in any case be liable for special, incidental,
75 consequential, indirect or other similar damages arising from the use
76 of this software.
77
78 Your mileage will vary. If in any doubt do not use it.
79
81 To create a new compartment, use
82
83 $cpt = new Safe;
84
85 Optional argument is (NAMESPACE), where NAMESPACE is the root namespace
86 to use for the compartment (defaults to "Safe::Root0", incremented for
87 each new compartment).
88
89 Note that version 1.00 of the Safe module supported a second optional
90 parameter, MASK. That functionality has been withdrawn pending deeper
91 consideration. Use the permit and deny methods described below.
92
93 The following methods can then be used on the compartment object
94 returned by the above constructor. The object argument is implicit in
95 each case.
96
97 permit (OP, ...)
98 Permit the listed operators to be used when compiling code in the
99 compartment (in addition to any operators already permitted).
100
101 You can list opcodes by names, or use a tag name; see "Predefined
102 Opcode Tags" in Opcode.
103
104 permit_only (OP, ...)
105 Permit only the listed operators to be used when compiling code in the
106 compartment (no other operators are permitted).
107
108 deny (OP, ...)
109 Deny the listed operators from being used when compiling code in the
110 compartment (other operators may still be permitted).
111
112 deny_only (OP, ...)
113 Deny only the listed operators from being used when compiling code in
114 the compartment (all other operators will be permitted, so you probably
115 don't want to use this method).
116
117 trap (OP, ...), untrap (OP, ...)
118 The trap and untrap methods are synonyms for deny and permit
119 respectfully.
120
121 share (NAME, ...)
122 This shares the variable(s) in the argument list with the compartment.
123 This is almost identical to exporting variables using the Exporter
124 module.
125
126 Each NAME must be the name of a non-lexical variable, typically with
127 the leading type identifier included. A bareword is treated as a
128 function name.
129
130 Examples of legal names are '$foo' for a scalar, '@foo' for an array,
131 '%foo' for a hash, '&foo' or 'foo' for a subroutine and '*foo' for a
132 glob (i.e. all symbol table entries associated with "foo", including
133 scalar, array, hash, sub and filehandle).
134
135 Each NAME is assumed to be in the calling package. See share_from for
136 an alternative method (which "share" uses).
137
138 share_from (PACKAGE, ARRAYREF)
139 This method is similar to share() but allows you to explicitly name the
140 package that symbols should be shared from. The symbol names (including
141 type characters) are supplied as an array reference.
142
143 $safe->share_from('main', [ '$foo', '%bar', 'func' ]);
144
145 Names can include package names, which are relative to the specified
146 PACKAGE. So these two calls have the same effect:
147
148 $safe->share_from('Scalar::Util', [ 'reftype' ]);
149 $safe->share_from('main', [ 'Scalar::Util::reftype' ]);
150
151 varglob (VARNAME)
152 This returns a glob reference for the symbol table entry of VARNAME in
153 the package of the compartment. VARNAME must be the name of a variable
154 without any leading type marker. For example:
155
156 ${$cpt->varglob('foo')} = "Hello world";
157
158 has the same effect as:
159
160 $cpt = new Safe 'Root';
161 $Root::foo = "Hello world";
162
163 but avoids the need to know $cpt's package name.
164
165 reval (STRING, STRICT)
166 This evaluates STRING as perl code inside the compartment.
167
168 The code can only see the compartment's namespace (as returned by the
169 root method). The compartment's root package appears to be the "main::"
170 package to the code inside the compartment.
171
172 Any attempt by the code in STRING to use an operator which is not
173 permitted by the compartment will cause an error (at run-time of the
174 main program but at compile-time for the code in STRING). The error is
175 of the form "'%s' trapped by operation mask...".
176
177 If an operation is trapped in this way, then the code in STRING will
178 not be executed. If such a trapped operation occurs or any other
179 compile-time or return error, then $@ is set to the error message, just
180 as with an eval().
181
182 If there is no error, then the method returns the value of the last
183 expression evaluated, or a return statement may be used, just as with
184 subroutines and eval(). The context (list or scalar) is determined by
185 the caller as usual.
186
187 If the return value of reval() is (or contains) any code reference,
188 those code references are wrapped to be themselves executed always in
189 the compartment. See "wrap_code_refs_within".
190
191 The formerly undocumented STRICT argument sets strictness: if true 'use
192 strict;' is used, otherwise it uses 'no strict;'. Note: if STRICT is
193 omitted 'no strict;' is the default.
194
195 Some points to note:
196
197 If the entereval op is permitted then the code can use eval "..." to
198 'hide' code which might use denied ops. This is not a major problem
199 since when the code tries to execute the eval it will fail because the
200 opmask is still in effect. However this technique would allow clever,
201 and possibly harmful, code to 'probe' the boundaries of what is
202 possible.
203
204 Any string eval which is executed by code executing in a compartment,
205 or by code called from code executing in a compartment, will be eval'd
206 in the namespace of the compartment. This is potentially a serious
207 problem.
208
209 Consider a function foo() in package pkg compiled outside a compartment
210 but shared with it. Assume the compartment has a root package called
211 'Root'. If foo() contains an eval statement like eval '$foo = 1' then,
212 normally, $pkg::foo will be set to 1. If foo() is called from the
213 compartment (by whatever means) then instead of setting $pkg::foo, the
214 eval will actually set $Root::pkg::foo.
215
216 This can easily be demonstrated by using a module, such as the Socket
217 module, which uses eval "..." as part of an AUTOLOAD function. You can
218 'use' the module outside the compartment and share an (autoloaded)
219 function with the compartment. If an autoload is triggered by code in
220 the compartment, or by any code anywhere that is called by any means
221 from the compartment, then the eval in the Socket module's AUTOLOAD
222 function happens in the namespace of the compartment. Any variables
223 created or used by the eval'd code are now under the control of the
224 code in the compartment.
225
226 A similar effect applies to all runtime symbol lookups in code called
227 from a compartment but not compiled within it.
228
229 rdo (FILENAME)
230 This evaluates the contents of file FILENAME inside the compartment.
231 It uses the same rules as perl's built-in "do" to locate the file,
232 poossibly using @INC.
233
234 See above documentation on the reval method for further details.
235
236 root (NAMESPACE)
237 This method returns the name of the package that is the root of the
238 compartment's namespace.
239
240 Note that this behaviour differs from version 1.00 of the Safe module
241 where the root module could be used to change the namespace. That
242 functionality has been withdrawn pending deeper consideration.
243
244 mask (MASK)
245 This is a get-or-set method for the compartment's operator mask.
246
247 With no MASK argument present, it returns the current operator mask of
248 the compartment.
249
250 With the MASK argument present, it sets the operator mask for the
251 compartment (equivalent to calling the deny_only method).
252
253 wrap_code_ref (CODEREF)
254 Returns a reference to an anonymous subroutine that, when executed,
255 will call CODEREF with the Safe compartment 'in effect'. In other
256 words, with the package namespace adjusted and the opmask enabled.
257
258 Note that the opmask doesn't affect the already compiled code, it only
259 affects any further compilation that the already compiled code may try
260 to perform.
261
262 This is particularly useful when applied to code references returned
263 from reval().
264
265 (It also provides a kind of workaround for RT#60374: "Safe.pm sort {}
266 bug with -Dusethreads". See
267 <http://rt.perl.org/rt3//Public/Bug/Display.html?id=60374> for much
268 more detail.)
269
270 wrap_code_refs_within (...)
271 Wraps any CODE references found within the arguments by replacing each
272 with the result of calling "wrap_code_ref" on the CODE reference. Any
273 ARRAY or HASH references in the arguments are inspected recursively.
274
275 Returns nothing.
276
278 This section is just an outline of some of the things code in a
279 compartment might do (intentionally or unintentionally) which can have
280 an effect outside the compartment.
281
282 Memory Consuming all (or nearly all) available memory.
283
284 CPU Causing infinite loops etc.
285
286 Snooping
287 Copying private information out of your system. Even something
288 as simple as your user name is of value to others. Much useful
289 information could be gleaned from your environment variables
290 for example.
291
292 Signals Causing signals (especially SIGFPE and SIGALARM) to affect your
293 process.
294
295 Setting up a signal handler will need to be carefully
296 considered and controlled. What mask is in effect when a
297 signal handler gets called? If a user can get an imported
298 function to get an exception and call the user's signal
299 handler, does that user's restricted mask get re-instated
300 before the handler is called? Does an imported handler get
301 called with its original mask or the user's one?
302
303 State Changes
304 Ops such as chdir obviously effect the process as a whole and
305 not just the code in the compartment. Ops such as rand and
306 srand have a similar but more subtle effect.
307
309 Originally designed and implemented by Malcolm Beattie.
310
311 Reworked to use the Opcode module and other changes added by Tim Bunce.
312
313 Currently maintained by the Perl 5 Porters, <perl5-porters@perl.org>.
314
315
316
317perl v5.30.2 2020-03-27 Safe(3pm)