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.

575 lines
15 KiB

  1. package Opcode;
  2. require 5.005_64;
  3. our($VERSION, $XS_VERSION, @ISA, @EXPORT_OK);
  4. $VERSION = "1.04";
  5. $XS_VERSION = "1.03";
  6. use strict;
  7. use Carp;
  8. use Exporter ();
  9. use XSLoader ();
  10. @ISA = qw(Exporter);
  11. BEGIN {
  12. @EXPORT_OK = qw(
  13. opset ops_to_opset
  14. opset_to_ops opset_to_hex invert_opset
  15. empty_opset full_opset
  16. opdesc opcodes opmask define_optag
  17. opmask_add verify_opset opdump
  18. );
  19. }
  20. sub opset (;@);
  21. sub opset_to_hex ($);
  22. sub opdump (;$);
  23. use subs @EXPORT_OK;
  24. XSLoader::load 'Opcode', $XS_VERSION;
  25. _init_optags();
  26. sub ops_to_opset { opset @_ } # alias for old name
  27. sub opset_to_hex ($) {
  28. return "(invalid opset)" unless verify_opset($_[0]);
  29. unpack("h*",$_[0]);
  30. }
  31. sub opdump (;$) {
  32. my $pat = shift;
  33. # handy utility: perl -MOpcode=opdump -e 'opdump File'
  34. foreach(opset_to_ops(full_opset)) {
  35. my $op = sprintf " %12s %s\n", $_, opdesc($_);
  36. next if defined $pat and $op !~ m/$pat/i;
  37. print $op;
  38. }
  39. }
  40. sub _init_optags {
  41. my(%all, %seen);
  42. @all{opset_to_ops(full_opset)} = (); # keys only
  43. local($_);
  44. local($/) = "\n=cut"; # skip to optags definition section
  45. <DATA>;
  46. $/ = "\n="; # now read in 'pod section' chunks
  47. while(<DATA>) {
  48. next unless m/^item\s+(:\w+)/;
  49. my $tag = $1;
  50. # Split into lines, keep only indented lines
  51. my @lines = grep { m/^\s/ } split(/\n/);
  52. foreach (@lines) { s/--.*// } # delete comments
  53. my @ops = map { split ' ' } @lines; # get op words
  54. foreach(@ops) {
  55. warn "$tag - $_ already tagged in $seen{$_}\n" if $seen{$_};
  56. $seen{$_} = $tag;
  57. delete $all{$_};
  58. }
  59. # opset will croak on invalid names
  60. define_optag($tag, opset(@ops));
  61. }
  62. close(DATA);
  63. warn "Untagged opnames: ".join(' ',keys %all)."\n" if %all;
  64. }
  65. 1;
  66. __DATA__
  67. =head1 NAME
  68. Opcode - Disable named opcodes when compiling perl code
  69. =head1 SYNOPSIS
  70. use Opcode;
  71. =head1 DESCRIPTION
  72. Perl code is always compiled into an internal format before execution.
  73. Evaluating perl code (e.g. via "eval" or "do 'file'") causes
  74. the code to be compiled into an internal format and then,
  75. provided there was no error in the compilation, executed.
  76. The internal format is based on many distinct I<opcodes>.
  77. By default no opmask is in effect and any code can be compiled.
  78. The Opcode module allow you to define an I<operator mask> to be in
  79. effect when perl I<next> compiles any code. Attempting to compile code
  80. which contains a masked opcode will cause the compilation to fail
  81. with an error. The code will not be executed.
  82. =head1 NOTE
  83. The Opcode module is not usually used directly. See the ops pragma and
  84. Safe modules for more typical uses.
  85. =head1 WARNING
  86. The authors make B<no warranty>, implied or otherwise, about the
  87. suitability of this software for safety or security purposes.
  88. The authors shall not in any case be liable for special, incidental,
  89. consequential, indirect or other similar damages arising from the use
  90. of this software.
  91. Your mileage will vary. If in any doubt B<do not use it>.
  92. =head1 Operator Names and Operator Lists
  93. The canonical list of operator names is the contents of the array
  94. PL_op_name defined and initialised in file F<opcode.h> of the Perl
  95. source distribution (and installed into the perl library).
  96. Each operator has both a terse name (its opname) and a more verbose or
  97. recognisable descriptive name. The opdesc function can be used to
  98. return a list of descriptions for a list of operators.
  99. Many of the functions and methods listed below take a list of
  100. operators as parameters. Most operator lists can be made up of several
  101. types of element. Each element can be one of
  102. =over 8
  103. =item an operator name (opname)
  104. Operator names are typically small lowercase words like enterloop,
  105. leaveloop, last, next, redo etc. Sometimes they are rather cryptic
  106. like gv2cv, i_ncmp and ftsvtx.
  107. =item an operator tag name (optag)
  108. Operator tags can be used to refer to groups (or sets) of operators.
  109. Tag names always begin with a colon. The Opcode module defines several
  110. optags and the user can define others using the define_optag function.
  111. =item a negated opname or optag
  112. An opname or optag can be prefixed with an exclamation mark, e.g., !mkdir.
  113. Negating an opname or optag means remove the corresponding ops from the
  114. accumulated set of ops at that point.
  115. =item an operator set (opset)
  116. An I<opset> as a binary string of approximately 44 bytes which holds a
  117. set or zero or more operators.
  118. The opset and opset_to_ops functions can be used to convert from
  119. a list of operators to an opset and I<vice versa>.
  120. Wherever a list of operators can be given you can use one or more opsets.
  121. See also Manipulating Opsets below.
  122. =back
  123. =head1 Opcode Functions
  124. The Opcode package contains functions for manipulating operator names
  125. tags and sets. All are available for export by the package.
  126. =over 8
  127. =item opcodes
  128. In a scalar context opcodes returns the number of opcodes in this
  129. version of perl (around 350 for perl-5.7.0).
  130. In a list context it returns a list of all the operator names.
  131. (Not yet implemented, use @names = opset_to_ops(full_opset).)
  132. =item opset (OP, ...)
  133. Returns an opset containing the listed operators.
  134. =item opset_to_ops (OPSET)
  135. Returns a list of operator names corresponding to those operators in
  136. the set.
  137. =item opset_to_hex (OPSET)
  138. Returns a string representation of an opset. Can be handy for debugging.
  139. =item full_opset
  140. Returns an opset which includes all operators.
  141. =item empty_opset
  142. Returns an opset which contains no operators.
  143. =item invert_opset (OPSET)
  144. Returns an opset which is the inverse set of the one supplied.
  145. =item verify_opset (OPSET, ...)
  146. Returns true if the supplied opset looks like a valid opset (is the
  147. right length etc) otherwise it returns false. If an optional second
  148. parameter is true then verify_opset will croak on an invalid opset
  149. instead of returning false.
  150. Most of the other Opcode functions call verify_opset automatically
  151. and will croak if given an invalid opset.
  152. =item define_optag (OPTAG, OPSET)
  153. Define OPTAG as a symbolic name for OPSET. Optag names always start
  154. with a colon C<:>.
  155. The optag name used must not be defined already (define_optag will
  156. croak if it is already defined). Optag names are global to the perl
  157. process and optag definitions cannot be altered or deleted once
  158. defined.
  159. It is strongly recommended that applications using Opcode should use a
  160. leading capital letter on their tag names since lowercase names are
  161. reserved for use by the Opcode module. If using Opcode within a module
  162. you should prefix your tags names with the name of your module to
  163. ensure uniqueness and thus avoid clashes with other modules.
  164. =item opmask_add (OPSET)
  165. Adds the supplied opset to the current opmask. Note that there is
  166. currently I<no> mechanism for unmasking ops once they have been masked.
  167. This is intentional.
  168. =item opmask
  169. Returns an opset corresponding to the current opmask.
  170. =item opdesc (OP, ...)
  171. This takes a list of operator names and returns the corresponding list
  172. of operator descriptions.
  173. =item opdump (PAT)
  174. Dumps to STDOUT a two column list of op names and op descriptions.
  175. If an optional pattern is given then only lines which match the
  176. (case insensitive) pattern will be output.
  177. It's designed to be used as a handy command line utility:
  178. perl -MOpcode=opdump -e opdump
  179. perl -MOpcode=opdump -e 'opdump Eval'
  180. =back
  181. =head1 Manipulating Opsets
  182. Opsets may be manipulated using the perl bit vector operators & (and), | (or),
  183. ^ (xor) and ~ (negate/invert).
  184. However you should never rely on the numerical position of any opcode
  185. within the opset. In other words both sides of a bit vector operator
  186. should be opsets returned from Opcode functions.
  187. Also, since the number of opcodes in your current version of perl might
  188. not be an exact multiple of eight, there may be unused bits in the last
  189. byte of an upset. This should not cause any problems (Opcode functions
  190. ignore those extra bits) but it does mean that using the ~ operator
  191. will typically not produce the same 'physical' opset 'string' as the
  192. invert_opset function.
  193. =head1 TO DO (maybe)
  194. $bool = opset_eq($opset1, $opset2) true if opsets are logically eqiv
  195. $yes = opset_can($opset, @ops) true if $opset has all @ops set
  196. @diff = opset_diff($opset1, $opset2) => ('foo', '!bar', ...)
  197. =cut
  198. # the =cut above is used by _init_optags() to get here quickly
  199. =head1 Predefined Opcode Tags
  200. =over 5
  201. =item :base_core
  202. null stub scalar pushmark wantarray const defined undef
  203. rv2sv sassign
  204. rv2av aassign aelem aelemfast aslice av2arylen
  205. rv2hv helem hslice each values keys exists delete
  206. preinc i_preinc predec i_predec postinc i_postinc postdec i_postdec
  207. int hex oct abs pow multiply i_multiply divide i_divide
  208. modulo i_modulo add i_add subtract i_subtract
  209. left_shift right_shift bit_and bit_xor bit_or negate i_negate
  210. not complement
  211. lt i_lt gt i_gt le i_le ge i_ge eq i_eq ne i_ne ncmp i_ncmp
  212. slt sgt sle sge seq sne scmp
  213. substr vec stringify study pos length index rindex ord chr
  214. ucfirst lcfirst uc lc quotemeta trans chop schop chomp schomp
  215. match split qr
  216. list lslice splice push pop shift unshift reverse
  217. cond_expr flip flop andassign orassign and or xor
  218. warn die lineseq nextstate scope enter leave setstate
  219. rv2cv anoncode prototype
  220. entersub leavesub leavesublv return method method_named -- XXX loops via recursion?
  221. leaveeval -- needed for Safe to operate, is safe without entereval
  222. =item :base_mem
  223. These memory related ops are not included in :base_core because they
  224. can easily be used to implement a resource attack (e.g., consume all
  225. available memory).
  226. concat repeat join range
  227. anonlist anonhash
  228. Note that despite the existance of this optag a memory resource attack
  229. may still be possible using only :base_core ops.
  230. Disabling these ops is a I<very> heavy handed way to attempt to prevent
  231. a memory resource attack. It's probable that a specific memory limit
  232. mechanism will be added to perl in the near future.
  233. =item :base_loop
  234. These loop ops are not included in :base_core because they can easily be
  235. used to implement a resource attack (e.g., consume all available CPU time).
  236. grepstart grepwhile
  237. mapstart mapwhile
  238. enteriter iter
  239. enterloop leaveloop unstack
  240. last next redo
  241. goto
  242. =item :base_io
  243. These ops enable I<filehandle> (rather than filename) based input and
  244. output. These are safe on the assumption that only pre-existing
  245. filehandles are available for use. To create new filehandles other ops
  246. such as open would need to be enabled.
  247. readline rcatline getc read
  248. formline enterwrite leavewrite
  249. print sysread syswrite send recv
  250. eof tell seek sysseek
  251. readdir telldir seekdir rewinddir
  252. =item :base_orig
  253. These are a hotchpotch of opcodes still waiting to be considered
  254. gvsv gv gelem
  255. padsv padav padhv padany
  256. rv2gv refgen srefgen ref
  257. bless -- could be used to change ownership of objects (reblessing)
  258. pushre regcmaybe regcreset regcomp subst substcont
  259. sprintf prtf -- can core dump
  260. crypt
  261. tie untie
  262. dbmopen dbmclose
  263. sselect select
  264. pipe_op sockpair
  265. getppid getpgrp setpgrp getpriority setpriority localtime gmtime
  266. entertry leavetry -- can be used to 'hide' fatal errors
  267. =item :base_math
  268. These ops are not included in :base_core because of the risk of them being
  269. used to generate floating point exceptions (which would have to be caught
  270. using a $SIG{FPE} handler).
  271. atan2 sin cos exp log sqrt
  272. These ops are not included in :base_core because they have an effect
  273. beyond the scope of the compartment.
  274. rand srand
  275. =item :base_thread
  276. These ops are related to multi-threading.
  277. lock threadsv
  278. =item :default
  279. A handy tag name for a I<reasonable> default set of ops. (The current ops
  280. allowed are unstable while development continues. It will change.)
  281. :base_core :base_mem :base_loop :base_io :base_orig :base_thread
  282. If safety matters to you (and why else would you be using the Opcode module?)
  283. then you should not rely on the definition of this, or indeed any other, optag!
  284. =item :filesys_read
  285. stat lstat readlink
  286. ftatime ftblk ftchr ftctime ftdir fteexec fteowned fteread
  287. ftewrite ftfile ftis ftlink ftmtime ftpipe ftrexec ftrowned
  288. ftrread ftsgid ftsize ftsock ftsuid fttty ftzero ftrwrite ftsvtx
  289. fttext ftbinary
  290. fileno
  291. =item :sys_db
  292. ghbyname ghbyaddr ghostent shostent ehostent -- hosts
  293. gnbyname gnbyaddr gnetent snetent enetent -- networks
  294. gpbyname gpbynumber gprotoent sprotoent eprotoent -- protocols
  295. gsbyname gsbyport gservent sservent eservent -- services
  296. gpwnam gpwuid gpwent spwent epwent getlogin -- users
  297. ggrnam ggrgid ggrent sgrent egrent -- groups
  298. =item :browse
  299. A handy tag name for a I<reasonable> default set of ops beyond the
  300. :default optag. Like :default (and indeed all the other optags) its
  301. current definition is unstable while development continues. It will change.
  302. The :browse tag represents the next step beyond :default. It it a
  303. superset of the :default ops and adds :filesys_read the :sys_db.
  304. The intent being that scripts can access more (possibly sensitive)
  305. information about your system but not be able to change it.
  306. :default :filesys_read :sys_db
  307. =item :filesys_open
  308. sysopen open close
  309. umask binmode
  310. open_dir closedir -- other dir ops are in :base_io
  311. =item :filesys_write
  312. link unlink rename symlink truncate
  313. mkdir rmdir
  314. utime chmod chown
  315. fcntl -- not strictly filesys related, but possibly as dangerous?
  316. =item :subprocess
  317. backtick system
  318. fork
  319. wait waitpid
  320. glob -- access to Cshell via <`rm *`>
  321. =item :ownprocess
  322. exec exit kill
  323. time tms -- could be used for timing attacks (paranoid?)
  324. =item :others
  325. This tag holds groups of assorted specialist opcodes that don't warrant
  326. having optags defined for them.
  327. SystemV Interprocess Communications:
  328. msgctl msgget msgrcv msgsnd
  329. semctl semget semop
  330. shmctl shmget shmread shmwrite
  331. =item :still_to_be_decided
  332. chdir
  333. flock ioctl
  334. socket getpeername ssockopt
  335. bind connect listen accept shutdown gsockopt getsockname
  336. sleep alarm -- changes global timer state and signal handling
  337. sort -- assorted problems including core dumps
  338. tied -- can be used to access object implementing a tie
  339. pack unpack -- can be used to create/use memory pointers
  340. entereval -- can be used to hide code from initial compile
  341. require dofile
  342. caller -- get info about calling environment and args
  343. reset
  344. dbstate -- perl -d version of nextstate(ment) opcode
  345. =item :dangerous
  346. This tag is simply a bucket for opcodes that are unlikely to be used via
  347. a tag name but need to be tagged for completness and documentation.
  348. syscall dump chroot
  349. =back
  350. =head1 SEE ALSO
  351. ops(3) -- perl pragma interface to Opcode module.
  352. Safe(3) -- Opcode and namespace limited execution compartments
  353. =head1 AUTHORS
  354. Originally designed and implemented by Malcolm Beattie,
  355. mbeattie@sable.ox.ac.uk as part of Safe version 1.
  356. Split out from Safe module version 1, named opcode tags and other
  357. changes added by Tim Bunce.
  358. =cut