xref: /openbsd/gnu/usr.bin/perl/dist/Safe/Safe.pm (revision 3d61058a)
1package Safe;
2
3use 5.003_11;
4use Scalar::Util qw(reftype refaddr);
5
6$Safe::VERSION = "2.46";
7
8# *** Don't declare any lexicals above this point ***
9#
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)
12
13sub lexless_anon_sub {
14                 # $_[0] is package;
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
18                            # world
19
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)
23    eval sprintf
24    'package %s; %s sub { @_=(); local *SIG; eval q[my $__ExPr__;] . $__ExPr__; }',
25                $_[0], $_[1] ? 'use strict;' : '';
26}
27
28use strict;
29use Carp;
30BEGIN { eval q{
31    use Carp::Heavy;
32} }
33
34use B ();
35BEGIN {
36    no strict 'refs';
37    if (defined &B::sub_generation) {
38        *sub_generation = \&B::sub_generation;
39    }
40    else {
41        # fake sub generation changing for perls < 5.8.9
42        my $sg; *sub_generation = sub { ++$sg };
43    }
44}
45
46use Opcode 1.01, qw(
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
50);
51
52*ops_to_opset = \&opset;   # Temporary alias for old Penguins
53
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
56# SWASHNEW method.
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.
62require utf8;
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)
70do { my $a = pack('U',0x100); $a =~ m/\x{1234}/; $a =~ tr/\x{1234}//; };
71# now we can safely include utf8::SWASHNEW in $default_share defined below.
72
73my $default_root  = 0;
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
77my $default_share = [qw[
78    *_
79    &PerlIO::get_layers
80    &UNIVERSAL::import
81    &UNIVERSAL::isa
82    &UNIVERSAL::can
83    &UNIVERSAL::unimport
84    &UNIVERSAL::VERSION
85    &utf8::is_utf8
86    &utf8::valid
87    &utf8::encode
88    &utf8::decode
89    &utf8::upgrade
90    &utf8::downgrade
91    &utf8::native_to_unicode
92    &utf8::unicode_to_native
93    &utf8::SWASHNEW
94    $version::VERSION
95    $version::CLASS
96    $version::STRICT
97    $version::LAX
98    @version::ISA
99], ($] < 5.010 && qw[
100    &utf8::SWASHGET
101]), ($] >= 5.008001 && qw[
102    &Regexp::DESTROY
103]), ($] >= 5.010 && qw[
104    &re::is_regexp
105    &re::regname
106    &re::regnames
107    &re::regnames_count
108    &UNIVERSAL::DOES
109    &version::()
110    &version::new
111    &version::(""
112    &version::stringify
113    &version::(0+
114    &version::numify
115    &version::normal
116    &version::(cmp
117    &version::(<=>
118    &version::vcmp
119    &version::(bool
120    &version::boolean
121    &version::(nomethod
122    &version::noop
123    &version::is_alpha
124    &version::qv
125    &version::vxs::declare
126    &version::vxs::qv
127    &version::vxs::_VERSION
128    &version::vxs::stringify
129    &version::vxs::new
130    &version::vxs::parse
131    &version::vxs::VCMP
132]), ($] >= 5.011 && qw[
133    &re::regexp_pattern
134]), ($] >= 5.010 && $] < 5.014 && qw[
135    &Tie::Hash::NamedCapture::FETCH
136    &Tie::Hash::NamedCapture::STORE
137    &Tie::Hash::NamedCapture::DELETE
138    &Tie::Hash::NamedCapture::CLEAR
139    &Tie::Hash::NamedCapture::EXISTS
140    &Tie::Hash::NamedCapture::FIRSTKEY
141    &Tie::Hash::NamedCapture::NEXTKEY
142    &Tie::Hash::NamedCapture::SCALAR
143    &Tie::Hash::NamedCapture::flags
144])];
145if (defined $Devel::Cover::VERSION) {
146    push @$default_share, '&Devel::Cover::use_file';
147}
148
149sub new {
150    my($class, $root, $mask) = @_;
151    my $obj = {};
152    bless $obj, $class;
153
154    if (defined($root)) {
155        croak "Can't use \"$root\" as root name"
156            if $root =~ /^main\b/ or $root !~ /^\w[:\w]*$/;
157        $obj->{Root}  = $root;
158        $obj->{Erase} = 0;
159    }
160    else {
161        $obj->{Root}  = "Safe::Root".$default_root++;
162        $obj->{Erase} = 1;
163    }
164
165    # use permit/deny methods instead till interface issues resolved
166    # XXX perhaps new Safe 'Root', mask => $mask, foo => bar, ...;
167    croak "Mask parameter to new no longer supported" if defined $mask;
168    $obj->permit_only(':default');
169
170    # We must share $_ and @_ with the compartment or else ops such
171    # as split, length and so on won't default to $_ properly, nor
172    # will passing argument to subroutines work (via @_). In fact,
173    # for reasons I don't completely understand, we need to share
174    # the whole glob *_ rather than $_ and @_ separately, otherwise
175    # @_ in non default packages within the compartment don't work.
176    $obj->share_from('main', $default_share);
177
178    Opcode::_safe_pkg_prep($obj->{Root}) if($Opcode::VERSION > 1.04);
179
180    return $obj;
181}
182
183sub DESTROY {
184    my $obj = shift;
185    $obj->erase('DESTROY') if $obj->{Erase};
186}
187
188sub erase {
189    my ($obj, $action) = @_;
190    my $pkg = $obj->root();
191    my ($stem, $leaf);
192
193    no strict 'refs';
194    $pkg = "main::$pkg\::";     # expand to full symbol table name
195    ($stem, $leaf) = $pkg =~ m/(.*::)(\w+::)$/;
196
197    # The 'my $foo' is needed! Without it you get an
198    # 'Attempt to free unreferenced scalar' warning!
199    my $stem_symtab = *{$stem}{HASH};
200
201    #warn "erase($pkg) stem=$stem, leaf=$leaf";
202    #warn " stem_symtab hash ".scalar(%$stem_symtab)."\n";
203    # ", join(', ', %$stem_symtab),"\n";
204
205#    delete $stem_symtab->{$leaf};
206
207    my $leaf_glob   = $stem_symtab->{$leaf};
208    my $leaf_symtab = *{$leaf_glob}{HASH};
209#    warn " leaf_symtab ", join(', ', %$leaf_symtab),"\n";
210    %$leaf_symtab = ();
211    #delete $leaf_symtab->{'__ANON__'};
212    #delete $leaf_symtab->{'foo'};
213    #delete $leaf_symtab->{'main::'};
214#    my $foo = undef ${"$stem\::"}{"$leaf\::"};
215
216    if ($action and $action eq 'DESTROY') {
217        delete $stem_symtab->{$leaf};
218    } else {
219        $obj->share_from('main', $default_share);
220    }
221    1;
222}
223
224
225sub reinit {
226    my $obj= shift;
227    $obj->erase;
228    $obj->share_redo;
229}
230
231sub root {
232    my $obj = shift;
233    croak("Safe root method now read-only") if @_;
234    return $obj->{Root};
235}
236
237
238sub mask {
239    my $obj = shift;
240    return $obj->{Mask} unless @_;
241    $obj->deny_only(@_);
242}
243
244# v1 compatibility methods
245sub trap   { shift->deny(@_)   }
246sub untrap { shift->permit(@_) }
247
248sub deny {
249    my $obj = shift;
250    $obj->{Mask} |= opset(@_);
251}
252sub deny_only {
253    my $obj = shift;
254    $obj->{Mask} = opset(@_);
255}
256
257sub permit {
258    my $obj = shift;
259    # XXX needs testing
260    $obj->{Mask} &= invert_opset opset(@_);
261}
262sub permit_only {
263    my $obj = shift;
264    $obj->{Mask} = invert_opset opset(@_);
265}
266
267
268sub dump_mask {
269    my $obj = shift;
270    print opset_to_hex($obj->{Mask}),"\n";
271}
272
273
274sub share {
275    my($obj, @vars) = @_;
276    $obj->share_from(scalar(caller), \@vars);
277}
278
279
280sub share_from {
281    my $obj = shift;
282    my $pkg = shift;
283    my $vars = shift;
284    my $no_record = shift || 0;
285    my $root = $obj->root();
286    croak("vars not an array ref") unless ref $vars eq 'ARRAY';
287    no strict 'refs';
288    # Check that 'from' package actually exists
289    croak("Package \"$pkg\" does not exist")
290        unless keys %{"$pkg\::"};
291    my $arg;
292    foreach $arg (@$vars) {
293        # catch some $safe->share($var) errors:
294        my ($var, $type);
295        $type = $1 if ($var = $arg) =~ s/^(\W)//;
296        # warn "share_from $pkg $type $var";
297        for (1..2) { # assign twice to avoid any 'used once' warnings
298            *{$root."::$var"} = (!$type)   ? \&{$pkg."::$var"}
299                          : ($type eq '&') ? \&{$pkg."::$var"}
300                          : ($type eq '$') ? \${$pkg."::$var"}
301                          : ($type eq '@') ? \@{$pkg."::$var"}
302                          : ($type eq '%') ? \%{$pkg."::$var"}
303                          : ($type eq '*') ?  *{$pkg."::$var"}
304                          : croak(qq(Can't share "$type$var" of unknown type));
305        }
306    }
307    $obj->share_record($pkg, $vars) unless $no_record or !$vars;
308}
309
310
311sub share_record {
312    my $obj = shift;
313    my $pkg = shift;
314    my $vars = shift;
315    my $shares = \%{$obj->{Shares} ||= {}};
316    # Record shares using keys of $obj->{Shares}. See reinit.
317    @{$shares}{@$vars} = ($pkg) x @$vars if @$vars;
318}
319
320
321sub share_redo {
322    my $obj = shift;
323    my $shares = \%{$obj->{Shares} ||= {}};
324    my($var, $pkg);
325    while(($var, $pkg) = each %$shares) {
326        # warn "share_redo $pkg\:: $var";
327        $obj->share_from($pkg,  [ $var ], 1);
328    }
329}
330
331
332sub share_forget {
333    delete shift->{Shares};
334}
335
336
337sub varglob {
338    my ($obj, $var) = @_;
339    no strict 'refs';
340    return *{$obj->root()."::$var"};
341}
342
343sub _clean_stash {
344    my ($root, $saved_refs) = @_;
345    $saved_refs ||= [];
346    no strict 'refs';
347    foreach my $hook (qw(DESTROY AUTOLOAD), grep /^\(/, keys %$root) {
348        push @$saved_refs, \*{$root.$hook};
349        delete ${$root}{$hook};
350    }
351
352    for (grep /::$/, keys %$root) {
353        next if \%{$root.$_} eq \%$root;
354        _clean_stash($root.$_, $saved_refs);
355    }
356}
357
358sub reval {
359    my ($obj, $expr, $strict) = @_;
360    die "Bad Safe object" unless $obj->isa('Safe');
361
362    my $root = $obj->{Root};
363
364    my $evalsub = lexless_anon_sub($root, $strict, $expr);
365    # propagate context
366    my $sg = sub_generation();
367    my @subret;
368    if (defined wantarray) {
369        @subret = (wantarray)
370               ?        Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub)
371               : scalar Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub);
372    }
373    else {
374        Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub);
375    }
376    _clean_stash($root.'::') if $sg != sub_generation();
377    $obj->wrap_code_refs_within(@subret);
378    return (wantarray) ? @subret : $subret[0];
379}
380
381my %OID;
382
383sub wrap_code_refs_within {
384    my $obj = shift;
385
386    %OID = ();
387    $obj->_find_code_refs('wrap_code_ref', @_);
388}
389
390
391sub _find_code_refs {
392    my $obj = shift;
393    my $visitor = shift;
394
395    for my $item (@_) {
396        my $reftype = $item && reftype $item
397            or next;
398
399        # skip references already seen
400        next if ++$OID{refaddr $item} > 1;
401
402        if ($reftype eq 'ARRAY') {
403            $obj->_find_code_refs($visitor, @$item);
404        }
405        elsif ($reftype eq 'HASH') {
406            $obj->_find_code_refs($visitor, values %$item);
407        }
408        # XXX GLOBs?
409        elsif ($reftype eq 'CODE') {
410            $item = $obj->$visitor($item);
411        }
412    }
413}
414
415
416sub wrap_code_ref {
417    my ($obj, $sub) = @_;
418    die "Bad safe object" unless $obj->isa('Safe');
419
420    # wrap code ref $sub with _safe_call_sv so that, when called, the
421    # execution will happen with the compartment fully 'in effect'.
422
423    croak "Not a CODE reference"
424        if reftype $sub ne 'CODE';
425
426    my $ret = sub {
427        my @args = @_; # lexical to close over
428        my $sub_with_args = sub { $sub->(@args) };
429
430        my @subret;
431        my $error;
432        do {
433            local $@;  # needed due to perl_call_sv(sv, G_EVAL|G_KEEPERR)
434            my $sg = sub_generation();
435            @subret = (wantarray)
436                ?        Opcode::_safe_call_sv($obj->{Root}, $obj->{Mask}, $sub_with_args)
437                : scalar Opcode::_safe_call_sv($obj->{Root}, $obj->{Mask}, $sub_with_args);
438            $error = $@;
439            _clean_stash($obj->{Root}.'::') if $sg != sub_generation();
440        };
441        if ($error) { # rethrow exception
442            $error =~ s/\t\(in cleanup\) //; # prefix added by G_KEEPERR
443            die $error;
444        }
445        return (wantarray) ? @subret : $subret[0];
446    };
447
448    return $ret;
449}
450
451
452sub rdo {
453    my ($obj, $file) = @_;
454    die "Bad Safe object" unless $obj->isa('Safe');
455
456    my $root = $obj->{Root};
457
458    my $sg = sub_generation();
459    my $evalsub = eval
460            sprintf('package %s; sub { @_ = (); do $file }', $root);
461    my @subret = (wantarray)
462               ?        Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub)
463               : scalar Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub);
464    _clean_stash($root.'::') if $sg != sub_generation();
465    $obj->wrap_code_refs_within(@subret);
466    return (wantarray) ? @subret : $subret[0];
467}
468
469
4701;
471
472__END__
473
474=head1 NAME
475
476Safe - Compile and execute code in restricted compartments
477
478=head1 SYNOPSIS
479
480  use Safe;
481
482  $compartment = new Safe;
483
484  $compartment->permit(qw(time sort :browse));
485
486  $result = $compartment->reval($unsafe_code);
487
488=head1 DESCRIPTION
489
490The Safe extension module allows the creation of compartments
491in which perl code can be evaluated. Each compartment has
492
493=over 8
494
495=item a new namespace
496
497The "root" of the namespace (i.e. "main::") is changed to a
498different package and code evaluated in the compartment cannot
499refer to variables outside this namespace, even with run-time
500glob lookups and other tricks.
501
502Code which is compiled outside the compartment can choose to place
503variables into (or I<share> variables with) the compartment's namespace
504and only that data will be visible to code evaluated in the
505compartment.
506
507By default, the only variables shared with compartments are the
508"underscore" variables $_ and @_ (and, technically, the less frequently
509used %_, the _ filehandle and so on). This is because otherwise perl
510operators which default to $_ will not work and neither will the
511assignment of arguments to @_ on subroutine entry.
512
513=item an operator mask
514
515Each compartment has an associated "operator mask". Recall that
516perl code is compiled into an internal format before execution.
517Evaluating perl code (e.g. via "eval" or "do 'file'") causes
518the code to be compiled into an internal format and then,
519provided there was no error in the compilation, executed.
520Code evaluated in a compartment compiles subject to the
521compartment's operator mask. Attempting to evaluate code in a
522compartment which contains a masked operator will cause the
523compilation to fail with an error. The code will not be executed.
524
525The default operator mask for a newly created compartment is
526the ':default' optag.
527
528It is important that you read the L<Opcode> module documentation
529for more information, especially for detailed definitions of opnames,
530optags and opsets.
531
532Since it is only at the compilation stage that the operator mask
533applies, controlled access to potentially unsafe operations can
534be achieved by having a handle to a wrapper subroutine (written
535outside the compartment) placed into the compartment. For example,
536
537    $cpt = new Safe;
538    sub wrapper {
539      # vet arguments and perform potentially unsafe operations
540    }
541    $cpt->share('&wrapper');
542
543=back
544
545
546=head1 WARNING
547
548The Safe module does not implement an effective sandbox for
549evaluating untrusted code with the perl interpreter.
550
551Bugs in the perl interpreter that could be abused to bypass
552Safe restrictions are not treated as vulnerabilities. See
553L<perlsecpolicy> for additional information.
554
555The authors make B<no warranty>, implied or otherwise, about the
556suitability of this software for safety or security purposes.
557
558The authors shall not in any case be liable for special, incidental,
559consequential, indirect or other similar damages arising from the use
560of this software.
561
562Your mileage will vary. If in any doubt B<do not use it>.
563
564
565=head1 METHODS
566
567To create a new compartment, use
568
569    $cpt = new Safe;
570
571Optional argument is (NAMESPACE), where NAMESPACE is the root namespace
572to use for the compartment (defaults to "Safe::Root0", incremented for
573each new compartment).
574
575Note that version 1.00 of the Safe module supported a second optional
576parameter, MASK.  That functionality has been withdrawn pending deeper
577consideration. Use the permit and deny methods described below.
578
579The following methods can then be used on the compartment
580object returned by the above constructor. The object argument
581is implicit in each case.
582
583
584=head2 permit (OP, ...)
585
586Permit the listed operators to be used when compiling code in the
587compartment (in I<addition> to any operators already permitted).
588
589You can list opcodes by names, or use a tag name; see
590L<Opcode/"Predefined Opcode Tags">.
591
592=head2 permit_only (OP, ...)
593
594Permit I<only> the listed operators to be used when compiling code in
595the compartment (I<no> other operators are permitted).
596
597=head2 deny (OP, ...)
598
599Deny the listed operators from being used when compiling code in the
600compartment (other operators may still be permitted).
601
602=head2 deny_only (OP, ...)
603
604Deny I<only> the listed operators from being used when compiling code
605in the compartment (I<all> other operators will be permitted, so you probably
606don't want to use this method).
607
608=head2 trap (OP, ...), untrap (OP, ...)
609
610The trap and untrap methods are synonyms for deny and permit
611respectfully.
612
613=head2 share (NAME, ...)
614
615This shares the variable(s) in the argument list with the compartment.
616This is almost identical to exporting variables using the L<Exporter>
617module.
618
619Each NAME must be the B<name> of a non-lexical variable, typically
620with the leading type identifier included. A bareword is treated as a
621function name.
622
623Examples of legal names are '$foo' for a scalar, '@foo' for an
624array, '%foo' for a hash, '&foo' or 'foo' for a subroutine and '*foo'
625for a glob (i.e.  all symbol table entries associated with "foo",
626including scalar, array, hash, sub and filehandle).
627
628Each NAME is assumed to be in the calling package. See share_from
629for an alternative method (which C<share> uses).
630
631=head2 share_from (PACKAGE, ARRAYREF)
632
633This method is similar to share() but allows you to explicitly name the
634package that symbols should be shared from. The symbol names (including
635type characters) are supplied as an array reference.
636
637    $safe->share_from('main', [ '$foo', '%bar', 'func' ]);
638
639Names can include package names, which are relative to the specified PACKAGE.
640So these two calls have the same effect:
641
642    $safe->share_from('Scalar::Util', [ 'reftype' ]);
643    $safe->share_from('main', [ 'Scalar::Util::reftype' ]);
644
645=head2 varglob (VARNAME)
646
647This returns a glob reference for the symbol table entry of VARNAME in
648the package of the compartment. VARNAME must be the B<name> of a
649variable without any leading type marker. For example:
650
651    ${$cpt->varglob('foo')} = "Hello world";
652
653has the same effect as:
654
655    $cpt = new Safe 'Root';
656    $Root::foo = "Hello world";
657
658but avoids the need to know $cpt's package name.
659
660
661=head2 reval (STRING, STRICT)
662
663This evaluates STRING as perl code inside the compartment.
664
665The code can only see the compartment's namespace (as returned by the
666B<root> method). The compartment's root package appears to be the
667C<main::> package to the code inside the compartment.
668
669Any attempt by the code in STRING to use an operator which is not permitted
670by the compartment will cause an error (at run-time of the main program
671but at compile-time for the code in STRING).  The error is of the form
672"'%s' trapped by operation mask...".
673
674If an operation is trapped in this way, then the code in STRING will
675not be executed. If such a trapped operation occurs or any other
676compile-time or return error, then $@ is set to the error message, just
677as with an eval().
678
679If there is no error, then the method returns the value of the last
680expression evaluated, or a return statement may be used, just as with
681subroutines and B<eval()>. The context (list or scalar) is determined
682by the caller as usual.
683
684If the return value of reval() is (or contains) any code reference,
685those code references are wrapped to be themselves executed always
686in the compartment. See L</wrap_code_refs_within>.
687
688The formerly undocumented STRICT argument sets strictness: if true
689'use strict;' is used, otherwise it uses 'no strict;'. B<Note>: if
690STRICT is omitted 'no strict;' is the default.
691
692Some points to note:
693
694If the entereval op is permitted then the code can use eval "..." to
695'hide' code which might use denied ops. This is not a major problem
696since when the code tries to execute the eval it will fail because the
697opmask is still in effect. However this technique would allow clever,
698and possibly harmful, code to 'probe' the boundaries of what is
699possible.
700
701Any string eval which is executed by code executing in a compartment,
702or by code called from code executing in a compartment, will be eval'd
703in the namespace of the compartment. This is potentially a serious
704problem.
705
706Consider a function foo() in package pkg compiled outside a compartment
707but shared with it. Assume the compartment has a root package called
708'Root'. If foo() contains an eval statement like eval '$foo = 1' then,
709normally, $pkg::foo will be set to 1.  If foo() is called from the
710compartment (by whatever means) then instead of setting $pkg::foo, the
711eval will actually set $Root::pkg::foo.
712
713This can easily be demonstrated by using a module, such as the Socket
714module, which uses eval "..." as part of an AUTOLOAD function. You can
715'use' the module outside the compartment and share an (autoloaded)
716function with the compartment. If an autoload is triggered by code in
717the compartment, or by any code anywhere that is called by any means
718from the compartment, then the eval in the Socket module's AUTOLOAD
719function happens in the namespace of the compartment. Any variables
720created or used by the eval'd code are now under the control of
721the code in the compartment.
722
723A similar effect applies to I<all> runtime symbol lookups in code
724called from a compartment but not compiled within it.
725
726=head2 rdo (FILENAME)
727
728This evaluates the contents of file FILENAME inside the compartment.
729It uses the same rules as perl's built-in C<do> to locate the file,
730poossibly using C<@INC>.
731
732See above documentation on the B<reval> method for further details.
733
734=head2 root (NAMESPACE)
735
736This method returns the name of the package that is the root of the
737compartment's namespace.
738
739Note that this behaviour differs from version 1.00 of the Safe module
740where the root module could be used to change the namespace. That
741functionality has been withdrawn pending deeper consideration.
742
743=head2 mask (MASK)
744
745This is a get-or-set method for the compartment's operator mask.
746
747With no MASK argument present, it returns the current operator mask of
748the compartment.
749
750With the MASK argument present, it sets the operator mask for the
751compartment (equivalent to calling the deny_only method).
752
753=head2 wrap_code_ref (CODEREF)
754
755Returns a reference to an anonymous subroutine that, when executed, will call
756CODEREF with the Safe compartment 'in effect'.  In other words, with the
757package namespace adjusted and the opmask enabled.
758
759Note that the opmask doesn't affect the already compiled code, it only affects
760any I<further> compilation that the already compiled code may try to perform.
761
762This is particularly useful when applied to code references returned from reval().
763
764(It also provides a kind of workaround for RT#60374: "Safe.pm sort {} bug with
765-Dusethreads". See L<https://rt.perl.org/rt3//Public/Bug/Display.html?id=60374>
766for I<much> more detail.)
767
768=head2 wrap_code_refs_within (...)
769
770Wraps any CODE references found within the arguments by replacing each with the
771result of calling L</wrap_code_ref> on the CODE reference. Any ARRAY or HASH
772references in the arguments are inspected recursively.
773
774Returns nothing.
775
776=head1 RISKS
777
778This section is just an outline of some of the things code in a compartment
779might do (intentionally or unintentionally) which can have an effect outside
780the compartment.
781
782=over 8
783
784=item Memory
785
786Consuming all (or nearly all) available memory.
787
788=item CPU
789
790Causing infinite loops etc.
791
792=item Snooping
793
794Copying private information out of your system. Even something as
795simple as your user name is of value to others. Much useful information
796could be gleaned from your environment variables for example.
797
798=item Signals
799
800Causing signals (especially SIGFPE and SIGALARM) to affect your process.
801
802Setting up a signal handler will need to be carefully considered
803and controlled.  What mask is in effect when a signal handler
804gets called?  If a user can get an imported function to get an
805exception and call the user's signal handler, does that user's
806restricted mask get re-instated before the handler is called?
807Does an imported handler get called with its original mask or
808the user's one?
809
810=item State Changes
811
812Ops such as chdir obviously effect the process as a whole and not just
813the code in the compartment. Ops such as rand and srand have a similar
814but more subtle effect.
815
816=back
817
818=head1 AUTHOR
819
820Originally designed and implemented by Malcolm Beattie.
821
822Reworked to use the Opcode module and other changes added by Tim Bunce.
823
824Currently maintained by the Perl 5 Porters, <perl5-porters@perl.org>.
825
826=cut
827