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