Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

558 lines
17 KiB

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