Opcode - perlコードコンパイル時の opcode 無効化

目次


名前

Opcode - perlコードコンパイル時の opcode 無効化


概要

  use Opcode;

説明

Perl コードは実行前に常に内部形式にコンパイルされます.

perl コードの評価(例えば "eval" や "do 'file'") は コードを内部形式へとコンパイルし, コンパイルエラーがなければ 実行されます. 内部形式は数多くの異なる opcode によって 構成されています.

デフォルトでは何のopmaskも適用されず全てのコードにコンパイルできます.

Opcode モジュールは perl の次の何らかのコードのコンパイル時に 効果を持つ 演算マスク の定義を可能にします. マスクされた opcode を持つコードをコンパイルしようとするとそのコンパイルは エラーとなり失敗します. そしてコードは実行されません.


留意事項

Opcode モジュールは通常直接使用するものではありません. 使用する状況に応じて ops プラグマや Safe モジュールを参照してください.


警告

The authors make no warranty, implied or otherwise, about the suitability of this software for safety or security purposes.

The authors shall not in any case be liable for special, incidental, consequential, indirect or other similar damages arising from the use of this software.

Your mileage will vary. If in any doubt do not use it.


演算子名と演算子リスト

演算子名の正式なリストは Perl ソース配布物(及び perl ライブラリに インストールされている) opcode.h ファイルで定義及び初期化 されている PL_op_name 配列に格納されてるものです.

各演算子は簡潔名(演算子のopname)及び冗長な又は認識しやすい記述的な名前の 両方をもっています. opdesc 関数で演算子のリストに対する説明文の リストを取得できます.

以下にある多くの関数及びメソッドはパラメータに演算子のリストをとります. ほとんどの演算子リストはいくつかの種類の要素からなります. 各要素は次のいずれかです:

演算子名 (opname)

演算子名は大概は enterloop, leaveloop, last, next, redo 等のように 小文字で構成されています. gv2cv, i_ncmp, ftsvtx の様に, 時々いくぶん 不思議なものもあります.

演算子タグ名 (optag)

演算子タグは演算子のグループ(又は集合)を参照するために使用されます. タグ名は常にコロンで始まります. Opcode モジュールではいくつかの optag を定義してあり, また, ユーザは define_optag 関数で他の タグを定義することもできます.

否定付き演算子名及び演算子タグ名

opname や optag は !mkdir の様に感嘆符を前置することができます. opname や optag の否定はその時に積み立てたopsの集合から対応するops を取り除くことを意味します.

演算子集合 (opset)

opset は集合もしくは0個もしくはそれ以上の演算子を保持するおよそ 44 バイトのバイナリ文字列です.

opset 及び opset_to_ops 関数は演算子のリストからopsetに変換及びその逆 を行います.

どんな演算子のリストが与えられたとしても1つまたはそれ以上のopset を使用できます. 後述の opset の操作も参照してください.


opcode 関数

The Opcode package contains functions for manipulating operator names tags and sets. All are available for export by the package.

opcodes

In a scalar context opcodes returns the number of opcodes in this version of perl (around 350 for perl-5.7.0).

In a list context it returns a list of all the operator names. (Not yet implemented, use @names = opset_to_ops(full_opset).)

opset (OP, ...)

Returns an opset containing the listed operators.

opset_to_ops (OPSET)

Returns a list of operator names corresponding to those operators in the set.

opset_to_hex (OPSET)

Returns a string representation of an opset. Can be handy for debugging.

full_opset

Returns an opset which includes all operators.

empty_opset

Returns an opset which contains no operators.

invert_opset (OPSET)

Returns an opset which is the inverse set of the one supplied.

verify_opset (OPSET, ...)

Returns true if the supplied opset looks like a valid opset (is the right length etc) otherwise it returns false. If an optional second parameter is true then verify_opset will croak on an invalid opset instead of returning false.

Most of the other Opcode functions call verify_opset automatically and will croak if given an invalid opset.

define_optag (OPTAG, OPSET)

Define OPTAG as a symbolic name for OPSET. Optag names always start with a colon :.

The optag name used must not be defined already (define_optag will croak if it is already defined). Optag names are global to the perl process and optag definitions cannot be altered or deleted once defined.

