4 use Scalar::Util qw(reftype refaddr);
6 $Safe::VERSION = "2.37";
8 # *** Don't declare any lexicals above this point ***
10 # This function should return a closure which contains an eval that can't
11 # see any lexicals in scope (apart from __ExPr__ which is unavoidable)
13 sub lexless_anon_sub {
15 # $_[1] is strict flag;
16 my $__ExPr__ = $_[2]; # must be a lexical to create the closure that
17 # can be used to pass the value into the safe
20 # Create anon sub ref in root of compartment.
21 # Uses a closure (on $__ExPr__) to pass in the code to be executed.
22 # (eval on one line to keep line numbers as expected by caller)
24 'package %s; %s sub { @_=(); eval q[local *SIG; my $__ExPr__;] . $__ExPr__; }',
25 $_[0], $_[1] ? 'use strict;' : '';
37 if (defined &B::sub_generation) {
38 *sub_generation = \&B::sub_generation;
41 # fake sub generation changing for perls < 5.8.9
42 my $sg; *sub_generation = sub { ++$sg };
47 opset opset_to_ops opmask_add
48 empty_opset full_opset invert_opset verify_opset
49 opdesc opcodes opmask define_optag opset_to_hex
52 *ops_to_opset = \&opset; # Temporary alias for old Penguins
54 # Regular expressions and other unicode-aware code may need to call
55 # utf8->SWASHNEW (via perl's utf8.c). That will fail unless we share the
57 # Sadly we can't just add utf8::SWASHNEW to $default_share because perl's
58 # utf8.c code does a fetchmethod on SWASHNEW to check if utf8.pm is loaded,
59 # and sharing makes it look like the method exists.
60 # The simplest and most robust fix is to ensure the utf8 module is loaded when
61 # Safe is loaded. Then we can add utf8::SWASHNEW to $default_share.
63 # we must ensure that utf8_heavy.pl, where SWASHNEW is defined, is loaded
64 # but without depending on too much knowledge of that implementation detail.
65 # This code (//i on a unicode string) should ensure utf8 is fully loaded
66 # and also loads the ToFold SWASH, unless things change so that these
67 # particular code points don't cause it to load.
68 # (Swashes are cached internally by perl in PL_utf8_* variables
69 # independent of being inside/outside of Safe. So once loaded they can be)
70 do { my $a = pack('U',0x100); my $b = chr 0x101; utf8::upgrade $b; $a =~ /$b/i };
71 # now we can safely include utf8::SWASHNEW in $default_share defined below.
74 # share *_ and functions defined in universal.c
75 # Don't share stuff like *UNIVERSAL:: otherwise code from the
76 # compartment can 0wn functions in UNIVERSAL
77 my $default_share = [qw[
89 &utf8::native_to_unicode
90 &utf8::unicode_to_native
99 ]), ($] >= 5.008001 && qw[
101 ]), ($] >= 5.010 && qw[
123 &version::vxs::declare
125 &version::vxs::_VERSION
126 &version::vxs::stringify
130 ]), ($] >= 5.011 && qw[
132 ]), ($] >= 5.010 && $] < 5.014 && qw[
133 &Tie::Hash::NamedCapture::FETCH
134 &Tie::Hash::NamedCapture::STORE
135 &Tie::Hash::NamedCapture::DELETE
136 &Tie::Hash::NamedCapture::CLEAR
137 &Tie::Hash::NamedCapture::EXISTS
138 &Tie::Hash::NamedCapture::FIRSTKEY
139 &Tie::Hash::NamedCapture::NEXTKEY
140 &Tie::Hash::NamedCapture::SCALAR
141 &Tie::Hash::NamedCapture::flags
143 if (defined $Devel::Cover::VERSION) {
144 push @$default_share, '&Devel::Cover::use_file';
148 my($class, $root, $mask) = @_;
152 if (defined($root)) {
153 croak "Can't use \"$root\" as root name"
154 if $root =~ /^main\b/ or $root !~ /^\w[:\w]*$/;
155 $obj->{Root} = $root;
159 $obj->{Root} = "Safe::Root".$default_root++;
163 # use permit/deny methods instead till interface issues resolved
164 # XXX perhaps new Safe 'Root', mask => $mask, foo => bar, ...;
165 croak "Mask parameter to new no longer supported" if defined $mask;
166 $obj->permit_only(':default');
168 # We must share $_ and @_ with the compartment or else ops such
169 # as split, length and so on won't default to $_ properly, nor
170 # will passing argument to subroutines work (via @_). In fact,
171 # for reasons I don't completely understand, we need to share
172 # the whole glob *_ rather than $_ and @_ separately, otherwise
173 # @_ in non default packages within the compartment don't work.
174 $obj->share_from('main', $default_share);
176 Opcode::_safe_pkg_prep($obj->{Root}) if($Opcode::VERSION > 1.04);
183 $obj->erase('DESTROY') if $obj->{Erase};
187 my ($obj, $action) = @_;
188 my $pkg = $obj->root();
192 $pkg = "main::$pkg\::"; # expand to full symbol table name
193 ($stem, $leaf) = $pkg =~ m/(.*::)(\w+::)$/;
195 # The 'my $foo' is needed! Without it you get an
196 # 'Attempt to free unreferenced scalar' warning!
197 my $stem_symtab = *{$stem}{HASH};
199 #warn "erase($pkg) stem=$stem, leaf=$leaf";
200 #warn " stem_symtab hash ".scalar(%$stem_symtab)."\n";
201 # ", join(', ', %$stem_symtab),"\n";
203 # delete $stem_symtab->{$leaf};
205 my $leaf_glob = $stem_symtab->{$leaf};
206 my $leaf_symtab = *{$leaf_glob}{HASH};
207 # warn " leaf_symtab ", join(', ', %$leaf_symtab),"\n";
209 #delete $leaf_symtab->{'__ANON__'};
210 #delete $leaf_symtab->{'foo'};
211 #delete $leaf_symtab->{'main::'};
212 # my $foo = undef ${"$stem\::"}{"$leaf\::"};
214 if ($action and $action eq 'DESTROY') {
215 delete $stem_symtab->{$leaf};
217 $obj->share_from('main', $default_share);
231 croak("Safe root method now read-only") if @_;
238 return $obj->{Mask} unless @_;
242 # v1 compatibility methods
243 sub trap { shift->deny(@_) }
244 sub untrap { shift->permit(@_) }
248 $obj->{Mask} |= opset(@_);
252 $obj->{Mask} = opset(@_);
258 $obj->{Mask} &= invert_opset opset(@_);
262 $obj->{Mask} = invert_opset opset(@_);
268 print opset_to_hex($obj->{Mask}),"\n";
273 my($obj, @vars) = @_;
274 $obj->share_from(scalar(caller), \@vars);
282 my $no_record = shift || 0;
283 my $root = $obj->root();
284 croak("vars not an array ref") unless ref $vars eq 'ARRAY';
286 # Check that 'from' package actually exists
287 croak("Package \"$pkg\" does not exist")
288 unless keys %{"$pkg\::"};
290 foreach $arg (@$vars) {
291 # catch some $safe->share($var) errors:
293 $type = $1 if ($var = $arg) =~ s/^(\W)//;
294 # warn "share_from $pkg $type $var";
295 for (1..2) { # assign twice to avoid any 'used once' warnings
296 *{$root."::$var"} = (!$type) ? \&{$pkg."::$var"}
297 : ($type eq '&') ? \&{$pkg."::$var"}
298 : ($type eq '$') ? \${$pkg."::$var"}
299 : ($type eq '@') ? \@{$pkg."::$var"}
300 : ($type eq '%') ? \%{$pkg."::$var"}
301 : ($type eq '*') ? *{$pkg."::$var"}
302 : croak(qq(Can't share "$type$var" of unknown type));
305 $obj->share_record($pkg, $vars) unless $no_record or !$vars;
313 my $shares = \%{$obj->{Shares} ||= {}};
314 # Record shares using keys of $obj->{Shares}. See reinit.
315 @{$shares}{@$vars} = ($pkg) x @$vars if @$vars;
321 my $shares = \%{$obj->{Shares} ||= {}};
323 while(($var, $pkg) = each %$shares) {
324 # warn "share_redo $pkg\:: $var";
325 $obj->share_from($pkg, [ $var ], 1);
331 delete shift->{Shares};
336 my ($obj, $var) = @_;
338 return *{$obj->root()."::$var"};
342 my ($root, $saved_refs) = @_;
345 foreach my $hook (qw(DESTROY AUTOLOAD), grep /^\(/, keys %$root) {
346 push @$saved_refs, \*{$root.$hook};
347 delete ${$root}{$hook};
350 for (grep /::$/, keys %$root) {
351 next if \%{$root.$_} eq \%$root;
352 _clean_stash($root.$_, $saved_refs);
357 my ($obj, $expr, $strict) = @_;
358 die "Bad Safe object" unless $obj->isa('Safe');
360 my $root = $obj->{Root};
362 my $evalsub = lexless_anon_sub($root, $strict, $expr);
364 my $sg = sub_generation();
365 my @subret = (wantarray)
366 ? Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub)
367 : scalar Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub);
368 _clean_stash($root.'::') if $sg != sub_generation();
369 $obj->wrap_code_refs_within(@subret);
370 return (wantarray) ? @subret : $subret[0];
375 sub wrap_code_refs_within {
379 $obj->_find_code_refs('wrap_code_ref', @_);
383 sub _find_code_refs {
388 my $reftype = $item && reftype $item
391 # skip references already seen
392 next if ++$OID{refaddr $item} > 1;
394 if ($reftype eq 'ARRAY') {
395 $obj->_find_code_refs($visitor, @$item);
397 elsif ($reftype eq 'HASH') {
398 $obj->_find_code_refs($visitor, values %$item);
401 elsif ($reftype eq 'CODE') {
402 $item = $obj->$visitor($item);
409 my ($obj, $sub) = @_;
410 die "Bad safe object" unless $obj->isa('Safe');
412 # wrap code ref $sub with _safe_call_sv so that, when called, the
413 # execution will happen with the compartment fully 'in effect'.
415 croak "Not a CODE reference"
416 if reftype $sub ne 'CODE';
419 my @args = @_; # lexical to close over
420 my $sub_with_args = sub { $sub->(@args) };
425 local $@; # needed due to perl_call_sv(sv, G_EVAL|G_KEEPERR)
426 my $sg = sub_generation();
427 @subret = (wantarray)
428 ? Opcode::_safe_call_sv($obj->{Root}, $obj->{Mask}, $sub_with_args)
429 : scalar Opcode::_safe_call_sv($obj->{Root}, $obj->{Mask}, $sub_with_args);
431 _clean_stash($obj->{Root}.'::') if $sg != sub_generation();
433 if ($error) { # rethrow exception
434 $error =~ s/\t\(in cleanup\) //; # prefix added by G_KEEPERR
437 return (wantarray) ? @subret : $subret[0];
445 my ($obj, $file) = @_;
446 die "Bad Safe object" unless $obj->isa('Safe');
448 my $root = $obj->{Root};
450 my $sg = sub_generation();
452 sprintf('package %s; sub { @_ = (); do $file }', $root);
453 my @subret = (wantarray)
454 ? Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub)
455 : scalar Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub);
456 _clean_stash($root.'::') if $sg != sub_generation();
457 $obj->wrap_code_refs_within(@subret);
458 return (wantarray) ? @subret : $subret[0];
468 Safe - Compile and execute code in restricted compartments
474 $compartment = new Safe;
476 $compartment->permit(qw(time sort :browse));
478 $result = $compartment->reval($unsafe_code);
482 The Safe extension module allows the creation of compartments
483 in which perl code can be evaluated. Each compartment has
487 =item a new namespace
489 The "root" of the namespace (i.e. "main::") is changed to a
490 different package and code evaluated in the compartment cannot
491 refer to variables outside this namespace, even with run-time
492 glob lookups and other tricks.
494 Code which is compiled outside the compartment can choose to place
495 variables into (or I<share> variables with) the compartment's namespace
496 and only that data will be visible to code evaluated in the
499 By default, the only variables shared with compartments are the
500 "underscore" variables $_ and @_ (and, technically, the less frequently
501 used %_, the _ filehandle and so on). This is because otherwise perl
502 operators which default to $_ will not work and neither will the
503 assignment of arguments to @_ on subroutine entry.
505 =item an operator mask
507 Each compartment has an associated "operator mask". Recall that
508 perl code is compiled into an internal format before execution.
509 Evaluating perl code (e.g. via "eval" or "do 'file'") causes
510 the code to be compiled into an internal format and then,
511 provided there was no error in the compilation, executed.
512 Code evaluated in a compartment compiles subject to the
513 compartment's operator mask. Attempting to evaluate code in a
514 compartment which contains a masked operator will cause the
515 compilation to fail with an error. The code will not be executed.
517 The default operator mask for a newly created compartment is
518 the ':default' optag.
520 It is important that you read the L<Opcode> module documentation
521 for more information, especially for detailed definitions of opnames,
524 Since it is only at the compilation stage that the operator mask
525 applies, controlled access to potentially unsafe operations can
526 be achieved by having a handle to a wrapper subroutine (written
527 outside the compartment) placed into the compartment. For example,
531 # vet arguments and perform potentially unsafe operations
533 $cpt->share('&wrapper');
540 The authors make B<no warranty>, implied or otherwise, about the
541 suitability of this software for safety or security purposes.
543 The authors shall not in any case be liable for special, incidental,
544 consequential, indirect or other similar damages arising from the use
547 Your mileage will vary. If in any doubt B<do not use it>.
552 To create a new compartment, use
556 Optional argument is (NAMESPACE), where NAMESPACE is the root namespace
557 to use for the compartment (defaults to "Safe::Root0", incremented for
558 each new compartment).
560 Note that version 1.00 of the Safe module supported a second optional
561 parameter, MASK. That functionality has been withdrawn pending deeper
562 consideration. Use the permit and deny methods described below.
564 The following methods can then be used on the compartment
565 object returned by the above constructor. The object argument
566 is implicit in each case.
569 =head2 permit (OP, ...)
571 Permit the listed operators to be used when compiling code in the
572 compartment (in I<addition> to any operators already permitted).
574 You can list opcodes by names, or use a tag name; see
575 L<Opcode/"Predefined Opcode Tags">.
577 =head2 permit_only (OP, ...)
579 Permit I<only> the listed operators to be used when compiling code in
580 the compartment (I<no> other operators are permitted).
582 =head2 deny (OP, ...)
584 Deny the listed operators from being used when compiling code in the
585 compartment (other operators may still be permitted).
587 =head2 deny_only (OP, ...)
589 Deny I<only> the listed operators from being used when compiling code
590 in the compartment (I<all> other operators will be permitted, so you probably
591 don't want to use this method).
593 =head2 trap (OP, ...), untrap (OP, ...)
595 The trap and untrap methods are synonyms for deny and permit
598 =head2 share (NAME, ...)
600 This shares the variable(s) in the argument list with the compartment.
601 This is almost identical to exporting variables using the L<Exporter>
604 Each NAME must be the B<name> of a non-lexical variable, typically
605 with the leading type identifier included. A bareword is treated as a
608 Examples of legal names are '$foo' for a scalar, '@foo' for an
609 array, '%foo' for a hash, '&foo' or 'foo' for a subroutine and '*foo'
610 for a glob (i.e. all symbol table entries associated with "foo",
611 including scalar, array, hash, sub and filehandle).
613 Each NAME is assumed to be in the calling package. See share_from
614 for an alternative method (which C<share> uses).
616 =head2 share_from (PACKAGE, ARRAYREF)
618 This method is similar to share() but allows you to explicitly name the
619 package that symbols should be shared from. The symbol names (including
620 type characters) are supplied as an array reference.
622 $safe->share_from('main', [ '$foo', '%bar', 'func' ]);
624 Names can include package names, which are relative to the specified PACKAGE.
625 So these two calls have the same effect:
627 $safe->share_from('Scalar::Util', [ 'reftype' ]);
628 $safe->share_from('main', [ 'Scalar::Util::reftype' ]);
630 =head2 varglob (VARNAME)
632 This returns a glob reference for the symbol table entry of VARNAME in
633 the package of the compartment. VARNAME must be the B<name> of a
634 variable without any leading type marker. For example:
636 ${$cpt->varglob('foo')} = "Hello world";
638 has the same effect as:
640 $cpt = new Safe 'Root';
641 $Root::foo = "Hello world";
643 but avoids the need to know $cpt's package name.
646 =head2 reval (STRING, STRICT)
648 This evaluates STRING as perl code inside the compartment.
650 The code can only see the compartment's namespace (as returned by the
651 B<root> method). The compartment's root package appears to be the
652 C<main::> package to the code inside the compartment.
654 Any attempt by the code in STRING to use an operator which is not permitted
655 by the compartment will cause an error (at run-time of the main program
656 but at compile-time for the code in STRING). The error is of the form
657 "'%s' trapped by operation mask...".
659 If an operation is trapped in this way, then the code in STRING will
660 not be executed. If such a trapped operation occurs or any other
661 compile-time or return error, then $@ is set to the error message, just
664 If there is no error, then the method returns the value of the last
665 expression evaluated, or a return statement may be used, just as with
666 subroutines and B<eval()>. The context (list or scalar) is determined
667 by the caller as usual.
669 If the return value of reval() is (or contains) any code reference,
670 those code references are wrapped to be themselves executed always
671 in the compartment. See L</wrap_code_refs_within>.
673 The formerly undocumented STRICT argument sets strictness: if true
674 'use strict;' is used, otherwise it uses 'no strict;'. B<Note>: if
675 STRICT is omitted 'no strict;' is the default.
679 If the entereval op is permitted then the code can use eval "..." to
680 'hide' code which might use denied ops. This is not a major problem
681 since when the code tries to execute the eval it will fail because the
682 opmask is still in effect. However this technique would allow clever,
683 and possibly harmful, code to 'probe' the boundaries of what is
686 Any string eval which is executed by code executing in a compartment,
687 or by code called from code executing in a compartment, will be eval'd
688 in the namespace of the compartment. This is potentially a serious
691 Consider a function foo() in package pkg compiled outside a compartment
692 but shared with it. Assume the compartment has a root package called
693 'Root'. If foo() contains an eval statement like eval '$foo = 1' then,
694 normally, $pkg::foo will be set to 1. If foo() is called from the
695 compartment (by whatever means) then instead of setting $pkg::foo, the
696 eval will actually set $Root::pkg::foo.
698 This can easily be demonstrated by using a module, such as the Socket
699 module, which uses eval "..." as part of an AUTOLOAD function. You can
700 'use' the module outside the compartment and share an (autoloaded)
701 function with the compartment. If an autoload is triggered by code in
702 the compartment, or by any code anywhere that is called by any means
703 from the compartment, then the eval in the Socket module's AUTOLOAD
704 function happens in the namespace of the compartment. Any variables
705 created or used by the eval'd code are now under the control of
706 the code in the compartment.
708 A similar effect applies to I<all> runtime symbol lookups in code
709 called from a compartment but not compiled within it.
711 =head2 rdo (FILENAME)
713 This evaluates the contents of file FILENAME inside the compartment.
714 See above documentation on the B<reval> method for further details.
716 =head2 root (NAMESPACE)
718 This method returns the name of the package that is the root of the
719 compartment's namespace.
721 Note that this behaviour differs from version 1.00 of the Safe module
722 where the root module could be used to change the namespace. That
723 functionality has been withdrawn pending deeper consideration.
727 This is a get-or-set method for the compartment's operator mask.
729 With no MASK argument present, it returns the current operator mask of
732 With the MASK argument present, it sets the operator mask for the
733 compartment (equivalent to calling the deny_only method).
735 =head2 wrap_code_ref (CODEREF)
737 Returns a reference to an anonymous subroutine that, when executed, will call
738 CODEREF with the Safe compartment 'in effect'. In other words, with the
739 package namespace adjusted and the opmask enabled.
741 Note that the opmask doesn't affect the already compiled code, it only affects
742 any I<further> compilation that the already compiled code may try to perform.
744 This is particularly useful when applied to code references returned from reval().
746 (It also provides a kind of workaround for RT#60374: "Safe.pm sort {} bug with
747 -Dusethreads". See L<http://rt.perl.org/rt3//Public/Bug/Display.html?id=60374>
748 for I<much> more detail.)
750 =head2 wrap_code_refs_within (...)
752 Wraps any CODE references found within the arguments by replacing each with the
753 result of calling L</wrap_code_ref> on the CODE reference. Any ARRAY or HASH
754 references in the arguments are inspected recursively.
760 This section is just an outline of some of the things code in a compartment
761 might do (intentionally or unintentionally) which can have an effect outside
768 Consuming all (or nearly all) available memory.
772 Causing infinite loops etc.
776 Copying private information out of your system. Even something as
777 simple as your user name is of value to others. Much useful information
778 could be gleaned from your environment variables for example.
782 Causing signals (especially SIGFPE and SIGALARM) to affect your process.
784 Setting up a signal handler will need to be carefully considered
785 and controlled. What mask is in effect when a signal handler
786 gets called? If a user can get an imported function to get an
787 exception and call the user's signal handler, does that user's
788 restricted mask get re-instated before the handler is called?
789 Does an imported handler get called with its original mask or
794 Ops such as chdir obviously effect the process as a whole and not just
795 the code in the compartment. Ops such as rand and srand have a similar
796 but more subtle effect.
802 Originally designed and implemented by Malcolm Beattie.
804 Reworked to use the Opcode module and other changes added by Tim Bunce.
806 Currently maintained by the Perl 5 Porters, <perl5-porters@perl.org>.