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