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