5.38.0

名前

perlsec - Perl security

perlsec - Perl のセキュリティ

説明

Perl is designed to make it easy to program securely even when running with extra privileges, like setuid or setgid programs. Unlike most command line shells, which are based on multiple substitution passes on each line of the script, Perl uses a more conventional evaluation scheme with fewer hidden snags. Additionally, because the language has more builtin functionality, it can rely less upon external (and possibly untrustworthy) programs to accomplish its purposes.

Perl は、プログラムが setuid や setgid されるような特別な権限を付加されて 実行されたときでもセキュリティ保持が容易になるように設計されています。 スクリプトの一行ごとの多重置換を行うことに基づいているような大部分の コマンドラインシェルとは違って、Perl は隠れた障害が少ないような、 より便利な評価手法を用いています。 それに加えて Perl はより多くの組み込み関数を持っているので、 ある目的を達成するために(信頼できないかもしれないような) 外部プログラムを使うことが少なくてすむのです。

セキュリティ脆弱性連絡窓口

If you believe you have found a security vulnerability in the Perl interpreter or modules maintained in the core Perl codebase, email the details to perl-security@perl.org. This address is a closed membership mailing list monitored by the Perl security team.

Perl インタプリタや、コア Perl コードベースで管理しているモジュールの セキュリティ脆弱性を発見したと確信したときには、詳細を perl-security@perl.org に メールしてください。 このアドレスは Perl セキュリティチームによって監視されている、 閉じられたメンバーのメーリングリストです。

See perlsecpolicy for additional information.

追加の情報については perlsecpolicy を参照してください。

SECURITY MECHANISMS AND CONCERNS

汚染モード

By default, Perl automatically enables a set of special security checks, called taint mode, when it detects its program running with differing real and effective user or group IDs. The setuid bit in Unix permissions is mode 04000, the setgid bit mode 02000; either or both may be set. You can also enable taint mode explicitly by using the -T command line flag. This flag is strongly suggested for server programs and any program run on behalf of someone else, such as a CGI script. Once taint mode is on, it's on for the remainder of your script.

Perl はデフォルトでは、 そのプログラムが異なる実ユーザー ID、実効ユーザー ID、実グループ ID、 実効グループ ID を使って実行されることを検出したときに、 自動的に 汚染モード (taint mode) と呼ばれる特別なセキュリティチェックの セットを有効にします。 UNIX パーミッションにおける setuid ビットはモード 04000 で、 setgid ビットはモード 02000 です。 これらは重複してセットすることもできます。 汚染モードは、コマンドラインフラグ -T を使って陽に有効にすることもできます。 このフラグはサーバープログラムであるとか、 CGI スクリプトのような、他の誰かにすりかわって実行されるプログラムに 使うことを 強く 勧めます。

While in this mode, Perl takes special precautions called taint checks to prevent both obvious and subtle traps. Some of these checks are reasonably simple, such as verifying that path directories aren't writable by others; careful programmers have always used checks like these. Other checks, however, are best supported by the language itself, and it is these checks especially that contribute to making a set-id Perl program more secure than the corresponding C program.

このモードで動作しているとき、Perl は明白な罠と隠れた罠の両方に対処するために 汚染検査 (taint check) と呼ばれる特別な警戒を行います。 これらのチェックの幾つかは、単純です; path ディレクトリが他から書き込み 可能でないことを検査するといったことがそうです; 注意深いプログラマーは常に これらのことはチェックしています。 このほかのチェックはしかしながら、言語自身によって最も良くサポートされます; そして、これらのチェックは特に set-id された Perl プログラムを対応する C プログラムよりも安全にするのに貢献するのです。

You may not use data derived from outside your program to affect something else outside your program--at least, not by accident. All command line arguments, environment variables, locale information (see perllocale), results of certain system calls (readdir(), readlink(), the variable of shmread(), the messages returned by msgrcv(), the password, gcos and shell fields returned by the getpwxxx() calls), and all file input are marked as "tainted". Tainted data may not be used directly or indirectly in any command that invokes a sub-shell, nor in any command that modifies files, directories, or processes, with the following exceptions:

自分のプログラムの外側から来たデータをプログラムの外の何かに影響を 及ぼすために使うことは、少なくともアクシデントででもなければ、できません。 すべてのコマンドライン引数、環境変数、ロケール情報(perllocale を参照)、 幾つかのシステムコールの結果(readdir(), readlink(), shmread() の変数、 msgrcv() が返したメッセージ、パスワード、getpwxxx() 呼び出しが返した gecos フィールドとシェルフィールド)、すべてのファイル入力といったものは “汚染された”(tainted) と目印が付けられます。 汚染されたデータは直接、間接を問わずサブシェルを起動するコマンドに使うことも、 ファイルやディレクトリ、プロセスに変更を加えるようなコマンドに 使うこともできません; 但し 以下の例外 があります。

Support for taint checks adds an overhead to all Perl programs, whether or not you're using the taint features. Perl 5.18 introduced C preprocessor symbols that can be used to disable the taint features.

汚染チェック対応は、汚染チェック機能をを使うかどうかに関わらず、 全ての Perl プログラムにオーバーヘッドを追加します。 Perl 5.18 では、汚染チェック機能を無効にするために使える C プリプロセッサシンボルが導入されました。

  • Arguments to print and syswrite are not checked for taintedness.

    printsyswrite の引数に対する汚染検査は 行われません

  • Symbolic methods

    シンボリックメソッド

        $obj->$method(@args);

    and symbolic sub references

    とシンボリックサブルーチンリファレンス

        &{$foo}(@args);
        $foo->(@args);

    are not checked for taintedness. This requires extra carefulness unless you want external data to affect your control flow. Unless you carefully limit what these symbolic values are, people are able to call functions outside your Perl code, such as POSIX::system, in which case they are able to run arbitrary external code.

    は汚染性がチェックされません。 これは、あなたの制御フローが外部データに影響されたいと思わないなら、 さらなる慎重さを要求します。 これらのシンボリックな値が何かを注意深く制限しないと、POSIX::system のような あなたの Perl コードの 外側 の関数を呼び出すことを可能にし、この場合 任意の外部コードを実行できるようになります。

  • Hash keys are never tainted.

    ハッシュのキーは 決して 汚染されません。

