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