5ec376bf64f8d5cd7ea21a5e51636017abbb3fe4
[p5sagit/p5-mst-13.2.git] / ext / Opcode / Safe.pm
1 package Safe;
2
3 use 5.003_11;
4 use strict;
5
6 $Safe::VERSION = "2.12";
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
13 sub 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 }
27
28 use Carp;
29 BEGIN { eval q{
30     use Carp::Heavy;
31 } }
32
33 use 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
42 my $default_root  = 0;
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
46 my $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 ]];
92
93 sub 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);
121     Opcode::_safe_pkg_prep($obj->{Root}) if($Opcode::VERSION > 1.04);
122     return $obj;
123 }
124
125 sub DESTROY {
126     my $obj = shift;
127     $obj->erase('DESTROY') if $obj->{Erase};
128 }
129
130 sub erase {
131     my ($obj, $action) = @_;
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
147 #    delete $stem_symtab->{$leaf};
148
149     my $leaf_glob   = $stem_symtab->{$leaf};
150     my $leaf_symtab = *{$leaf_glob}{HASH};
151 #    warn " leaf_symtab ", join(', ', %$leaf_symtab),"\n";
152     %$leaf_symtab = ();
153     #delete $leaf_symtab->{'__ANON__'};
154     #delete $leaf_symtab->{'foo'};
155     #delete $leaf_symtab->{'main::'};
156 #    my $foo = undef ${"$stem\::"}{"$leaf\::"};
157
158     if ($action and $action eq 'DESTROY') {
159         delete $stem_symtab->{$leaf};
160     } else {
161         $obj->share_from('main', $default_share);
162     }
163     1;
164 }
165
166
167 sub reinit {
168     my $obj= shift;
169     $obj->erase;
170     $obj->share_redo;
171 }
172
173 sub root {
174     my $obj = shift;
175     croak("Safe root method now read-only") if @_;
176     return $obj->{Root};
177 }
178
179
180 sub mask {
181     my $obj = shift;
182     return $obj->{Mask} unless @_;
183     $obj->deny_only(@_);
184 }
185
186 # v1 compatibility methods
187 sub trap   { shift->deny(@_)   }
188 sub untrap { shift->permit(@_) }
189
190 sub deny {
191     my $obj = shift;
192     $obj->{Mask} |= opset(@_);
193 }
194 sub deny_only {
195     my $obj = shift;
196     $obj->{Mask} = opset(@_);
197 }
198
199 sub permit {
200     my $obj = shift;
201     # XXX needs testing
202     $obj->{Mask} &= invert_opset opset(@_);
203 }
204 sub permit_only {
205     my $obj = shift;
206     $obj->{Mask} = invert_opset opset(@_);
207 }
208
209
210 sub dump_mask {
211     my $obj = shift;
212     print opset_to_hex($obj->{Mask}),"\n";
213 }
214
215
216
217 sub share {
218     my($obj, @vars) = @_;
219     $obj->share_from(scalar(caller), \@vars);
220 }
221
222 sub share_from {
223     my $obj = shift;
224     my $pkg = shift;
225     my $vars = shift;
226     my $no_record = shift || 0;
227     my $root = $obj->root();
228     croak("vars not an array ref") unless ref $vars eq 'ARRAY';
229     no strict 'refs';
230     # Check that 'from' package actually exists
231     croak("Package \"$pkg\" does not exist")
232         unless keys %{"$pkg\::"};
233     my $arg;
234     foreach $arg (@$vars) {
235         # catch some $safe->share($var) errors:
236         my ($var, $type);
237         $type = $1 if ($var = $arg) =~ s/^(\W)//;
238         # warn "share_from $pkg $type $var";
239         *{$root."::$var"} = (!$type)       ? \&{$pkg."::$var"}
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));
246     }
247     $obj->share_record($pkg, $vars) unless $no_record or !$vars;
248 }
249
250 sub 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 }
258 sub share_redo {
259     my $obj = shift;
260     my $shares = \%{$obj->{Shares} ||= {}};
261     my($var, $pkg);
262     while(($var, $pkg) = each %$shares) {
263         # warn "share_redo $pkg\:: $var";
264         $obj->share_from($pkg,  [ $var ], 1);
265     }
266 }
267 sub share_forget {
268     delete shift->{Shares};
269 }
270
271 sub varglob {
272     my ($obj, $var) = @_;
273     no strict 'refs';
274     return *{$obj->root()."::$var"};
275 }
276
277
278 sub reval {
279     my ($obj, $expr, $strict) = @_;
280     my $root = $obj->{Root};
281
282     my $evalsub = lexless_anon_sub($root,$strict, $expr);
283     return Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub);
284 }
285
286 sub rdo {
287     my ($obj, $file) = @_;
288     my $root = $obj->{Root};
289
290     my $evalsub = eval
291             sprintf('package %s; sub { @_ = (); do $file }', $root);
292     return Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub);
293 }
294
295
296 1;
297
298 __END__
299
300 =head1 NAME
301
302 Safe - 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
316 The Safe extension module allows the creation of compartments
317 in which perl code can be evaluated. Each compartment has
318
319 =over 8
320
321 =item a new namespace
322
323 The "root" of the namespace (i.e. "main::") is changed to a
324 different package and code evaluated in the compartment cannot
325 refer to variables outside this namespace, even with run-time
326 glob lookups and other tricks.
327
328 Code which is compiled outside the compartment can choose to place
329 variables into (or I<share> variables with) the compartment's namespace
330 and only that data will be visible to code evaluated in the
331 compartment.
332
333 By default, the only variables shared with compartments are the
334 "underscore" variables $_ and @_ (and, technically, the less frequently
335 used %_, the _ filehandle and so on). This is because otherwise perl
336 operators which default to $_ will not work and neither will the
337 assignment of arguments to @_ on subroutine entry.
338
339 =item an operator mask
340
341 Each compartment has an associated "operator mask". Recall that
342 perl code is compiled into an internal format before execution.
343 Evaluating perl code (e.g. via "eval" or "do 'file'") causes
344 the code to be compiled into an internal format and then,
345 provided there was no error in the compilation, executed.
346 Code evaluated in a compartment compiles subject to the
347 compartment's operator mask. Attempting to evaluate code in a
348 compartment which contains a masked operator will cause the
349 compilation to fail with an error. The code will not be executed.
350
351 The default operator mask for a newly created compartment is
352 the ':default' optag.
353
354 It is important that you read the L<Opcode> module documentation
355 for more information, especially for detailed definitions of opnames,
356 optags and opsets.
357
358 Since it is only at the compilation stage that the operator mask
359 applies, controlled access to potentially unsafe operations can
360 be achieved by having a handle to a wrapper subroutine (written
361 outside 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
374 The authors make B<no warranty>, implied or otherwise, about the
375 suitability of this software for safety or security purposes.
376
377 The authors shall not in any case be liable for special, incidental,
378 consequential, indirect or other similar damages arising from the use
379 of this software.
380
381 Your mileage will vary. If in any doubt B<do not use it>.
382
383
384 =head2 RECENT CHANGES
385
386 The interface to the Safe module has changed quite dramatically since
387 version 1 (as supplied with Perl5.002). Study these pages carefully if
388 you have code written to use Safe version 1 because you will need to
389 makes changes.
390
391
392 =head2 Methods in class Safe
393
394 To create a new compartment, use
395
396     $cpt = new Safe;
397
398 Optional argument is (NAMESPACE), where NAMESPACE is the root namespace
399 to use for the compartment (defaults to "Safe::Root0", incremented for
400 each new compartment).
401
402 Note that version 1.00 of the Safe module supported a second optional
403 parameter, MASK.  That functionality has been withdrawn pending deeper
404 consideration. Use the permit and deny methods described below.
405
406 The following methods can then be used on the compartment
407 object returned by the above constructor. The object argument
408 is implicit in each case.
409
410
411 =over 8
412
413 =item permit (OP, ...)
414
415 Permit the listed operators to be used when compiling code in the
416 compartment (in I<addition> to any operators already permitted).
417
418 You can list opcodes by names, or use a tag name; see
419 L<Opcode/"Predefined Opcode Tags">.
420
421 =item permit_only (OP, ...)
422
423 Permit I<only> the listed operators to be used when compiling code in
424 the compartment (I<no> other operators are permitted).
425
426 =item deny (OP, ...)
427
428 Deny the listed operators from being used when compiling code in the
429 compartment (other operators may still be permitted).
430
431 =item deny_only (OP, ...)
432
433 Deny I<only> the listed operators from being used when compiling code
434 in the compartment (I<all> other operators will be permitted).
435
436 =item trap (OP, ...)
437
438 =item untrap (OP, ...)
439
440 The trap and untrap methods are synonyms for deny and permit
441 respectfully.
442
443 =item share (NAME, ...)
444
445 This shares the variable(s) in the argument list with the compartment.
446 This is almost identical to exporting variables using the L<Exporter>
447 module.
448
449 Each NAME must be the B<name> of a non-lexical variable, typically
450 with the leading type identifier included. A bareword is treated as a
451 function name.
452
453 Examples of legal names are '$foo' for a scalar, '@foo' for an
454 array, '%foo' for a hash, '&foo' or 'foo' for a subroutine and '*foo'
455 for a glob (i.e.  all symbol table entries associated with "foo",
456 including scalar, array, hash, sub and filehandle).
457
458 Each NAME is assumed to be in the calling package. See share_from
459 for an alternative method (which share uses).
460
461 =item share_from (PACKAGE, ARRAYREF)
462
463 This method is similar to share() but allows you to explicitly name the
464 package that symbols should be shared from. The symbol names (including
465 type characters) are supplied as an array reference.
466
467     $safe->share_from('main', [ '$foo', '%bar', 'func' ]);
468
469
470 =item varglob (VARNAME)
471
472 This returns a glob reference for the symbol table entry of VARNAME in
473 the package of the compartment. VARNAME must be the B<name> of a
474 variable 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
484 This evaluates STRING as perl code inside the compartment.
485
486 The code can only see the compartment's namespace (as returned by the
487 B<root> method). The compartment's root package appears to be the
488 C<main::> package to the code inside the compartment.
489
490 Any attempt by the code in STRING to use an operator which is not permitted
491 by the compartment will cause an error (at run-time of the main program
492 but at compile-time for the code in STRING).  The error is of the form
493 "'%s' trapped by operation mask...".
494
495 If an operation is trapped in this way, then the code in STRING will
496 not be executed. If such a trapped operation occurs or any other
497 compile-time or return error, then $@ is set to the error message, just
498 as with an eval().
499
500 If there is no error, then the method returns the value of the last
501 expression evaluated, or a return statement may be used, just as with
502 subroutines and B<eval()>. The context (list or scalar) is determined
503 by the caller as usual.
504
505 This behaviour differs from the beta distribution of the Safe extension
506 where earlier versions of perl made it hard to mimic the return
507 behaviour of the eval() command and the context was always scalar.
508
509 Some points to note:
510
511 If 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
513 since when the code tries to execute the eval it will fail because the
514 opmask is still in effect. However this technique would allow clever,
515 and possibly harmful, code to 'probe' the boundaries of what is
516 possible.
517
518 Any string eval which is executed by code executing in a compartment,
519 or by code called from code executing in a compartment, will be eval'd
520 in the namespace of the compartment. This is potentially a serious
521 problem.
522
523 Consider a function foo() in package pkg compiled outside a compartment
524 but shared with it. Assume the compartment has a root package called
525 'Root'. If foo() contains an eval statement like eval '$foo = 1' then,
526 normally, $pkg::foo will be set to 1.  If foo() is called from the
527 compartment (by whatever means) then instead of setting $pkg::foo, the
528 eval will actually set $Root::pkg::foo.
529
530 This can easily be demonstrated by using a module, such as the Socket
531 module, which uses eval "..." as part of an AUTOLOAD function. You can
532 'use' the module outside the compartment and share an (autoloaded)
533 function with the compartment. If an autoload is triggered by code in
534 the compartment, or by any code anywhere that is called by any means
535 from the compartment, then the eval in the Socket module's AUTOLOAD
536 function happens in the namespace of the compartment. Any variables
537 created or used by the eval'd code are now under the control of
538 the code in the compartment.
539
540 A similar effect applies to I<all> runtime symbol lookups in code
541 called from a compartment but not compiled within it.
542
543
544
545 =item rdo (FILENAME)
546
547 This evaluates the contents of file FILENAME inside the compartment.
548 See above documentation on the B<reval> method for further details.
549
550 =item root (NAMESPACE)
551
552 This method returns the name of the package that is the root of the
553 compartment's namespace.
554
555 Note that this behaviour differs from version 1.00 of the Safe module
556 where the root module could be used to change the namespace. That
557 functionality has been withdrawn pending deeper consideration.
558
559 =item mask (MASK)
560
561 This is a get-or-set method for the compartment's operator mask.
562
563 With no MASK argument present, it returns the current operator mask of
564 the compartment.
565
566 With the MASK argument present, it sets the operator mask for the
567 compartment (equivalent to calling the deny_only method).
568
569 =back
570
571
572 =head2 Some Safety Issues
573
574 This section is currently just an outline of some of the things code in
575 a compartment might do (intentionally or unintentionally) which can
576 have an effect outside the compartment.
577
578 =over 8
579
580 =item Memory
581
582 Consuming all (or nearly all) available memory.
583
584 =item CPU
585
586 Causing infinite loops etc.
587
588 =item Snooping
589
590 Copying private information out of your system. Even something as
591 simple as your user name is of value to others. Much useful information
592 could be gleaned from your environment variables for example.
593
594 =item Signals
595
596 Causing signals (especially SIGFPE and SIGALARM) to affect your process.
597
598 Setting up a signal handler will need to be carefully considered
599 and controlled.  What mask is in effect when a signal handler
600 gets called?  If a user can get an imported function to get an
601 exception and call the user's signal handler, does that user's
602 restricted mask get re-instated before the handler is called?
603 Does an imported handler get called with its original mask or
604 the user's one?
605
606 =item State Changes
607
608 Ops such as chdir obviously effect the process as a whole and not just
609 the code in the compartment. Ops such as rand and srand have a similar
610 but more subtle effect.
611
612 =back
613
614 =head2 AUTHOR
615
616 Originally designed and implemented by Malcolm Beattie.
617
618 Reworked to use the Opcode module and other changes added by Tim Bunce.
619
620 Currently maintained by the Perl 5 Porters, <perl5-porters@perl.org>.
621
622 =cut
623