For efficiency reasons, Perl takes a conservative view of whether data is tainted. If an expression contains tainted data, any subexpression may be considered tainted, even if the value of the subexpression is not itself affected by the tainted data.

効率上の理由から、Perl はデータが汚染されているかどうかについて保守的な 見方をします。 汚染されているデータが式に含まれている場合、たとえ副式の値自身は汚染された データに影響を受けない場合でも、全ての副式も汚染されたものとして 扱います。

Because taintedness is associated with each scalar value, some elements of an array or hash can be tainted and others not. The keys of a hash are never tainted.

汚染は各スカラ値に結び付けられるので、配列の幾つかの要素が汚染されていて、 そのほかの要素はそうではないということもありえます。 ハッシュのキーは 決して 汚染されません。

For example:

例を示します:

    $arg = shift;               # $arg is tainted
    $hid = $arg . 'bar';        # $hid is also tainted
    $line = <>;                 # Tainted
    $line = <STDIN>;            # Also tainted
    open FOO, "/home/me/bar" or die $!;
    $line = <FOO>;              # Still tainted
    $path = $ENV{'PATH'};       # Tainted, but see below
    $data = 'abc';              # Not tainted
    $arg = shift;               # $arg は汚染された
    $hid = $arg . 'bar';        # $hid も汚染された
    $line = <>;                 # 汚染された
    $line = <STDIN>;            # これも汚染された
    open FOO, "/home/me/bar" or die $!;
    $line = <FOO>;              # まだ汚染されている
    $path = $ENV{'PATH'};       # 汚染されているが、下記を参照のこと
    $data = 'abc';              # 汚染されていない
    system "echo $arg";         # Insecure
    system "/bin/echo", $arg;   # Considered insecure
                                # (Perl doesn't know about /bin/echo)
    system "echo $hid";         # Insecure
    system "echo $data";        # Insecure until PATH set
    system "echo $arg";         # 安全ではない
    system "/bin/echo", $arg;   # 安全ではないと考えられる
                                # (Perl は /bin/echo について知らない)
    system "echo $hid";         # 安全ではない
    system "echo $data";        # PATHを設定するまでは安全ではない
    $path = $ENV{'PATH'};       # $path now tainted
    $path = $ENV{'PATH'};       # $path が汚染された

    $ENV{'PATH'} = '/bin:/usr/bin';
    delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
    $path = $ENV{'PATH'};       # $path now NOT tainted
    system "echo $data";        # Is secure now!
    $path = $ENV{'PATH'};       # $path は汚染されていない
    system "echo $data";        # これで安全!
    open(FOO, "< $arg");        # OK - read-only file
    open(FOO, "> $arg");        # Not OK - trying to write
    open(FOO, "< $arg");        # OK - 読み込みのみのファイル
    open(FOO, "> $arg");        # Not OK - 書き込みしようとしている

    open(FOO,"echo $arg|");     # Not OK
    open(FOO,"-|")
        or exec 'echo', $arg;   # Also not OK
    $shout = `echo $arg`;       # Insecure, $shout now tainted
    $shout = `echo $arg`;       # 安全でない; $shoutは汚染された
    unlink $data, $arg;         # Insecure
    umask $arg;                 # Insecure
    unlink $data, $arg;         # 安全でない
    umask $arg;                 # 安全でない
    exec "echo $arg";           # Insecure
    exec "echo", $arg;          # Insecure
    exec "sh", '-c', $arg;      # Very insecure!
    exec "echo $arg";           # 安全でない
    exec "echo", $arg;          # 安全でない
    exec "sh", '-c', $arg;      # とても安全ではない!
    @files = <*.c>;             # insecure (uses readdir() or similar)
    @files = glob('*.c');       # insecure (uses readdir() or similar)
    @files = <*.c>;             # 安全でない (readdir() のようなものを使う)
    @files = glob('*.c');       # 安全でない (readdir() のようなものを使う)
    # In either case, the results of glob are tainted, since the list of
    # filenames comes from outside of the program.
    # どちらの場合でも、glob の結果は汚染されています; ファイル名の一覧は
    # プログラムの外部から来るからです。
    $bad = ($arg, 23);          # $bad will be tainted
    $arg, `true`;               # Insecure (although it isn't really)
    $bad = ($arg, 23);          # $bad は汚染されているかも
    $arg, `true`;               # 安全でない (実際はそうでなくても)

If you try to do something insecure, you will get a fatal error saying something like "Insecure dependency" or "Insecure $ENV{PATH}".

安全でないことをやろうとすると、"Insecure dependency" や "Insecure $ENV{PATH}" のような致命的エラーとなるでしょう。

The exception to the principle of "one tainted value taints the whole expression" is with the ternary conditional operator ?:. Since code with a ternary conditional

「一つの汚染された値が式全体を汚染する」の原則の例外は、3 項条件演算子 ?: です。 3 項条件を使ったコード

    $result = $tainted_value ? "Untainted" : "Also untainted";

is effectively

というのは事実上

    if ( $tainted_value ) {
        $result = "Untainted";
    } else {
        $result = "Also untainted";
    }

it doesn't make sense for $result to be tainted.

なので、$result が汚染されたと考えるのは意味がありません。

汚染されたデータの検出と洗浄

To test whether a variable contains tainted data, and whose use would thus trigger an "Insecure dependency" message, you can use the tainted() function of the Scalar::Util module, available in your nearby CPAN mirror, and included in Perl starting from the release 5.8.0. Or you may be able to use the following is_tainted() function.

ある変数が汚染されたデータを保持しているかどうかを検査するため、そして、 "Insecure dependency" メッセージの引き金になる可能性があるかどうかを 検査するために、CPAN にあり、5.8.0 からは Perl に含まれている Scalar::Util モジュールの tainted() 関数を使えます。 あるいは、以下のような関数 is_tainted() を使うことができます。

    sub is_tainted {
        local $@;   # Don't pollute caller's value.
        return ! eval { eval("#" . substr(join("", @_), 0, 0)); 1 };
    }

This function makes use of the fact that the presence of tainted data anywhere within an expression renders the entire expression tainted. It would be inefficient for every operator to test every argument for taintedness. Instead, the slightly more efficient and conservative approach is used that if any tainted value has been accessed within the same expression, the whole expression is considered tainted.