It is strongly recommended that applications using Opcode should use a leading capital letter on their tag names since lowercase names are reserved for use by the Opcode module. If using Opcode within a module you should prefix your tags names with the name of your module to ensure uniqueness and thus avoid clashes with other modules.

opmask_add (OPSET)

Adds the supplied opset to the current opmask. Note that there is currently no mechanism for unmasking ops once they have been masked. This is intentional.

opmask

Returns an opset corresponding to the current opmask.

opdesc (OP, ...)

This takes a list of operator names and returns the corresponding list of operator descriptions.

opdump (PAT)

Dumps to STDOUT a two column list of op names and op descriptions. If an optional pattern is given then only lines which match the (case insensitive) pattern will be output.

It's designed to be used as a handy command line utility:

	perl -MOpcode=opdump -e opdump
	perl -MOpcode=opdump -e 'opdump Eval'

opset の操作

Opsets may be manipulated using the perl bit vector operators & (and), | (or), ^ (xor) and ~ (negate/invert).

However you should never rely on the numerical position of any opcode within the opset. In other words both sides of a bit vector operator should be opsets returned from Opcode functions.

Also, since the number of opcodes in your current version of perl might not be an exact multiple of eight, there may be unused bits in the last byte of an upset. This should not cause any problems (Opcode functions ignore those extra bits) but it does mean that using the ~ operator will typically not produce the same 'physical' opset 'string' as the invert_opset function.


TO DO (maybe)

    $bool = opset_eq($opset1, $opset2)	true if opsets are logically eqiv

    $yes = opset_can($opset, @ops)	true if $opset has all @ops set

    @diff = opset_diff($opset1, $opset2) => ('foo', '!bar', ...)

定義済み opcode タグ

:base_core
    null stub scalar pushmark wantarray const defined undef

    rv2sv sassign

    rv2av aassign aelem aelemfast aslice av2arylen

    rv2hv helem hslice each values keys exists delete

    preinc i_preinc predec i_predec postinc i_postinc postdec i_postdec
    int hex oct abs pow multiply i_multiply divide i_divide
    modulo i_modulo add i_add subtract i_subtract

    left_shift right_shift bit_and bit_xor bit_or negate i_negate
    not complement

    lt i_lt gt i_gt le i_le ge i_ge eq i_eq ne i_ne ncmp i_ncmp
    slt sgt sle sge seq sne scmp

    substr vec stringify study pos length index rindex ord chr

    ucfirst lcfirst uc lc quotemeta trans chop schop chomp schomp

    match split qr

    list lslice splice push pop shift unshift reverse

    cond_expr flip flop andassign orassign and or xor

    warn die lineseq nextstate scope enter leave setstate

    rv2cv anoncode prototype

    entersub leavesub leavesublv return method method_named -- XXX loops via recursion?

    leaveeval -- needed for Safe to operate, is safe without entereval
:base_mem

これらのメモリ関連のopsは :base_core には含まれていません. これはリソースアタック(例えば有効な全メモリの消費)を簡単に実装できるためです.

    concat repeat join range

    anonlist anonhash

この optag が存在するにもかかわらずメモリリソースアタックは :base_core のみで 恐らく可能な点に注意してください.

これらのopsの無効化はメモリリソースアタックを防止することを試みる とても重い手法です. 特定のメモリ制限メカニズムはperlに近い将来 加えられるでしょう.

:base_loop

これらのループ関連のopsは :base_core には含まれていません. これはリソースアタック(例えば有効な全CPU時間の消費)を簡単に実装できるためです.

    grepstart grepwhile
    mapstart mapwhile
    enteriter iter
    enterloop leaveloop unstack
    last next redo
    goto
:base_io

These ops enable filehandle (rather than filename) based input and output. These are safe on the assumption that only pre-existing filehandles are available for use. To create new filehandles other ops such as open would need to be enabled.

    readline rcatline getc read

    formline enterwrite leavewrite

    print sysread syswrite send recv

    eof tell seek sysseek

    readdir telldir seekdir rewinddir
:base_orig

These are a hotchpotch of opcodes still waiting to be considered

    gvsv gv gelem

    padsv padav padhv padany

    rv2gv refgen srefgen ref

    bless -- could be used to change ownership of objects (reblessing)

    pushre regcmaybe regcreset regcomp subst substcont

    sprintf prtf -- can core dump

    crypt

    tie untie

    dbmopen dbmclose
    sselect select
    pipe_op sockpair

    getppid getpgrp setpgrp getpriority setpriority localtime gmtime

    entertry leavetry -- can be used to 'hide' fatal errors

    custom -- where should this go
