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