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