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