由于 PHP 的文件系統操作是基于 C 語言的函數的,所以它可能會以您意想不到的方式處理 Null 字符。 Null字符在 C 語言中用于標識字符串結束,一個完整的字符串是從其開頭到遇見 Null 字符為止。 以下代碼演示了類似的攻擊: Example #1 會被 Null 字符問題攻擊的代碼 復制代碼 代碼如下: ?php $file = $_GET['file']; // "../../etc/passwd/0" if (file_exists('/home/wwwrun/'.$file.'.php')) { // file_exists will return true as the file /home/wwwrun/../../etc/passwd exists include '/home/wwwrun/'.$file.'.php'; // the file /etc/passwd will be included } ?
因此,任何用于操作文件系統的字符串(譯注:特別是程序外部輸入的字符串)都必須經過適當的檢查。以下是上述例子的改進版本: Example #2 驗證輸入的正確做法 復制代碼 代碼如下: ?php $file = $_GET['file']; // 對字符串進行白名單檢查 switch ($file) { case 'main': case 'foo': case 'bar': include '/home/wwwrun/include/'.$file.'.php'; break; default: include '/home/wwwrun/include/main.php'; } ?