[inseparable changes from patch from perl5.003_11 to perl5.003_12]
[p5sagit/p5-mst-13.2.git] / ext / Opcode / Safe.pm
CommitLineData
2ded1cc1 1package Safe;
2
5f05dabc 3use 5.003_11;
2ded1cc1 4use strict;
2ded1cc1 5use vars qw($VERSION);
6
7$VERSION = "2.06";
8
5f05dabc 9use Carp;
10
2ded1cc1 11use Opcode 1.01, qw(
12 opset opset_to_ops opmask_add
13 empty_opset full_opset invert_opset verify_opset
14 opdesc opcodes opmask define_optag opset_to_hex
15);
16
17*ops_to_opset = \&opset; # Temporary alias for old Penguins
18
19
20my $default_root = 0;
21my $default_share = ['*_']; #, '*main::'];
22
23sub new {
24 my($class, $root, $mask) = @_;
25 my $obj = {};
26 bless $obj, $class;
27
28 if (defined($root)) {
29 croak "Can't use \"$root\" as root name"
30 if $root =~ /^main\b/ or $root !~ /^\w[:\w]*$/;
31 $obj->{Root} = $root;
32 $obj->{Erase} = 0;
33 }
34 else {
35 $obj->{Root} = "Safe::Root".$default_root++;
36 $obj->{Erase} = 1;
37 }
38
39 # use permit/deny methods instead till interface issues resolved
40 # XXX perhaps new Safe 'Root', mask => $mask, foo => bar, ...;
41 croak "Mask parameter to new no longer supported" if defined $mask;
42 $obj->permit_only(':default');
43
44 # We must share $_ and @_ with the compartment or else ops such
45 # as split, length and so on won't default to $_ properly, nor
46 # will passing argument to subroutines work (via @_). In fact,
47 # for reasons I don't completely understand, we need to share
48 # the whole glob *_ rather than $_ and @_ separately, otherwise
49 # @_ in non default packages within the compartment don't work.
50 $obj->share_from('main', $default_share);
51 return $obj;
52}
53
54sub DESTROY {
55 my $obj = shift;
56 $obj->erase if $obj->{Erase};
57}
58
59sub erase {
60 my $obj= shift;
61 my $pkg = $obj->root();
62 my ($stem, $leaf);
63
64 no strict 'refs';
65 $pkg = "main::$pkg\::"; # expand to full symbol table name
66 ($stem, $leaf) = $pkg =~ m/(.*::)(\w+::)$/;
67
68 # The 'my $foo' is needed! Without it you get an
69 # 'Attempt to free unreferenced scalar' warning!
70 my $stem_symtab = *{$stem}{HASH};
71
72 #warn "erase($pkg) stem=$stem, leaf=$leaf";
73 #warn " stem_symtab hash ".scalar(%$stem_symtab)."\n";
74 # ", join(', ', %$stem_symtab),"\n";
75
76 delete $stem_symtab->{$leaf};
77
78# my $leaf_glob = $stem_symtab->{$leaf};
79# my $leaf_symtab = *{$leaf_glob}{HASH};
80# warn " leaf_symtab ", join(', ', %$leaf_symtab),"\n";
81# %$leaf_symtab = ();
82 #delete $leaf_symtab->{'__ANON__'};
83 #delete $leaf_symtab->{'foo'};
84 #delete $leaf_symtab->{'main::'};
85# my $foo = undef ${"$stem\::"}{"$leaf\::"};
86
87 $obj->share_from('main', $default_share);
88 1;
89}
90
91
92sub reinit {
93 my $obj= shift;
94 $obj->erase;
95 $obj->share_redo;
96}
97
98sub root {
99 my $obj = shift;
100 croak("Safe root method now read-only") if @_;
101 return $obj->{Root};
102}
103
104
105sub mask {
106 my $obj = shift;
107 return $obj->{Mask} unless @_;
108 $obj->deny_only(@_);
109}
110
111# v1 compatibility methods
112sub trap { shift->deny(@_) }
113sub untrap { shift->permit(@_) }
114
115sub deny {
116 my $obj = shift;
117 $obj->{Mask} |= opset(@_);
118}
119sub deny_only {
120 my $obj = shift;
121 $obj->{Mask} = opset(@_);
122}
123
124sub permit {
125 my $obj = shift;
126 # XXX needs testing
127 $obj->{Mask} &= invert_opset opset(@_);
128}
129sub permit_only {
130 my $obj = shift;
131 $obj->{Mask} = invert_opset opset(@_);
132}
133
134
135sub dump_mask {
136 my $obj = shift;
137 print opset_to_hex($obj->{Mask}),"\n";
138}
139
140
141
142sub share {
143 my($obj, @vars) = @_;
144 $obj->share_from(scalar(caller), \@vars);
145}
146
147sub share_from {
148 my $obj = shift;
149 my $pkg = shift;
150 my $vars = shift;
151 my $no_record = shift || 0;
152 my $root = $obj->root();
153 my ($var, $arg);
154 croak("vars not an array ref") unless ref $vars eq 'ARRAY';
155 no strict 'refs';
156 # Check that 'from' package actually exists
157 croak("Package \"$pkg\" does not exist")
158 unless keys %{"$pkg\::"};
159 foreach $arg (@$vars) {
160 # catch some $safe->share($var) errors:
161 croak("'$arg' not a valid symbol table name")
162 unless $arg =~ /^[\$\@%*&]?\w[\w:]*$/
163 or $arg =~ /^\$\W$/;
164 ($var = $arg) =~ s/^(\W)//; # get type char
165 # warn "share_from $pkg $1 $var";
166 *{$root."::$var"} = ($1 eq '$') ? \${$pkg."::$var"}
167 : ($1 eq '@') ? \@{$pkg."::$var"}
168 : ($1 eq '%') ? \%{$pkg."::$var"}
169 : ($1 eq '*') ? *{$pkg."::$var"}
170 : ($1 eq '&') ? \&{$pkg."::$var"}
171 : (!$1) ? \&{$pkg."::$var"}
172 : croak(qq(Can't share "$1$var" of unknown type));
173 }
174 $obj->share_record($pkg, $vars) unless $no_record or !$vars;
175}
176
177sub share_record {
178 my $obj = shift;
179 my $pkg = shift;
180 my $vars = shift;
181 my $shares = \%{$obj->{Shares} ||= {}};
182 # Record shares using keys of $obj->{Shares}. See reinit.
183 @{$shares}{@$vars} = ($pkg) x @$vars if @$vars;
184}
185sub share_redo {
186 my $obj = shift;
187 my $shares = \%{$obj->{Shares} ||= {}};
188 my($var, $pkg);
189 while(($var, $pkg) = each %$shares) {
190 # warn "share_redo $pkg\:: $var";
191 $obj->share_from($pkg, [ $var ], 1);
192 }
193}
194sub share_forget {
195 delete shift->{Shares};
196}
197
198sub varglob {
199 my ($obj, $var) = @_;
200 no strict 'refs';
201 return *{$obj->root()."::$var"};
202}
203
204
205sub reval {
206 my ($obj, $expr, $strict) = @_;
207 my $root = $obj->{Root};
208
209 # Create anon sub ref in root of compartment.
210 # Uses a closure (on $expr) to pass in the code to be executed.
211 # (eval on one line to keep line numbers as expected by caller)
212 my $evalcode = sprintf('package %s; sub { eval $expr; }', $root);
213 my $evalsub;
214
215 if ($strict) { use strict; $evalsub = eval $evalcode; }
216 else { no strict; $evalsub = eval $evalcode; }
217
218 return Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub);
219}
220
221sub rdo {
222 my ($obj, $file) = @_;
223 my $root = $obj->{Root};
224
225 my $evalsub = eval
226 sprintf('package %s; sub { do $file }', $root);
227 return Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub);
228}
229
230
2311;
232
233__DATA__
234
235=head1 NAME
236
237Safe - Compile and execute code in restricted compartments
238
239=head1 SYNOPSIS
240
241 use Safe;
242
243 $compartment = new Safe;
244
245 $compartment->permit(qw(time sort :browse));
246
247 $result = $compartment->reval($unsafe_code);
248
249=head1 DESCRIPTION
250
251The Safe extension module allows the creation of compartments
252in which perl code can be evaluated. Each compartment has
253
254=over 8
255
256=item a new namespace
257
258The "root" of the namespace (i.e. "main::") is changed to a
259different package and code evaluated in the compartment cannot
260refer to variables outside this namespace, even with run-time
261glob lookups and other tricks.
262
263Code which is compiled outside the compartment can choose to place
264variables into (or I<share> variables with) the compartment's namespace
265and only that data will be visible to code evaluated in the
266compartment.
267
268By default, the only variables shared with compartments are the
269"underscore" variables $_ and @_ (and, technically, the less frequently
270used %_, the _ filehandle and so on). This is because otherwise perl
271operators which default to $_ will not work and neither will the
272assignment of arguments to @_ on subroutine entry.
273
274=item an operator mask
275
276Each compartment has an associated "operator mask". Recall that
277perl code is compiled into an internal format before execution.
278Evaluating perl code (e.g. via "eval" or "do 'file'") causes
279the code to be compiled into an internal format and then,
280provided there was no error in the compilation, executed.
281Code evaulated in a compartment compiles subject to the
282compartment's operator mask. Attempting to evaulate code in a
283compartment which contains a masked operator will cause the
284compilation to fail with an error. The code will not be executed.
285
286The default operator mask for a newly created compartment is
287the ':default' optag.
288
1fef88e7 289It is important that you read the Opcode(3) module documentation
290for more information, especially for detailed definitions of opnames,
2ded1cc1 291optags and opsets.
292
293Since it is only at the compilation stage that the operator mask
294applies, controlled access to potentially unsafe operations can
295be achieved by having a handle to a wrapper subroutine (written
296outside the compartment) placed into the compartment. For example,
297
298 $cpt = new Safe;
299 sub wrapper {
300 # vet arguments and perform potentially unsafe operations
301 }
302 $cpt->share('&wrapper');
303
304=back
305
306
307=head1 WARNING
308
309The authors make B<no warranty>, implied or otherwise, about the
310suitability of this software for safety or security purposes.
311
312The authors shall not in any case be liable for special, incidental,
313consequential, indirect or other similar damages arising from the use
314of this software.
315
316Your mileage will vary. If in any doubt B<do not use it>.
317
318
319=head2 RECENT CHANGES
320
321The interface to the Safe module has changed quite dramatically since
322version 1 (as supplied with Perl5.002). Study these pages carefully if
323you have code written to use Safe version 1 because you will need to
324makes changes.
325
326
327=head2 Methods in class Safe
328
329To create a new compartment, use
330
331 $cpt = new Safe;
332
333Optional argument is (NAMESPACE), where NAMESPACE is the root namespace
334to use for the compartment (defaults to "Safe::Root0", incremented for
335each new compartment).
336
337Note that version 1.00 of the Safe module supported a second optional
338parameter, MASK. That functionality has been withdrawn pending deeper
339consideration. Use the permit and deny methods described below.
340
341The following methods can then be used on the compartment
342object returned by the above constructor. The object argument
343is implicit in each case.
344
345
346=over 8
347
348=item permit (OP, ...)
349
350Permit the listed operators to be used when compiling code in the
351compartment (in I<addition> to any operators already permitted).
352
353=item permit_only (OP, ...)
354
355Permit I<only> the listed operators to be used when compiling code in
356the compartment (I<no> other operators are permitted).
357
358=item deny (OP, ...)
359
360Deny the listed operators from being used when compiling code in the
361compartment (other operators may still be permitted).
362
363=item deny_only (OP, ...)
364
365Deny I<only> the listed operators from being used when compiling code
366in the compartment (I<all> other operators will be permitted).
367
368=item trap (OP, ...)
369
370=item untrap (OP, ...)
371
372The trap and untrap methods are synonyms for deny and permit
373respectfully.
374
375=item share (NAME, ...)
376
377This shares the variable(s) in the argument list with the compartment.
378This is almost identical to exporting variables using the L<Exporter(3)>
379module.
380
381Each NAME must be the B<name> of a variable, typically with the leading
382type identifier included. A bareword is treated as a function name.
383
384Examples of legal names are '$foo' for a scalar, '@foo' for an
385array, '%foo' for a hash, '&foo' or 'foo' for a subroutine and '*foo'
386for a glob (i.e. all symbol table entries associated with "foo",
387including scalar, array, hash, sub and filehandle).
388
389Each NAME is assumed to be in the calling package. See share_from
390for an alternative method (which share uses).
391
392=item share_from (PACKAGE, ARRAYREF)
393
394This method is similar to share() but allows you to explicitly name the
395package that symbols should be shared from. The symbol names (including
396type characters) are supplied as an array reference.
397
398 $safe->share_from('main', [ '$foo', '%bar', 'func' ]);
399
400
401=item varglob (VARNAME)
402
403This returns a glob reference for the symbol table entry of VARNAME in
404the package of the compartment. VARNAME must be the B<name> of a
405variable without any leading type marker. For example,
406
407 $cpt = new Safe 'Root';
408 $Root::foo = "Hello world";
409 # Equivalent version which doesn't need to know $cpt's package name:
410 ${$cpt->varglob('foo')} = "Hello world";
411
412
413=item reval (STRING)
414
415This evaluates STRING as perl code inside the compartment.
416
417The code can only see the compartment's namespace (as returned by the
418B<root> method). The compartment's root package appears to be the
419C<main::> package to the code inside the compartment.
420
421Any attempt by the code in STRING to use an operator which is not permitted
422by the compartment will cause an error (at run-time of the main program
423but at compile-time for the code in STRING). The error is of the form
424"%s trapped by operation mask operation...".
425
426If an operation is trapped in this way, then the code in STRING will
427not be executed. If such a trapped operation occurs or any other
428compile-time or return error, then $@ is set to the error message, just
429as with an eval().
430
431If there is no error, then the method returns the value of the last
432expression evaluated, or a return statement may be used, just as with
433subroutines and B<eval()>. The context (list or scalar) is determined
434by the caller as usual.
435
436This behaviour differs from the beta distribution of the Safe extension
437where earlier versions of perl made it hard to mimic the return
438behaviour of the eval() command and the context was always scalar.
439
440Some points to note:
441
442If the entereval op is permitted then the code can use eval "..." to
443'hide' code which might use denied ops. This is not a major problem
444since when the code tries to execute the eval it will fail because the
445opmask is still in effect. However this technique would allow clever,
446and possibly harmful, code to 'probe' the boundaries of what is
447possible.
448
449Any string eval which is executed by code executing in a compartment,
450or by code called from code executing in a compartment, will be eval'd
451in the namespace of the compartment. This is potentially a serious
452problem.
453
454Consider a function foo() in package pkg compiled outside a compartment
455but shared with it. Assume the compartment has a root package called
1fef88e7 456'Root'. If foo() contains an eval statement like eval '$foo = 1' then,
2ded1cc1 457normally, $pkg::foo will be set to 1. If foo() is called from the
458compartment (by whatever means) then instead of setting $pkg::foo, the
459eval will actually set $Root::pkg::foo.
460
461This can easily be demonstrated by using a module, such as the Socket
462module, which uses eval "..." as part of an AUTOLOAD function. You can
463'use' the module outside the compartment and share an (autoloaded)
464function with the compartment. If an autoload is triggered by code in
465the compartment, or by any code anywhere that is called by any means
466from the compartment, then the eval in the Socket module's AUTOLOAD
467function happens in the namespace of the compartment. Any variables
468created or used by the eval'd code are now under the control of
469the code in the compartment.
470
471A similar effect applies to I<all> runtime symbol lookups in code
472called from a compartment but not compiled within it.
473
474
475
476=item rdo (FILENAME)
477
478This evaluates the contents of file FILENAME inside the compartment.
479See above documentation on the B<reval> method for further details.
480
481=item root (NAMESPACE)
482
483This method returns the name of the package that is the root of the
484compartment's namespace.
485
486Note that this behaviour differs from version 1.00 of the Safe module
487where the root module could be used to change the namespace. That
488functionality has been withdrawn pending deeper consideration.
489
490=item mask (MASK)
491
492This is a get-or-set method for the compartment's operator mask.
493
494With no MASK argument present, it returns the current operator mask of
495the compartment.
496
497With the MASK argument present, it sets the operator mask for the
498compartment (equivalent to calling the deny_only method).
499
500=back
501
502
503=head2 Some Safety Issues
504
505This section is currently just an outline of some of the things code in
506a compartment might do (intentionally or unintentionally) which can
507have an effect outside the compartment.
508
509=over 8
510
511=item Memory
512
513Consuming all (or nearly all) available memory.
514
515=item CPU
516
517Causing infinite loops etc.
518
519=item Snooping
520
521Copying private information out of your system. Even something as
522simple as your user name is of value to others. Much useful information
523could be gleaned from your environment variables for example.
524
525=item Signals
526
527Causing signals (especially SIGFPE and SIGALARM) to affect your process.
528
529Setting up a signal handler will need to be carefully considered
530and controlled. What mask is in effect when a signal handler
531gets called? If a user can get an imported function to get an
532exception and call the user's signal handler, does that user's
533restricted mask get re-instated before the handler is called?
534Does an imported handler get called with its original mask or
535the user's one?
536
537=item State Changes
538
539Ops such as chdir obviously effect the process as a whole and not just
540the code in the compartment. Ops such as rand and srand have a similar
541but more subtle effect.
542
543=back
544
545=head2 AUTHOR
546
547Originally designed and implemented by Malcolm Beattie,
548mbeattie@sable.ox.ac.uk.
549
550Reworked to use the Opcode module and other changes added by Tim Bunce
1fef88e7 551E<lt>F<Tim.Bunce@ig.co.uk>E<gt>.
2ded1cc1 552
553=cut
554