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