この関数はある式のどこかにある汚染されたデータが式全体を汚染してしまうことを 利用しています。 これはすべての演算子に対して、そのすべての引数が汚染されているかどうかの 検査をするので効率は良くないでしょう。 その代わりに、一部の式において汚染された値にアクセスして式全体が 汚染されたとみなされるような場合には、もっと効率が良くて 保守的な方法が使われます。

But testing for taintedness gets you only so far. Sometimes you have just to clear your data's taintedness. Values may be untainted by using them as keys in a hash; otherwise the only way to bypass the tainting mechanism is by referencing subpatterns from a regular expression match. Perl presumes that if you reference a substring using $1, $2, etc. in a non-tainting pattern, that you knew what you were doing when you wrote that pattern. That means using a bit of thought--don't just blindly untaint anything, or you defeat the entire mechanism. It's better to verify that the variable has only good characters (for certain values of "good") rather than checking whether it has any bad characters. That's because it's far too easy to miss bad characters that you never thought of.

しかし、汚染の検査は面倒です。 あなたのデータの汚染を取り除くだけということもあるでしょう。 値はハッシュのキーとして使うことで浄化されます; さもなければ、 汚染検査機構をバイパスするためのただ一つの方法は、 マッチした正規表現のサブパターンを参照することです。 Perl は、あなたが $1、$2 などを使って汚染されていないパターンで部分文字列を 参照したときに、あなたがパターンを記述したときに何を行うのかを知っていたと 仮定します。 つまり、汚染されていないものを束縛しないか、機構全体を 無効にするということです。 これは、変数がなんらかの悪い文字を持っているかどうかを 検査するというのではなく、変数が良い文字のみを持っていることの検査には 都合が良いです。 これは(あなたが考えもしないような)悪い文字を見失うことがあまりにも 簡単であるからです。

Here's a test to make sure that the data contains nothing but "word" characters (alphabetics, numerics, and underscores), a hyphen, an at sign, or a dot.

以下に示す例は、データに“語”(アルファベット、数字、アンダースコア)の 文字、ハイフン、アットマーク、ドット以外のものが入っていないことを 検査するものです。

    if ($data =~ /^([-\@\w.]+)$/) {
        $data = $1;                     # $data now untainted
    } else {
        die "Bad data in '$data'";      # log this somewhere
    }

This is fairly secure because /\w+/ doesn't normally match shell metacharacters, nor are dot, dash, or at going to mean something special to the shell. Use of /.+/ would have been insecure in theory because it lets everything through, but Perl doesn't check for that. The lesson is that when untainting, you must be exceedingly careful with your patterns. Laundering data using regular expression is the only mechanism for untainting dirty data, unless you use the strategy detailed below to fork a child of lesser privilege.

これはかなり安全です; なぜなら \w+ は通常シェルのメタ文字には マッチしませんし、ドットやダッシュなどのシェルにとって特別な意味を 持つようなものにもマッチしないからです。 /.+/ を使うのは、これはすべてを通してしまうのに Perl はそれを チェックしませんから、理論的には安全ではありません。 汚染を取り除くときには、自分のパターンについて十二分に注意せねばなりません。 正規表現を使ったデータの洗浄は、先に説明したより低い特権度の子プロセスを fork するための戦略を使うまでは汚れたデータの汚染除去 のみ の機構です。

The example does not untaint $data if use locale is in effect, because the characters matched by \w are determined by the locale. Perl considers that locale definitions are untrustworthy because they contain data from outside the program. If you are writing a locale-aware program, and want to launder data with a regular expression containing \w, put no locale ahead of the expression in the same block. See "SECURITY" in perllocale for further discussion and examples.

先の例では、use locale が有効であるときには $data の汚染除去を 行いません; なぜなら、\w にマッチする文字はロケールによって 決定されるからです。 Perl は、ロケールで決まることを、それがプログラムの外から来たデータから 構成されているという理由によって信用できないものとみなします。 もしロケールを考慮したプログラムを書いていて、\w を含んだ正規表現で データの洗浄を行いたいというのなら、式の置かれたのと同じブロックの前の部分に no localeを置きます。 "SECURITY" in perllocale に詳しい説明と例があります。

"#!" 行のスイッチ

When you make a script executable, in order to make it usable as a command, the system will pass switches to perl from the script's #! line. Perl checks that any command line switches given to a setuid (or setgid) script actually match the ones set on the #! line. Some Unix and Unix-like environments impose a one-switch limit on the #! line, so you may need to use something like -wU instead of -w -U under such systems. (This issue should arise only in Unix or Unix-like environments that support #! and setuid or setgid scripts.)

自分の作ったスクリプトをコマンドのように使えるようにしたとき、システムは perl に対して、スクリプトの #! の行からコマンドラインスイッチを渡します。 Perl は、setuid(あるいは setgid) されたスクリプトに与えられた コマンドラインスイッチが #! 行にあるものと本当に一致するかどうかを検査します。 一部の UNIX や UNIX 風の環境では #! 行には一つのスイッチしか置けないので、 そういったシステムでは -w -U といった形式ではなく -wU のようにする必要があるでしょう。 (これは #! をサポートしていて、setuid や setgid スクリプトが使える UNIX 環境や UNIX に似た環境でのみ行なわれることです。)

汚染検査モードと @INC

+When the taint mode (-T) is in effect, the environment variables +PERL5LIB, PERLLIB, and PERL_USE_UNSAFE_INC are ignored by Perl. You can still adjust @INC from outside the program by using the -I command line option as explained in perlrun. The two environment variables are ignored because they are obscured, and a user running a program could be unaware that they are set, whereas the -I option is clearly visible and therefore permitted.

汚染検査モード(-T) が有効のとき、 環境変数 PERL5LIB, PERLLIB, PERL_USE_UNSAFE_INC は Perl から無視されます。 それでも、perlrun で説明されている -I コマンドラインオプションを使うことで、 プログラムの外部から @INC を調整出来ます。 二つの環境変数は不明確で、プログラムを実行している ユーザーはこの変数が設定されていることに気付かないかもしれないので 無視されますが、一方 -I オプションは明確に見えるので許可されます。

Another way to modify @INC without modifying the program, is to use the lib pragma, e.g.:

