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