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