1

正規表現を使用して文字列をクリーンアップする関数があるとしましょう。

function RegExCleaner($var)
{
    return preg_replace('Regular expression', '', $var)
}

関数の外観と動作はそれほど重要ではありません。簡単な例です。

この関数を使用してユーザー入力または一部の値を1回クリーンアップしてから、値'server-side'で作業する場合、1回クリーンアップするだけで十分ですか、それともマルチレイヤーで実行できますか?したがって、一連の関数で変数を使用する場合、すべての関数で変数をクリーンアップしますか?これは実際にセキュリティを向上させますか、それとも不要なワークロードを追加するだけですか?

4

2 に答える 2

1

There are basically two ways of handling user input:

  1. Sanitizing: This removes unwanted stuff from the input. The unwanted stuff may be various tags, invalidly formatted characters, certain words or letters, etc. This is almost always something you should do. The only exception is if the input is a simple value such as an integer or a boolean value, which can be handled directly with validating.

  2. Validating: This makes sure that the input is indeed what you expect it to be. Is it a number, boolean value, text blocks, etc.? This is not so much about security as it is about actually getting the right kind of data for your program to be able to function.

For both of these points there is a PHP extension called Filter. It was made with this stuff in mind.

For sanitizing input you could do something like this:

$name     = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$age      = filter_input(INPUT_POST, 'age', FILTER_SANITIZE_NUMBER_INT);
$email    = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$password = filter_input(INPUT_POST, 'password', FILTER_UNSAFE_RAW);

And for validating:

if (preg_match('/[\w\d]{4,20}/', $name) === 0) {
    die('Invalid name!');
}
if ( ! ctype_digit($age) || ($age < 13)) {
    die('Invalid age or too young!');
}
if ( ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
    die('Invalid email address!');
}
if (strlen($password) < 10) {
    die('Password is too short!');
}

One very important thing to remember is that there is no magic pill. User input cannot just be washed in bleach as it comes in, and then be said to be safe. You need to know what the user input should be and then treat it accordingly. If it is not what you know it should be then hit the brakes immediately and throw it back at the user.

于 2012-12-24T15:56:44.850 に答える
1

これが私見で起こる場所を1つ持つ方が良いです。システムに入る途中ですべてをクリーンアップすれば、後で心配する必要はありません。また、多くの場所でサニタイズを行うと、どこでサニタイズを行っているかを追跡するのが混乱する可能性があります。すべてのレベルでサニタイズすることはロジックを損なうことはありませんが、この理由でメンテナンスが難しくなる可能性があります。

入力をクリーンアップするための関数のライブラリをお勧めします。静的メソッドなどのクラスにラップされ、それらの関数の1つにすべてを渡すことをお勧めします。

于 2012-12-24T15:35:34.200 に答える