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