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