プログラムを修正することなく @INC を修正するもう一つの方法は、 lib プラグマを使うことです; つまり:

  perl -Mlib=/foo program

The benefit of using -Mlib=/foo over -I/foo, is that the former will automagically remove any duplicated directories, while the latter will not.

-I/foo ではなく -Mlib=/foo を使う利点は、後者だけが自動的に重複した ディレクトリを自動的に除去することです。

Note that if a tainted string is added to @INC, the following problem will be reported:

もし汚染された文字列が @INC に追加されると、以下の問題が報告されることに 注意してください:

  Insecure dependency in require while running with -T switch

On versions of Perl before 5.26, activating taint mode will also remove the current directory (".") from the default value of @INC. Since version 5.26, the current directory isn't included in @INC by default.

5.26 より前のバージョンの Perl では、汚染モードを有効にすると、 @INC のデフォルト値からカレントディレクトリ (".") を削除します。 バージョン 5.26 からは、デフォルトではカレントディレクトリは @INC に 含まれていません。

実行パスを洗浄する

For "Insecure $ENV{PATH}" messages, you need to set $ENV{'PATH'} to a known value, and each directory in the path must be absolute and non-writable by others than its owner and group. You may be surprised to get this message even if the pathname to your executable is fully qualified. This is not generated because you didn't supply a full path to the program; instead, it's generated because you never set your PATH environment variable, or you didn't set it to something that was safe. Because Perl can't guarantee that the executable in question isn't itself going to turn around and execute some other program that is dependent on your PATH, it makes sure you set the PATH.

"Insecure $ENV{PATH}" メッセージに対処するために、$ENV{'PATH'} に 既知の値を設定する必要があります; そして path に含まれている各ディレクトリは、 絶対パスで、そのディレクトリの所有者やグループ以外からの書き込みを 禁じていなければなりません。 実行しようとしているファイルをフルパスで書いたとしてもこのメッセージが 出るので、びっくりすることがあるかもしれません。 このメッセージはプログラムのフルパスを書かなかったから出力されるではなく、 環境変数 PATH を設定しなかったり安全でない値を 設定したりしたために出力されるのです。 Perl は対象となっている実行ファイルが自分自身を方向転換したり、 PATH を参照して別のプログラムを起動したりするかどうかを知ることができないので、 確実に自分で PATH を設定するようにします。

The PATH isn't the only environment variable which can cause problems. Because some shells may use the variables IFS, CDPATH, ENV, and BASH_ENV, Perl checks that those are either empty or untainted when starting subprocesses. You may wish to add something like this to your setid and taint-checking scripts.

この問題を引き起こす環境変数は PATH だけではありません。 一部のシェルでは、IFS、CDPATH、ENV、BASH_ENV のような環境変数を 使っていますから、Perl はこれらの変数がからであるかあるいは サブプロセスが起動したときに汚染されていないかどうかチェックします。 setid していたり、汚染検査をするスクリプトに 以下のような行を付け加えたくなるかしれません。

    delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};   # Make %ENV safer

It's also possible to get into trouble with other operations that don't care whether they use tainted values. Make judicious use of the file tests in dealing with any user-supplied filenames. When possible, do opens and such after properly dropping any special user (or group!) privileges. Perl doesn't prevent you from opening tainted filenames for reading, so be careful what you print out. The tainting mechanism is intended to prevent stupid mistakes, not to remove the need for thought.

このほかの、汚染された値を使っているかどうかに注意を払わないような 操作によってトラブルに巻込まれる可能性もあります。 ユーザーが使うようなファイル名を扱うファイル検査の使用を賢明なものにします。 可能であれば、ファイルをオープンした その後で 適切にスペシャルユーザー (グループも!)の特権を落とします。 Perl はあなたが読み出しのために汚染されたファイル名を使ってファイルを オープンすることを妨げませんから、出力の際には注意しましょう。 汚染検査機構はばかばかしいミスに対応するためのものであって、 必要なことを取り除くものではありません。

Perl does not call the shell to expand wild cards when you pass system and exec explicit parameter lists instead of strings with possible shell wildcards in them. Unfortunately, the open, glob, and backtick functions provide no such alternate calling convention, so more subterfuge will be required.

Perl は、systemexec に対してシェルのワイルドカードが あるかもしれないような文字列ではなく陽にパラメータリストを渡した場合には、 ワイルドカードの展開のためにシェルを呼び出したりしません。 残念なことに、openglob、逆クォートといったものはそういった別の 呼び出し手順を提供していないので、より多くのごまかしが必要とされます。

Perl provides a reasonably safe way to open a file or pipe from a setuid or setgid program: just create a child process with reduced privilege who does the dirty work for you. First, fork a child using the special open syntax that connects the parent and child by a pipe. Now the child resets its ID set and any other per-process attributes, like environment variables, umasks, current working directories, back to the originals or known safe values. Then the child process, which no longer has any special permissions, does the open or other system call. Finally, the child passes the data it managed to access back to the parent. Because the file or pipe was opened in the child while running under less privilege than the parent, it's not apt to be tricked into doing something it shouldn't.

Perl は、setuid や setgid されたプログラムから安全にファイルやパイプを オープンする方法を提供しています。 これは単に、汚れ仕事をするための制限された権利を持った子プロセスを 生成するというものです。 まず最初に、パイプによって親プロセスと子プロセスとを繋ぐ構文の 特別な open を使って子プロセスを fork します。 このとき、子プロセスはその ID セットをリセットしさらにその他の プロセス毎の属性をリセットして、オリジナルの、 もしくは安全な既知の値へと戻します。 それからもはや何の特別のパーミッションも持っていない子プロセスが open などのシステムコールを実行します。 ファイルやパイプは親プロセスよりも低い特権の元で実行されている 子プロセスでオープンされたので、すべきではないようなことを ごまかしておこなうことはできません。

Here's a way to do backticks reasonably safely. Notice how the exec is not called with a string that the shell could expand. This is by far the best way to call something that might be subjected to shell escapes: just never call the shell at all.

