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