:base_math

These ops are not included in :base_core because of the risk of them being used to generate floating point exceptions (which would have to be caught using a $SIG{FPE} handler).

    atan2 sin cos exp log sqrt

These ops are not included in :base_core because they have an effect beyond the scope of the compartment.

    rand srand
:base_thread

これらの ops はマルチスレッド関連です.

    lock threadsv
:default

opsの手頃なデフォルト集合用の便利なタグ名. (現在許可されている opsでも開発が続いている間は不定(unstable)です. 変更されるかもしれません.)

    :base_core :base_mem :base_loop :base_io :base_orig :base_thread

安全のために(そうでなければなぜOpcodeモジュールを使う?) この定義を当てにするべきではありません. つまり他のoptagも.

:filesys_read
    stat lstat readlink

    ftatime ftblk ftchr ftctime ftdir fteexec fteowned fteread
    ftewrite ftfile ftis ftlink ftmtime ftpipe ftrexec ftrowned
    ftrread ftsgid ftsize ftsock ftsuid fttty ftzero ftrwrite ftsvtx

    fttext ftbinary

    fileno
:sys_db
    ghbyname ghbyaddr ghostent shostent ehostent      -- hosts
    gnbyname gnbyaddr gnetent snetent enetent         -- networks
    gpbyname gpbynumber gprotoent sprotoent eprotoent -- protocols
    gsbyname gsbyport gservent sservent eservent      -- services

    gpwnam gpwuid gpwent spwent epwent getlogin       -- users
    ggrnam ggrgid ggrent sgrent egrent                -- groups
:browse

A handy tag name for a reasonable default set of ops beyond the :default optag. Like :default (and indeed all the other optags) its current definition is unstable while development continues. It will change.

The :browse tag represents the next step beyond :default. It it a superset of the :default ops and adds :filesys_read the :sys_db. The intent being that scripts can access more (possibly sensitive) information about your system but not be able to change it.

    :default :filesys_read :sys_db
:filesys_open
    sysopen open close
    umask binmode

    open_dir closedir -- other dir ops are in :base_io
:filesys_write
    link unlink rename symlink truncate

    mkdir rmdir

    utime chmod chown

    fcntl -- not strictly filesys related, but possibly as dangerous?
:subprocess
    backtick system

    fork

    wait waitpid

    glob -- access to Cshell via <`rm *`>
:ownprocess
    exec exit kill

    time tms -- could be used for timing attacks (paranoid?)
:others

This tag holds groups of assorted specialist opcodes that don't warrant having optags defined for them.

SystemV Interprocess Communications:

    msgctl msgget msgrcv msgsnd

    semctl semget semop

    shmctl shmget shmread shmwrite
:still_to_be_decided
    chdir
    flock ioctl

    socket getpeername ssockopt
    bind connect listen accept shutdown gsockopt getsockname

    sleep alarm -- changes global timer state and signal handling
    sort -- assorted problems including core dumps
    tied -- can be used to access object implementing a tie
    pack unpack -- can be used to create/use memory pointers

    entereval -- can be used to hide code from initial compile
    require dofile 

    caller -- get info about calling environment and args

    reset

    dbstate -- perl -d version of nextstate(ment) opcode
:dangerous

This tag is simply a bucket for opcodes that are unlikely to be used via a tag name but need to be tagged for completness and documentation.

    syscall dump chroot

関連項目

ops(3) -- Opcode モジュールに対する perl プラグマインターフェース

Safe(3) -- opcode 及び名前空間を制限した実行環境


著者

はじめの設計及び実装は Malcolm Beattie, mbeattie@sable.ox.ac.uk に よって Safe バージョン1の一部として行われました.

Safe モジュールバージョン1からの分離及び名前付きopcodeタグ, そしてその他の変更は Tim Bunce によって追加されました.


和訳

山科 氷魚 (YAMASHINA Hio) <hio at hio.jp>, 2005/05/08, VERSION 1.05

Opcode - perlコードコンパイル時の opcode 無効化

索引

Opcode - perlコードコンパイル時の opcode 無効化