以下に示すのは、安全に逆クォートを行う方法です。 どのようにして exec はシェルが展開するかもしれない文字列を伴って 呼び出されないようになっているかに注目してください。 これはシェルをエスケープする目的には最善の方法というわけではありません; これは単に、シェルを呼び出さないというだけです。

        use English;
        die "Can't fork: $!" unless defined($pid = open(KID, "-|"));
        if ($pid) {           # parent
            while (<KID>) {
                # do something
            }
            close KID;
        } else {
            my @temp     = ($EUID, $EGID);
            my $orig_uid = $UID;
            my $orig_gid = $GID;
            $EUID = $UID;
            $EGID = $GID;
            # Drop privileges
            $UID  = $orig_uid;
            $GID  = $orig_gid;
            # Make sure privs are really gone
            ($EUID, $EGID) = @temp;
            die "Can't drop privileges"
                unless $UID == $EUID  && $GID eq $EGID;
            $ENV{PATH} = "/bin:/usr/bin"; # Minimal PATH.
            # Consider sanitizing the environment even more.
            exec 'myprog', 'arg1', 'arg2'
                or die "can't exec myprog: $!";
        }

A similar strategy would work for wildcard expansion via glob, although you can use readdir instead.

readdir を代わりに使うことができるにしても、同様の戦略が glob を 通じたワイルドカードの展開でも有効です。

Taint checking is most useful when although you trust yourself not to have written a program to give away the farm, you don't necessarily trust those who end up using it not to try to trick it into doing something bad. This is the kind of security checking that's useful for set-id programs and programs launched on someone else's behalf, like CGI programs.

汚染検査は、農場をくれてやる (give away the farm) ためのプログラムを 記述することを自分自身に任せないということではなくて、 最終的にそれをつかって良からぬなにかを行おうとしているだれかを 信頼する必要がないというときに最も便利なものです。 これは、set-id プログラムや、CGI プログラムのように誰かに すり変わって起動されるようなプログラムに便利なセキュリティチェックです。

This is quite different, however, from not even trusting the writer of the code not to try to do something evil. That's the kind of trust needed when someone hands you a program you've never seen before and says, "Here, run this." For that kind of safety, you might want to check out the Safe module, included standard in the Perl distribution. This module allows the programmer to set up special compartments in which all system operations are trapped and namespace access is carefully controlled. Safe should not be considered bullet-proof, though: it will not prevent the foreign code to set up infinite loops, allocate gigabytes of memory, or even abusing perl bugs to make the host interpreter crash or behave in unpredictable ways. In any case it's better avoided completely if you're really concerned about security.

しかしながら、これは良からぬなにかを行おうはしないコードの作者を 信用しないということとは明らかに違います。 これは誰かが、プログラムをあなたが今まで見たことのないようにいじって 「ほら、これを実行して」と言わせるようなときに必要な種類の信用です。 この種の安全性のために、Perl の配布パッケージに標準で含まれている Safe モジュールをチェックしたほうがいいかもしれません。 このモジュールはプログラマーがすべてのシステム操作をトラップし、 名前空間のアクセスが注意深く制御されるような 特別な仕切り(compartment)をセットアップすることを許します。 しかし Safe は防弾であると考えるべきではありません: 無限ループ、 何ギガバイトものメモリ割り当て、ホストインタプリタをクラッシュや予測不能な 振る舞いをさせるための perl のバグの悪用をする外部コードすら防げません。 本当にセキュリティのことを考えるならどの場合も完全に防いだ方が良いです。

Shebang の競合条件

Beyond the obvious problems that stem from giving special privileges to systems as flexible as scripts, on many versions of Unix, set-id scripts are inherently insecure right from the start. The problem is a race condition in the kernel. Between the time the kernel opens the file to see which interpreter to run and when the (now-set-id) interpreter turns around and reopens the file to interpret it, the file in question may have changed, especially if you have symbolic links on your system.

スクリプトと同じくらい柔軟に特別な権限をシステムに与えて しまう類の明白な問題の他に、多くの UNIX では、set-id されたスクリプトは 本質的に安全でない権利を最初から持っています。 その問題とは、カーネルにおける競合条件です。 インタープリターを実行するためにカーネルがファイルをオープンするのと、 (set-id された)インタープリターが起動してファイルを解釈するために 再度オープンするその間に、問題のファイルが変更されるかもしれません; 特に、使っているシステムがシンボリックリンクをサポートしている場合には。

Some Unixes, especially more recent ones, are free of this inherent security bug. On such systems, when the kernel passes the name of the set-id script to open to the interpreter, rather than using a pathname subject to meddling, it instead passes /dev/fd/3. This is a special file already opened on the script, so that there can be no race condition for evil scripts to exploit. On these systems, Perl should be compiled with -DSETUID_SCRIPTS_ARE_SECURE_NOW. The Configure program that builds Perl tries to figure this out for itself, so you should never have to specify this yourself. Most modern releases of SysVr4 and BSD 4.4 use this approach to avoid the kernel race condition.

一部の Unix、特に最近のものは、このようなセキュリティバグに対する耐性を 備えています。 そのようなシステムでは、インタプリタを起動するためにカーネルに set-id スクリプトが渡されたときにそのパス名をそのまま使うのではなく、 代わりに /dev/fd/3 を渡します。 これはスクリプトでは、あらかじめオープンされている特別なファイルですから、 邪悪なスクリプトをこじ入れるためにつかうことはできません。 こういったシステムにおいては、Perl は -DSETUID_SCRIPTS_ARE_SECURE_NOW を付加してコンパイルすべきでしょう。 Perl を構築する Configure プログラムは自分自身でこれを 見つけ出そうとするので、あなたが特別な何かをしなければならない、 ということはありあません。 SysVr4 の最近のリリースのほとんどや BSD4.4 は このアプローチをカーネルの競合条件を避けるために使っています。

If you don't have the safe version of set-id scripts, all is not lost. Sometimes this kernel "feature" can be disabled, so that the kernel either doesn't run set-id scripts with the set-id or doesn't run them at all. Either way avoids the exploitability of the race condition, but doesn't help in actually running scripts set-id.

安全なバージョンの set-id スクリプトがない場合でも、他に手段が ないわけではありません。 カーネルは set-id スクリプトを set-id で実行しないか、 これらを全く実行しないことで、 このカーネル「仕様」は使用禁止にできることもあります。 どちらかの方法で競合条件の悪用可能性を避けることができますが、 実際にスクリプトを set-id で実行する助けにはなりません。

If the kernel set-id script feature isn't disabled, then any set-id script provides an exploitable vulnerability. Perl can't avoid being exploitable, but will point out vulnerable scripts where it can. If Perl detects that it is being applied to a set-id script then it will complain loudly that your set-id script is insecure, and won't run it. When Perl complains, you need to remove the set-id bit from the script to eliminate the vulnerability. Refusing to run the script doesn't in itself close the vulnerability; it is just Perl's way of encouraging you to do this.

kernel set-id スクリプト機能が禁止されていなければ、 任意の set-id スクリプトは悪用可能な脆弱性を持ちます。 Perl は悪用可能性を避けることはできませんが、 可能性のある脆弱性のあるスクリプトを示すことはできます。 Perl が set-id スクリプトが適用されていることを検出した場合、 あなたの set-id スクリプトは安全ではないとやかましく主張し、 実行しません。 Perl が文句を言った場合、脆弱性を取り除くためにスクリプトから set-id ビットを取り除く必要があります。 スクリプトの実行を拒否することは、それ自体で脆弱性を閉じることはありません; これは単にそうするようにあなたを後押しする Perl の方法です。

To actually run a script set-id, if you don't have the safe version of set-id scripts, you'll need to put a C wrapper around the script. A C wrapper is just a compiled program that does nothing except call your Perl program. Compiled programs are not subject to the kernel bug that plagues set-id scripts. Here's a simple wrapper, written in C:

実際に set-id でスクリプトを実行するために、安全なバージョンの set-id スクリプトを持っていない場合は、 スクリプトを C のラッパーで包む必要があります。 C ラッパーは、Perl プログラムを呼び出すことを除いては 何もしないプログラムです。 コンパイルされたプログラムは set-id されたスクリプトに関する カーネルのバグには影響されません。 次の例は、C で書いた単純なラッパーです:

    #include <unistd.h>
    #include <stdio.h>
    #include <string.h>
    #include <errno.h>

    #define REAL_PATH "/path/to/script"

    int main(int argc, char **argv)
    {
        execv(REAL_PATH, argv);
        fprintf(stderr, "%s: %s: %s\n",
                        argv[0], REAL_PATH, strerror(errno));
        return 127;
    }

Compile this wrapper into a binary executable and then make it rather than your script setuid or setgid. Note that this wrapper isn't doing anything to sanitise the execution environment other than ensuring that a safe path to the script is used. It only avoids the shebang race condition. It relies on Perl's own features, and on the script itself being careful, to make it safe enough to run the script set-id.

このラッパーをコンパイルして実行ファイルにし、スクリプトではなく この実行ファイル を setuid したり setgid します。 このラッパーは、スクリプトが使われる安全なパスであることを保証する以外に 実行環境をサニタイズしないことに注意してください。 これはシェバン競合条件のみを回避します。 スクリプトを set-id で実行するのに十分なぐらい安全であることは、 これは Perl 自身の機能と、スクリプト自身が注意深いことに依存しています。

あなたのプログラムを守る

There are a number of ways to hide the source to your Perl programs, with varying levels of "security".

ここで挙げるのは、あなたの Perl プログラムのソースコードをさまざまな “セキュリティ”のレベルで隠す方法です。

First of all, however, you can't take away read permission, because the source code has to be readable in order to be compiled and interpreted. (That doesn't mean that a CGI script's source is readable by people on the web, though.) So you have to leave the permissions at the socially friendly 0755 level. This lets people on your local system only see your source.

しかしまず最初にいっておきますが、ソースコードの読み込み権限を 落とすことは できません。 なぜなら、ソースコードは、コンパイルやインタープリットするために 読めるようになっていなければならないからです(これは、CGI スクリプトのソースが web の利用者から見ることができないというのとは違います)。 このため、パーミッションは 0755 レベルにしておかなければならないのです。 これによってあなたのローカルシステム上のユーザーはあなたのソースを 見ることだけになります。

Some people mistakenly regard this as a security problem. If your program does insecure things, and relies on people not knowing how to exploit those insecurities, it is not secure. It is often possible for someone to determine the insecure things and exploit them without viewing the source. Security through obscurity, the name for hiding your bugs instead of fixing them, is little security indeed.

一部の人達はこれをセキュリティ上の問題であると考えています。 あなたのプログラムが安全でないことを行っていて、 他人がそういったセキュリティの隙間をこじ開ける方法を知らないことに 頼っているのなら、それは安全ではないのです。 これはある人が安全でないことがらを見つけだし、 ソースを見ることなしにそれをこじ開けることの要因となります。 明快さを通したセキュリティはバグを直すのではなく隠すことに比べれば、 セキュリティをほんの少しだけしか傷つけません。

You can try using encryption via source filters (Filter::* from CPAN, or Filter::Util::Call and Filter::Simple since Perl 5.8). But crackers might be able to decrypt it. You can try using the byte code compiler and interpreter described below, but crackers might be able to de-compile it. You can try using the native-code compiler described below, but crackers might be able to disassemble it. These pose varying degrees of difficulty to people wanting to get at your code, but none can definitively conceal it (this is true of every language, not just Perl).

ソースフィルター(CPAN にある Filter::*, or Filter::Util::Call and Filter::Simple since Perl 5.8) を通して暗号化しようとすることはできます。 しかしクラッカーがそれを復号化することは可能でしょう。 先に説明したバイトコードコンパイラーとインタープリターを使うことも できますが、クラッカーはそれを逆コンパイルすることができるかもしれません。 ネイティブコードコンパイラーを使おうとしても、クラッカーはそれを 逆アセンブルできるかもしれません。 こういったことは、他人があなたの プログラムを手に入れようとすることを難しくしたりしますが、 プログラムを決定的に隠すことは誰にもできないのです(このことは、 Perl に限らずすべての言語にあてはまります)。

If you're concerned about people profiting from your code, then the bottom line is that nothing but a restrictive license will give you legal security. License your software and pepper it with threatening statements like "This is unpublished proprietary software of XYZ Corp. Your access to it does not give you permission to use it blah blah blah." You should see a lawyer to be sure your license's wording will stand up in court.

