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