1package Opcode 1.64;
2
3use strict;
4
5use Carp;
6use Exporter 'import';
7use XSLoader;
8
9sub opset (;@);
10sub opset_to_hex ($);
11sub opdump (;$);
12use 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
20XSLoader::load();
21
22_init_optags();
23
24sub ops_to_opset { opset @_ }	# alias for old name
25
26sub opset_to_hex ($) {
27    return "(invalid opset)" unless verify_opset($_[0]);
28    unpack("h*",$_[0]);
29}
30
31sub 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
43sub _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
731;
74
75__DATA__
76
77=head1 NAME
78
79Opcode - Disable named opcodes when compiling perl code
80
81=head1 SYNOPSIS
82
83  use Opcode;
84
85
86=head1 DESCRIPTION
87
88Perl code is always compiled into an internal format before execution.
89
90Evaluating perl code (e.g. via "eval" or "do 'file'") causes
91the code to be compiled into an internal format and then,
92provided there was no error in the compilation, executed.
93The internal format is based on many distinct I<opcodes>.
94
95By default no opmask is in effect and any code can be compiled.
96
97The Opcode module allow you to define an I<operator mask> to be in
98effect when perl I<next> compiles any code.  Attempting to compile code
99which contains a masked opcode will cause the compilation to fail
100with an error. The code will not be executed.
101
102=head1 NOTE
103
104The Opcode module is not usually used directly. See the ops pragma and
105Safe modules for more typical uses.
106
107=head1 WARNING
108
109The Opcode module does not implement an effective sandbox for
110evaluating untrusted code with the perl interpreter.
111
112Bugs in the perl interpreter that could be abused to bypass
113Opcode restrictions are not treated as vulnerabilities. See
114L<perlsecpolicy> for additional information.
115
116The authors make B<no warranty>, implied or otherwise, about the
117suitability of this software for safety or security purposes.
118
119The authors shall not in any case be liable for special, incidental,
120consequential, indirect or other similar damages arising from the use
121of this software.
122
123Your mileage will vary. If in any doubt B<do not use it>.
124
125
126=head1 Operator Names and Operator Lists
127
128The canonical list of operator names is the contents of the array
129PL_op_name defined and initialised in file F<opcode.h> of the Perl
130source distribution (and installed into the perl library).
131
132Each operator has both a terse name (its opname) and a more verbose or
133recognisable descriptive name. The opdesc function can be used to
134return a list of descriptions for a list of operators.
135
136Many of the functions and methods listed below take a list of
137operators as parameters. Most operator lists can be made up of several
138types of element. Each element can be one of
139
140=over 8
141
142=item an operator name (opname)
143
144Operator names are typically small lowercase words like enterloop,
145leaveloop, last, next, redo etc. Sometimes they are rather cryptic
146like gv2cv, i_ncmp and ftsvtx.
147
148=item an operator tag name (optag)
149
150Operator tags can be used to refer to groups (or sets) of operators.
151Tag names always begin with a colon. The Opcode module defines several
152optags and the user can define others using the define_optag function.
153
154=item a negated opname or optag
155
156An opname or optag can be prefixed with an exclamation mark, e.g., !mkdir.
157Negating an opname or optag means remove the corresponding ops from the
158accumulated set of ops at that point.
159
160=item an operator set (opset)
161
162An I<opset> as a binary string of approximately 44 bytes which holds a
163set or zero or more operators.
164
165The opset and opset_to_ops functions can be used to convert from
166a list of operators to an opset and I<vice versa>.
167
168Wherever a list of operators can be given you can use one or more opsets.
169See also Manipulating Opsets below.
170
171=back
172
173
174=head1 Opcode Functions
175
176The Opcode package contains functions for manipulating operator names
177tags and sets. All are available for export by the package.
178
179=over 8
180
181=item opcodes
182
183In a scalar context opcodes returns the number of opcodes in this
184version of perl (around 350 for perl-5.7.0).
185
186In 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
191Returns an opset containing the listed operators.
192
193=item opset_to_ops (OPSET)
194
195Returns a list of operator names corresponding to those operators in
196the set.
197
198=item opset_to_hex (OPSET)
199
200Returns a string representation of an opset. Can be handy for debugging.
201
202=item full_opset
203
204Returns an opset which includes all operators.
205
206=item empty_opset
207
208Returns an opset which contains no operators.
209
210=item invert_opset (OPSET)
211
212Returns an opset which is the inverse set of the one supplied.
213
214=item verify_opset (OPSET, ...)
215
216Returns true if the supplied opset looks like a valid opset (is the
217right length etc) otherwise it returns false. If an optional second
218parameter is true then verify_opset will croak on an invalid opset
219instead of returning false.
220
221Most of the other Opcode functions call verify_opset automatically
222and will croak if given an invalid opset.
223
224=item define_optag (OPTAG, OPSET)
225
226Define OPTAG as a symbolic name for OPSET. Optag names always start
227with a colon C<:>.
228
229The optag name used must not be defined already (define_optag will
230croak if it is already defined). Optag names are global to the perl
231process and optag definitions cannot be altered or deleted once
232defined.
233
234It is strongly recommended that applications using Opcode should use a
235leading capital letter on their tag names since lowercase names are
236reserved for use by the Opcode module. If using Opcode within a module
237you should prefix your tags names with the name of your module to
238ensure uniqueness and thus avoid clashes with other modules.
239
240=item opmask_add (OPSET)
241
242Adds the supplied opset to the current opmask. Note that there is
243currently I<no> mechanism for unmasking ops once they have been masked.
244This is intentional.
245
246=item opmask
247
248Returns an opset corresponding to the current opmask.
249
250=item opdesc (OP, ...)
251
252This takes a list of operator names and returns the corresponding list
253of operator descriptions.
254
255=item opdump (PAT)
256
257Dumps to STDOUT a two column list of op names and op descriptions.
258If an optional pattern is given then only lines which match the
259(case insensitive) pattern will be output.
260
261It'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
270Opsets may be manipulated using the perl bit vector operators & (and), | (or),
271^ (xor) and ~ (negate/invert).
272
273However you should never rely on the numerical position of any opcode
274within the opset. In other words both sides of a bit vector operator
275should be opsets returned from Opcode functions.
276
277Also, since the number of opcodes in your current version of perl might
278not be an exact multiple of eight, there may be unused bits in the last
279byte of an upset. This should not cause any problems (Opcode functions
280ignore those extra bits) but it does mean that using the ~ operator
281will typically not produce the same 'physical' opset 'string' as the
282invert_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
358These memory related ops are not included in :base_core because they
359can easily be used to implement a resource attack (e.g., consume all
360available memory).
361
362    concat multiconcat repeat join range
363
364    anonlist anonhash
365
366Note that despite the existence of this optag a memory resource attack
367may still be possible using only :base_core ops.
368
369Disabling these ops is a I<very> heavy handed way to attempt to prevent
370a memory resource attack. It's probable that a specific memory limit
371mechanism will be added to perl in the near future.
372
373=item :base_loop
374
375These loop ops are not included in :base_core because they can easily be
376used 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
387These ops enable I<filehandle> (rather than filename) based input and
388output. These are safe on the assumption that only pre-existing
389filehandles are available for use.  Usually, to create new filehandles
390other ops such as open would need to be enabled, if you don't take into
391account 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
405These 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
452These ops are not included in :base_core because of the risk of them being
453used to generate floating point exceptions (which would have to be caught
454using a $SIG{FPE} handler).
455
456    atan2 sin cos exp log sqrt
457
458These ops are not included in :base_core because they have an effect
459beyond the scope of the compartment.
460
461    rand srand
462
463=item :base_thread
464
465These ops are related to multi-threading.
466
467    lock
468
469=item :default
470
471A handy tag name for a I<reasonable> default set of ops.  (The current ops
472allowed are unstable while development continues. It will change.)
473
474    :base_core :base_mem :base_loop :base_orig :base_thread
475
476This list used to contain :base_io prior to Opcode 1.07.
477
478If safety matters to you (and why else would you be using the Opcode module?)
479then 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
506A 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
508current definition is unstable while development continues. It will change.
509
510The :browse tag represents the next step beyond :default. It is a
511superset of the :default ops and adds :filesys_read the :sys_db.
512The intent being that scripts can access more (possibly sensitive)
513information 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
553This tag holds groups of assorted specialist opcodes that don't warrant
554having optags defined for them.
555
556SystemV Interprocess Communications:
557
558    msgctl msgget msgrcv msgsnd
559
560    semctl semget semop
561
562    shmctl shmget shmread shmwrite
563
564=item :load
565
566This tag holds opcodes related to loading modules and getting information
567about calling environment and args.
568
569    require dofile
570    caller runcv
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
595This tag is simply a bucket for opcodes that are unlikely to be used via
596a 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
604L<ops> -- perl pragma interface to Opcode module.
605
606L<Safe> -- Opcode and namespace limited execution compartments
607
608=head1 AUTHORS
609
610Originally designed and implemented by Malcolm Beattie,
611mbeattie@sable.ox.ac.uk as part of Safe version 1.
612
613Split out from Safe module version 1, named opcode tags and other
614changes added by Tim Bunce.
615
616=cut
617