他人があなたのプログラムから受ける利益について気にしているのであれば、 制限つきライセンスがあなたに法的な安全を与えるでしょう。 あなたのソフトウェアのライセンスに、「本ソフトウェアは XYZ Corp.による、 公表されていない独占的ソフトウェアです。 あなたが使用するためにこれにアクセスすることは許可されておらず云々」のような 脅し文句を付けておきます。 あなたのライセンスの文言が法廷で確実に有効なものとなるように、 弁護士と相談したほうが良いでしょう。

Unicode

Unicode is a new and complex technology and one may easily overlook certain security pitfalls. See perluniintro for an overview and perlunicode for details, and "Security Implications of Unicode" in perlunicode for security implications in particular.

Unicode は新しくて複雑な技術で、ある種のセキュリティの罠を簡単に 見落としてしまいます。 概要については perluniintro を、詳細については perlunicode を、 そして特にセキュリティ実装については "Security Implications of Unicode" in perlunicode を参照してください。

アルゴリズム的複雑性攻撃

Certain internal algorithms used in the implementation of Perl can be attacked by choosing the input carefully to consume large amounts of either time or space or both. This can lead into the so-called Denial of Service (DoS) attacks.

Perl の実装で使われているある種の内部アルゴリズムは、多くの時間や 空間を消費するように注意深く選択された入力によって攻撃可能です。 これにより サービス拒否(Denial of Service) (DoS) 攻撃と呼ばれている ものを引き起こすことができます。

  • Hash Algorithm - Hash algorithms like the one used in Perl are well known to be vulnerable to collision attacks on their hash function. Such attacks involve constructing a set of keys which collide into the same bucket producing inefficient behavior. Such attacks often depend on discovering the seed of the hash function used to map the keys to buckets. That seed is then used to brute-force a key set which can be used to mount a denial of service attack. In Perl 5.8.1 changes were introduced to harden Perl to such attacks, and then later in Perl 5.18.0 these features were enhanced and additional protections added.

    ハッシュアルゴリズム - 以前 Perl で使われていたようなハッシュアルゴリズムは、 ハッシュ関数に対する衝突攻撃に対して脆弱であることでよく知られています。 この攻撃は、非効率的な振る舞いをさせるために同じバケツに入るようなキーの集合を 構築することで行われます。 このような攻撃はしばしばキーをバケツにマッピングするために使われる ハッシュ関数の種の発見に依存します。 この種はそれからサービス拒否攻撃を起こせるブルートフォースキー集合に 使われます。 Perl 5.8.1 でこのような攻撃に対する Perl の強化が導入され、後に Perl 5.18.0 で これらの機能は拡張され、追加の防御が追加されました。

    At the time of this writing, Perl 5.18.0 is considered to be well-hardened against algorithmic complexity attacks on its hash implementation. This is largely owed to the following measures mitigate attacks:

    これを書いている時点では、Perl 5.18.0 はハッシュ実装に対するアルゴリズム的 複雑性攻撃に対してよく防御されていると考えられています。 これは主に以下のような要素が攻撃を緩和していることに依ります:

    Hash Seed Randomization

    (ハッシュの種のランダム化)

    In order to make it impossible to know what seed to generate an attack key set for, this seed is randomly initialized at process start. This may be overridden by using the PERL_HASH_SEED environment variable, see "PERL_HASH_SEED" in perlrun. This environment variable controls how items are actually stored, not how they are presented via keys, values and each.

    攻撃キー集合を生成するための種が何かを知ることを不可能にするために、この種は プロセス開始時にランダムに初期化されます。 これは PERL_HASH_SEED 環境変数を使うことで上書きできます; "PERL_HASH_SEED" in perlrun を参照してください。 この環境変数はアイテムが実際にどのように保管されるかを制御するもので、 keys, values, each 経由でどのように表現されるかを 制御するものではありません。

    Hash Traversal Randomization

    (ハッシュ探索のランダム化)

    Independent of which seed is used in the hash function, keys, values, and each return items in a per-hash randomized order. Modifying a hash by insertion will change the iteration order of that hash. This behavior can be overridden by using hash_traversal_mask() from Hash::Util or by using the PERL_PERTURB_KEYS environment variable, see "PERL_PERTURB_KEYS" in perlrun. Note that this feature controls the "visible" order of the keys, and not the actual order they are stored in.

    ハッシュ関数でどの種が使われるかとは独立に、keys, values, each は ハッシュ毎にランダム化された順序で要素を返します。 挿入によってハッシュが変更されると、そのハッシュの反復順が変わります。 この振る舞いは、Hash::Utilhash_traversal_mask() を使うか、 PERL_PERTURB_KEYS 環境変数を使うことで上書きできます; "PERL_PERTURB_KEYS" in perlrun を参照してください。 この機能は keys の「見える」順序を制御するもので、実際に保管される順序を 制御するものではありません。

    Bucket Order Perturbance

    (バケツ順の撹乱)

    When items collide into a given hash bucket the order they are stored in the chain is no longer predictable in Perl 5.18. This has the intention to make it harder to observe a collision. This behavior can be overridden by using the PERL_PERTURB_KEYS environment variable, see "PERL_PERTURB_KEYS" in perlrun.

    あるハッシュバケツで要素が衝突したとき、Perl 5.18 ではチェーンに保管される順番は もはや予測できなくなりました。 これは、衝突を観測するのをより困難にする意図があります。 この振る舞いは PERL_PERTURB_KEYS 環境変数を使うことで上書きできます; "PERL_PERTURB_KEYS" in perlrun を参照してください。

    New Default Hash Function

    (新しいデフォルトハッシュ関数)

    The default hash function has been modified with the intention of making it harder to infer the hash seed.

    デフォルトハッシュ関数は、ハッシュの種の推論をより難しくするために 修正されました。

    Alternative Hash Functions

    (代替ハッシュ関数)

    The source code includes multiple hash algorithms to choose from. While we believe that the default perl hash is robust to attack, we have included the hash function Siphash as a fall-back option. At the time of release of Perl 5.18.0 Siphash is believed to be of cryptographic strength. This is not the default as it is much slower than the default hash.

    ソースコードには選択できる複数のハッシュアルゴリズムが含まれています。 デフォルトの perl ハッシュは攻撃に頑強であると信じていますが、 フォールバックオプションとして Siphash ハッシュ関数も含めています。 Perl 5.18.0 のリリースの時点で、Siphash は暗号学的強度を持つと 信じられています。 これはデフォルトのハッシュよりもはるかに遅いので、デフォルトではありません。

    Without compiling a special Perl, there is no way to get the exact same behavior of any versions prior to Perl 5.18.0. The closest one can get is by setting PERL_PERTURB_KEYS to 0 and setting the PERL_HASH_SEED to a known value. We do not advise those settings for production use due to the above security considerations.

    特別な Perl をコンパイルしない限り、Perl 5.18.0 より前のバージョンと正確に 同じ振る舞いにする方法はありません。 最も近いのは、PERL_PERTURB_KEYS に 0 を設定し、PERL_HASH_SEED に既知の値を 設定することです。 上述のセキュリティ上の問題のため、製品にはこの設定をしないことを勧めます。

    Perl has never guaranteed any ordering of the hash keys, and the ordering has already changed several times during the lifetime of Perl 5. Also, the ordering of hash keys has always been, and continues to be, affected by the insertion order and the history of changes made to the hash over its lifetime.

    Perl はハッシュキーの順序について何の保障もありません し、Perl 5 の 間でも既に何度か変更されています。 また、ハッシュキーの順序は、今までもこれからも、挿入順と、ハッシュに対して 行われた変更の歴史の影響を受けます。

    Also note that while the order of the hash elements might be randomized, this "pseudo-ordering" should not be used for applications like shuffling a list randomly (use List::Util::shuffle() for that, see List::Util, a standard core module since Perl 5.8.0; or the CPAN module Algorithm::Numerical::Shuffle), or for generating permutations (use e.g. the CPAN modules Algorithm::Permute or Algorithm::FastPermute), or for any cryptographic applications.

    また、ハッシュ要素の順序はランダム化されますが、この「擬似整列」は 以下のことに 使うべきではありません: リストをランダムに シャッフルするようなアプリケーション (Perl 5.8.0 から標準モジュールと なっている List::UtilList::Util::shuffle() や、CPAN モジュールである Algorithm::Numerical::Shuffle を使ってください)、 順列の生成 (CPAN モジュールである Algorithm::PermuteAlgorithm::FastPermute を 使ってください)、あらゆる暗号アプリケーション。

    Tied hashes may have their own ordering and algorithmic complexity attacks.

    tie されたハッシュは独自の順序とアルゴリズム的複雑性攻撃があるかもしれません。

  • Regular expressions - Perl's regular expression engine is so called NFA (Non-deterministic Finite Automaton), which among other things means that it can rather easily consume large amounts of both time and space if the regular expression may match in several ways. Careful crafting of the regular expressions can help but quite often there really isn't much one can do (the book "Mastering Regular Expressions" is required reading, see perlfaq2). Running out of space manifests itself by Perl running out of memory.

    正規表現 - Perl の正規表現エンジンは NFA (Non-deterministic Finite Automaton: 非決定性有限オートマトン)と呼ばれ、これは他のものに比べて、もし正規表現が 複数の方法でマッチングする場合、かなり簡単に大量の時間と空間を 消費することを意味します。 正規表現を注意深く構築することは助けになりますが、かなりの場合これは 不十分です ("Mastering Regular Expressions" という本を読む必要があります; perlfaq2 を参照してください)。 空間の不足は Perl がメモリ不足になることで明らかになります。

  • Sorting - the quicksort algorithm used in Perls before 5.8.0 to implement the sort() function was very easy to trick into misbehaving so that it consumes a lot of time. Starting from Perl 5.8.0 a different sorting algorithm, mergesort, is used by default. Mergesort cannot misbehave on any input.

    ソート - 5.8.0 以前の Perl で sort() 関数を実装するために使われていた クイックソートアルゴリズムは、大量の時間を消費するような策略がとても 簡単でした。 Perl 5.8.0 から、異なったソートアルゴリズムであるマージソートが デフォルトで使われています。 マージソートは入力データによって影響を受けません。

