PHPマニュアル/PEARマニュアル | ユーザフォーラムで議論/質問 | マニュアル検索 | ハイライト | ハイライトオフ | ポータル | php spot

Script Injection Attacks | JavaScript入門&応用&リファレンスなら「JavaScriptist」

  

Script Injection Attacks

If you are using JavaScript, make sure that any variables that cross the PHP- to-JavaScript boundry are passed in the scope field of MongoDB\BSON\Javascript, not interpolated into the JavaScript string. This can come up when using $where clauses in queries, mapReduce and group commands, and any other time you may pass JavaScript into the database.

For example, suppose we have some JavaScript to greet a user in the database logs. We could do:

<?php
$m 
= new MongoDB\Driver\Manager;

// Don't do this!!!
$username $_GET['field']; 

$cmd = new \MongoDB\Driver\Command( [
    
'eval' => "print('Hello, $username!');"
] );

$r $m->executeCommand'dramio'$cmd );
?>

However, what if a malicious user passes in some JavaScript?

<?php
$m 
= new MongoDB\Driver\Manager;

// Don't do this!!!
$username $_GET['field']; 
// $username is set to "'); db.users.drop(); print('"

$cmd = new \MongoDB\Driver\Command( [
    
'eval' => "print('Hello, $username!');"
] );

$r $m->executeCommand'dramio'$cmd );
?>

Now MongoDB executes the JavaScript string "print('Hello, '); db.users.drop(); print('!');". This attack is easy to avoid: use args to pass variables from PHP to JavaScript:

<?php
$m 
= new MongoDB\Driver\Manager;

$_GET['field'] = 'derick';
$args = [ $_GET['field'] ];

$cmd = new \MongoDB\Driver\Command( [
    
'eval' => "function greet(username) { print('Hello, ' + username + '!'); }",
    
'args' => $args,
] );

$r $m->executeCommand'dramio'$cmd );
?>

This adds an argument to the JavaScript scope, which gets used as argument for the greet function. Now if someone tries to send malicious code, MongoDB will harmlessly print Hello, '); db.dropDatabase(); print('!.

Using arguments helps to prevent malicious input from being executed by the database. However, you must make sure that your code does not turn around and execute the input anyway! It is best to avoid executing any JavaScript on the server in the first place.

You are strongly recommended to stay clear of the » $where clause with queries, as it impacts performance significantly. Where possible, use either normal query operators, or the » Aggregation Framework.

As alternative to » MapReduce, which uses JavaScript, consider using the » Aggregation Framework. Unlike Map/Reduce, it uses an idiomatic language to construct queries, without having to write, and use, the slower JavaScript approach that Map/Reduce requires.

The » eval command has been deprecated since MongoDB 3.0, and should also be avoided.


忘却曲線を使ってこの知識を確実に記憶に残す

フォーラムで「Script Injection Attacks」について話す
各種マニュアル: PHPマニュアル | PEARマニュアル | Smarty(英語)マニュアル | PHP-GTKマニュアル | Script Injection Attacks」をGoogle検索
copyright © 1997-2024 PHP ドキュメント作成グループ(ライセンス). provided by php spot. マニュアル: