Debian Codegraph @

ext/Opcode/Opcode.pm

raw
1 package Opcode 1.65;
2
3 use strict;
4
5 use Carp;
6 use Exporter 'import';
7 use XSLoader;
8
9 sub opset (;@);
10 sub opset_to_hex ($);
11 sub opdump (;$);
12 use subs our @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 XSLoader::load();
21
22 _init_optags();
23
24 sub ops_to_opset { opset @_ } # alias for old name
25
26 sub opset_to_hex ($) {
27 return "(invalid opset)" unless verify_opset($_[0]);
28 unpack("h*",$_[0]);
29 }
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
41
42
43 sub _init_optags {
44 my(%all, %seen);
45 @all{opset_to_ops(full_opset)} = (); # keys only
46
47 local($_);
48 local($/) = "\n=cut"; # skip to optags definition section
49 <DATA>;
50 $/ = "\n="; # now read in 'pod section' chunks
51 while(<DATA>) {
52 next unless m/^item\s+(:\w+)/;
53 my $tag = $1;
54
55 # Split into lines, keep only indented lines
56 my @lines = grep { m/^\s/ } split(/\n/);
57 foreach (@lines) { s/(?:\t|--).*// } # delete comments
58 my @ops = map { split ' ' } @lines; # get op words
59
60 foreach(@ops) {
61 warn "$tag - $_ already tagged in $seen{$_}\n" if $seen{$_};
62 $seen{$_} = $tag;
63 delete $all{$_};
64 }
65 # opset will croak on invalid names
66 define_optag($tag, opset(@ops));
67 }
68 close(DATA);
69 warn "Untagged opnames: ".join(' ',keys %all)."\n" if %all;
70 }
71
72
73 1;
74
75 __DATA__
76
77 =head1 NAME
78
79 Opcode - Disable named opcodes when compiling perl code
80
81 =head1 SYNOPSIS
82
83 use Opcode;
84
85
86 =head1 DESCRIPTION
87
88 Perl code is always compiled into an internal format before execution.
89
90 Evaluating perl code (e.g. via "eval" or "do 'file'") causes
91 the code to be compiled into an internal format and then,
92 provided there was no error in the compilation, executed.
93 The internal format is based on many distinct I<opcodes>.
94
95 By default no opmask is in effect and any code can be compiled.
96
97 The Opcode module allow you to define an I<operator mask> to be in
98 effect when perl I<next> compiles any code. Attempting to compile code
99 which contains a masked opcode will cause the compilation to fail
100 with an error. The code will not be executed.
101
102 =head1 NOTE
103
104 The Opcode module is not usually used directly. See the ops pragma and
105 Safe modules for more typical uses.
106
107 =head1 WARNING
108
109 The Opcode module does not implement an effective sandbox for
110 evaluating untrusted code with the perl interpreter.
111
112 Bugs in the perl interpreter that could be abused to bypass
113 Opcode restrictions are not treated as vulnerabilities. See
114 L<perlsecpolicy> for additional information.
115
116 The authors make B<no warranty>, implied or otherwise, about the
117 suitability of this software for safety or security purposes.
118
119 The authors shall not in any case be liable for special, incidental,
120 consequential, indirect or other similar damages arising from the use
121 of this software.
122
123 Your mileage will vary. If in any doubt B<do not use it>.
124
125
126 =head1 Operator Names and Operator Lists
127
128 The canonical list of operator names is the contents of the array
129 PL_op_name defined and initialised in file F<opcode.h> of the Perl
130 source distribution (and installed into the perl library).
131
132 Each operator has both a terse name (its opname) and a more verbose or
133 recognisable descriptive name. The opdesc function can be used to
134 return a list of descriptions for a list of operators.
135
136 Many of the functions and methods listed below take a list of
137 operators as parameters. Most operator lists can be made up of several
138 types of element. Each element can be one of
139
140 =over 8
141
142 =item an operator name (opname)
143
144 Operator names are typically small lowercase words like enterloop,
145 leaveloop, last, next, redo etc. Sometimes they are rather cryptic
146 like gv2cv, i_ncmp and ftsvtx.
147
148 =item an operator tag name (optag)
149
150 Operator tags can be used to refer to groups (or sets) of operators.
151 Tag names always begin with a colon. The Opcode module defines several
152 optags and the user can define others using the define_optag function.
153
154 =item a negated opname or optag
155
156 An opname or optag can be prefixed with an exclamation mark, e.g., !mkdir.
157 Negating an opname or optag means remove the corresponding ops from the
158 accumulated set of ops at that point.
159
160 =item an operator set (opset)
161
162 An I<opset> as a binary string of approximately 44 bytes which holds a
163 set or zero or more operators.
164
165 The opset and opset_to_ops functions can be used to convert from
166 a list of operators to an opset and I<vice versa>.
167
168 Wherever a list of operators can be given you can use one or more opsets.
169 See also Manipulating Opsets below.
170
171 =back
172
173
174 =head1 Opcode Functions
175
176 The Opcode package contains functions for manipulating operator names
177 tags and sets. All are available for export by the package.
178
179 =over 8
180
181 =item opcodes
182
183 In a scalar context opcodes returns the number of opcodes in this
184 version of perl (around 350 for perl-5.7.0).
185
186 In a list context it returns a list of all the operator names.
187 (Not yet implemented, use @names = opset_to_ops(full_opset).)
188
189 =item opset (OP, ...)
190
191 Returns an opset containing the listed operators.
192
193 =item opset_to_ops (OPSET)
194
195 Returns a list of operator names corresponding to those operators in
196 the set.
197
198 =item opset_to_hex (OPSET)
199
200 Returns a string representation of an opset. Can be handy for debugging.
201
202 =item full_opset
203
204 Returns an opset which includes all operators.
205
206 =item empty_opset
207
208 Returns an opset which contains no operators.
209
210 =item invert_opset (OPSET)
211
212 Returns an opset which is the inverse set of the one supplied.
213
214 =item verify_opset (OPSET, ...)
215
216 Returns true if the supplied opset looks like a valid opset (is the
217 right length etc) otherwise it returns false. If an optional second
218 parameter is true then verify_opset will croak on an invalid opset
219 instead of returning false.
220
221 Most of the other Opcode functions call verify_opset automatically
222 and will croak if given an invalid opset.
223
224 =item define_optag (OPTAG, OPSET)
225
226 Define OPTAG as a symbolic name for OPSET. Optag names always start
227 with a colon C<:>.
228
229 The optag name used must not be defined already (define_optag will
230 croak if it is already defined). Optag names are global to the perl
231 process and optag definitions cannot be altered or deleted once
232 defined.
233
234 It is strongly recommended that applications using Opcode should use a
235 leading capital letter on their tag names since lowercase names are
236 reserved for use by the Opcode module. If using Opcode within a module
237 you should prefix your tags names with the name of your module to
238 ensure uniqueness and thus avoid clashes with other modules.
239
240 =item opmask_add (OPSET)
241
242 Adds the supplied opset to the current opmask. Note that there is
243 currently I<no> mechanism for unmasking ops once they have been masked.
244 This is intentional.
245
246 =item opmask
247
248 Returns an opset corresponding to the current opmask.
249
250 =item opdesc (OP, ...)
251
252 This takes a list of operator names and returns the corresponding list
253 of operator descriptions.
254
255 =item opdump (PAT)
256
257 Dumps to STDOUT a two column list of op names and op descriptions.
258 If an optional pattern is given then only lines which match the
259 (case insensitive) pattern will be output.
260
261 It's designed to be used as a handy command line utility:
262
263 perl -MOpcode=opdump -e opdump
264 perl -MOpcode=opdump -e 'opdump Eval'
265
266 =back
267
268 =head1 Manipulating Opsets
269
270 Opsets may be manipulated using the perl bit vector operators & (and), | (or),
271 ^ (xor) and ~ (negate/invert).
272
273 However you should never rely on the numerical position of any opcode
274 within the opset. In other words both sides of a bit vector operator
275 should be opsets returned from Opcode functions.
276
277 Also, since the number of opcodes in your current version of perl might
278 not be an exact multiple of eight, there may be unused bits in the last
279 byte of an upset. This should not cause any problems (Opcode functions
280 ignore those extra bits) but it does mean that using the ~ operator
281 will typically not produce the same 'physical' opset 'string' as the
282 invert_opset function.
283
284
285 =head1 TO DO (maybe)
286
287 $bool = opset_eq($opset1, $opset2) true if opsets are logically
288 equivalent
289 $yes = opset_can($opset, @ops) true if $opset has all @ops set
290
291 @diff = opset_diff($opset1, $opset2) => ('foo', '!bar', ...)
292
293 =cut
294
295 # the =cut above is used by _init_optags() to get here quickly
296
297 =head1 Predefined Opcode Tags
298
299 =over 5
300
301 =item :base_core
302
303 null stub scalar pushmark wantarray const defined undef
304
305 rv2sv sassign padsv_store
306
307 rv2av aassign aelem aelemfast aelemfast_lex aslice kvaslice
308 av2arylen aelemfastlex_store
309
310 rv2hv helem hslice kvhslice each values keys exists delete
311 aeach akeys avalues multideref argelem argdefelem argcheck
312
313 preinc i_preinc predec i_predec postinc i_postinc
314 postdec i_postdec int hex oct abs pow multiply i_multiply
315 divide i_divide modulo i_modulo add i_add subtract i_subtract
316
317 left_shift right_shift bit_and bit_xor bit_or nbit_and
318 nbit_xor nbit_or sbit_and sbit_xor sbit_or negate i_negate not
319 complement ncomplement scomplement
320
321 lt i_lt gt i_gt le i_le ge i_ge eq i_eq ne i_ne ncmp i_ncmp
322 slt sgt sle sge seq sne scmp
323 isa
324
325 substr vec stringify study pos length index rindex ord chr
326
327 ucfirst lcfirst uc lc fc quotemeta trans transr chop schop
328 chomp schomp
329
330 match split qr
331
332 list lslice splice push pop shift unshift reverse
333
334 cond_expr flip flop andassign orassign dorassign and or dor xor
335 helemexistsor
336
337 warn die lineseq nextstate scope enter leave
338
339 rv2cv anoncode prototype coreargs avhvswitch anonconst
340 emptyavhv
341
342 entersub leavesub leavesublv return method method_named
343 method_super method_redir method_redir_super
344 -- XXX loops via recursion?
345
346 cmpchain_and cmpchain_dup
347
348 is_bool
349 is_weak weaken unweaken
350
351 leaveeval -- needed for Safe to operate, is safe
352 without entereval
353
354 methstart initfield
355
356 =item :base_mem
357
358 These memory related ops are not included in :base_core because they
359 can easily be used to implement a resource attack (e.g., consume all
360 available memory).
361
362 concat multiconcat repeat join range
363
364 anonlist anonhash
365
366 Note that despite the existence of this optag a memory resource attack
367 may still be possible using only :base_core ops.
368
369 Disabling these ops is a I<very> heavy handed way to attempt to prevent
370 a memory resource attack. It's probable that a specific memory limit
371 mechanism will be added to perl in the near future.
372
373 =item :base_loop
374
375 These loop ops are not included in :base_core because they can easily be
376 used to implement a resource attack (e.g., consume all available CPU time).
377
378 grepstart grepwhile
379 mapstart mapwhile
380 enteriter iter
381 enterloop leaveloop unstack
382 last next redo
383 goto
384
385 =item :base_io
386
387 These ops enable I<filehandle> (rather than filename) based input and
388 output. These are safe on the assumption that only pre-existing
389 filehandles are available for use. Usually, to create new filehandles
390 other ops such as open would need to be enabled, if you don't take into
391 account the magical open of ARGV.
392
393 readline rcatline getc read
394
395 formline enterwrite leavewrite
396
397 print say sysread syswrite send recv
398
399 eof tell seek sysseek
400
401 readdir telldir seekdir rewinddir
402
403 =item :base_orig
404
405 These are a hotchpotch of opcodes still waiting to be considered
406
407 gvsv gv gelem
408
409 padsv padav padhv padcv padany padrange introcv clonecv
410
411 once
412
413 rv2gv refgen srefgen ref refassign lvref lvrefslice lvavref
414 blessed refaddr reftype
415
416 bless -- could be used to change ownership of objects
417 (reblessing)
418
419 regcmaybe regcreset regcomp subst substcont
420
421 sprintf prtf -- can core dump
422
423 crypt
424
425 tie untie
426
427 dbmopen dbmclose
428 sselect select
429 pipe_op sockpair
430
431 getppid getpgrp setpgrp getpriority setpriority
432 localtime gmtime
433
434 entertry leavetry -- can be used to 'hide' fatal errors
435 entertrycatch poptry catch leavetrycatch -- similar
436
437 entergiven leavegiven
438 enterwhen leavewhen
439 break continue
440 smartmatch
441
442 pushdefer
443
444 custom -- where should this go
445
446 ceil floor
447
448 is_tainted
449
450 =item :base_math
451
452 These ops are not included in :base_core because of the risk of them being
453 used to generate floating point exceptions (which would have to be caught
454 using a $SIG{FPE} handler).
455
456 atan2 sin cos exp log sqrt
457
458 These ops are not included in :base_core because they have an effect
459 beyond the scope of the compartment.
460
461 rand srand
462
463 =item :base_thread
464
465 These ops are related to multi-threading.
466
467 lock
468
469 =item :default
470
471 A handy tag name for a I<reasonable> default set of ops. (The current ops
472 allowed are unstable while development continues. It will change.)
473
474 :base_core :base_mem :base_loop :base_orig :base_thread
475
476 This list used to contain :base_io prior to Opcode 1.07.
477
478 If safety matters to you (and why else would you be using the Opcode module?)
479 then you should not rely on the definition of this, or indeed any other, optag!
480
481 =item :filesys_read
482
483 stat lstat readlink
484
485 ftatime ftblk ftchr ftctime ftdir fteexec fteowned
486 fteread ftewrite ftfile ftis ftlink ftmtime ftpipe
487 ftrexec ftrowned ftrread ftsgid ftsize ftsock ftsuid
488 fttty ftzero ftrwrite ftsvtx
489
490 fttext ftbinary
491
492 fileno
493
494 =item :sys_db
495
496 ghbyname ghbyaddr ghostent shostent ehostent -- hosts
497 gnbyname gnbyaddr gnetent snetent enetent -- networks
498 gpbyname gpbynumber gprotoent sprotoent eprotoent -- protocols
499 gsbyname gsbyport gservent sservent eservent -- services
500
501 gpwnam gpwuid gpwent spwent epwent getlogin -- users
502 ggrnam ggrgid ggrent sgrent egrent -- groups
503
504 =item :browse
505
506 A handy tag name for a I<reasonable> default set of ops beyond the
507 :default optag. Like :default (and indeed all the other optags) its
508 current definition is unstable while development continues. It will change.
509
510 The :browse tag represents the next step beyond :default. It is a
511 superset of the :default ops and adds :filesys_read the :sys_db.
512 The intent being that scripts can access more (possibly sensitive)
513 information about your system but not be able to change it.
514
515 :default :filesys_read :sys_db
516
517 =item :filesys_open
518
519 sysopen open close
520 umask binmode
521
522 open_dir closedir -- other dir ops are in :base_io
523
524 =item :filesys_write
525
526 link unlink rename symlink truncate
527
528 mkdir rmdir
529
530 utime chmod chown
531
532 fcntl -- not strictly filesys related, but possibly as
533 dangerous?
534
535 =item :subprocess
536
537 backtick system
538
539 fork
540
541 wait waitpid
542
543 glob -- access to Cshell via <`rm *`>
544
545 =item :ownprocess
546
547 exec exit kill
548
549 time tms -- could be used for timing attacks (paranoid?)
550
551 =item :others
552
553 This tag holds groups of assorted specialist opcodes that don't warrant
554 having optags defined for them.
555
556 SystemV Interprocess Communications:
557
558 msgctl msgget msgrcv msgsnd
559
560 semctl semget semop
561
562 shmctl shmget shmread shmwrite
563
564 =item :load
565
566 This tag holds opcodes related to loading modules and getting information
567 about calling environment and args.
568
569 require dofile
570 caller runcv classname
571
572 =item :still_to_be_decided
573
574 chdir
575 flock ioctl
576
577 socket getpeername ssockopt
578 bind connect listen accept shutdown gsockopt getsockname
579
580 sleep alarm -- changes global timer state and signal handling
581 sort -- assorted problems including core dumps
582 tied -- can be used to access object implementing a tie
583 pack unpack -- can be used to create/use memory pointers
584
585 hintseval -- constant op holding eval hints
586
587 entereval -- can be used to hide code from initial compile
588
589 reset
590
591 dbstate -- perl -d version of nextstate(ment) opcode
592
593 =item :dangerous
594
595 This tag is simply a bucket for opcodes that are unlikely to be used via
596 a tag name but need to be tagged for completeness and documentation.
597
598 syscall dump chroot
599
600 =back
601
602 =head1 SEE ALSO
603
604 L<ops> -- perl pragma interface to Opcode module.
605
606 L<Safe> -- Opcode and namespace limited execution compartments
607
608 =head1 AUTHORS
609
610 Originally designed and implemented by Malcolm Beattie,
611 [email protected] as part of Safe version 1.
612
613 Split out from Safe module version 1, named opcode tags and other
614 changes added by Tim Bunce.
615
616 =cut