See https://www.usenix.org/legacy/events/sec03/tech/full_papers/crosby/crosby.pdf for more information, and any computer science textbook on algorithmic complexity.

さらなる情報については https://www.usenix.org/legacy/events/sec03/tech/full_papers/crosby/crosby.pdf および、 アルゴリズム的複雑性に関する情報工学の教科書を参照してください。

sudo を使う

The popular tool sudo provides a controlled way for users to be able to run programs as other users. It sanitises the execution environment to some extent, and will avoid the shebang race condition. If you don't have the safe version of set-id scripts, then sudo may be a more convenient way of executing a script as another user than writing a C wrapper would be.

人気のあるツールである sudo は、 ユーザーが他のユーザーとしてプログラムを実行する制御された手段を 提供します。 これはある程度実行環境をサニタイズして、 シェバン競合条件 を回避します。 安全なバージョンの set-id スクリプトを持っていない場合、 sudo は、他のユーザーとしてスクリプトを実行するための、 C ラッパーを書くよりもより便利な手段になります。

However, sudo sets the real user or group ID to that of the target identity, not just the effective ID as set-id bits do. As a result, Perl can't detect that it is running under sudo, and so won't automatically take its own security precautions such as turning on taint mode. Where sudo configuration dictates exactly which command can be run, the approved command may include a -T option to perl to enable taint mode.

しかし、sudo はターゲットの身元として set-id ビットが行うような 単なる実効 ID ではなく、実ユーザー ID やグループ ID を設定します。 結果として、Perl はこれが sudo の基で実行されていることを検出できず、 汚染チェックモードを友好にすると行ったセキュリティ上の予防措置を 自動的に有効にしません。 sudo 設定が実行されるコマンドを正確に設定する部分では、 perl が汚染チェックモードを有効にするために、承認されたコマンドに -T オプションを含むことができます。

In general, it is necessary to evaluate the suitability of a script to run under sudo specifically with that kind of execution environment in mind. It is neither necessary nor sufficient for the same script to be suitable to run in a traditional set-id arrangement, though many of the issues overlap.

一般的に、sudo の基で実効するためのスクリプトの適合性を評価することは、 特に想定している実行環境では必要です。 同じスクリプトに対して伝統的な set-id 配置で実行できるようにすることは 必要でも十分でもありませんが、多くの問題は重なっています。

SEE ALSO

"ENVIRONMENT" in perlrun for its description of cleaning up environment variables.

"ENVIRONMENT" in perlrun には環境変数を洗浄する方法が記述されています。