PDO bindValue 不逃逸

PDO bindValue does not escape

发生了一些奇怪的事情,因为 PDO 应该逃避任何 XSS

这是我的 PDO Class

<?php
class Database {
    private $host = 'localhost';
    private $user = 'root';
    private $pass = '';
    private $dbname = '';

    private static $_instance;

    private $dbh;
    private $stmt;
    private $error;

    private function __construct() {
        if($this->dbh != null)
            return $this->dbh;

        $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
        $options = array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING, //ERRMODE_SILENT
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
        );
        try {
            $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
        }
        catch(PDOException $e) {
            echo '__construct -> ';
            var_dump($e->getMessage());
        }
    }
    private function __clone(){
    }

    public static function getInstance() {
        if(!self::$_instance) {
            self::$_instance = new Database();
        }
        return self::$_instance;
    }

    public function query($query) {
        try {
            $this->stmt = $this->dbh->prepare($query);
        }
        catch(PDOException $e) {
            echo 'query -> ';
            var_dump($e->getMessage());
        }
    }

    public function bindValue($param, $value, $type) {
        $this->stmt->bindValue($param, $value, $type);
    }
    public function execute() {
        try {
            return $this->stmt->execute();
        }
        catch(PDOException $e) {
            echo 'execute -> ';
            var_dump($e->getMessage());
        }
    }
}
?>

...这是一个将评论插入数据库的处理程序

        $this->db->query("INSERT INTO `comments` (`user_id`, `post_id`, `text`, `added`) VALUES (:user_id, :post_id, :text, :added)");
        $this->db->bindValue(':user_id', $user_id, PDO::PARAM_INT);
        $this->db->bindValue(':post_id', $recipe_id, PDO::PARAM_INT);
        $this->db->bindValue(':text', $_POST['text'], PDO::PARAM_STR);
        $this->db->bindValue(':added', time(), PDO::PARAM_INT);
        $this->db->execute();

并且输入没有被 "">'>''>"> alert(1);"转义";"

...那么 PDO 有什么问题吗??

你混淆了不同类型的安全漏洞,它们具有相同的基本原理,但发生在不同的地方:

  • SQL 当攻击者诱骗您的代码构建对您的数据有副作用的 SQL 字符串时,就会发生注入。例如,通过操作动态 WHERE 子句来执行 DROP TABLE 语句。
  • HTML 当攻击者欺骗您的代码构建 HTML 时会发生注入,其中包含您不想要的其他元素,可能包括在用户浏览器上执行的脚本。
  • 当您动态构建 JS 本身时,JS 注入再次遵循类似的模式。

针对所有这些问题的缓解措施是相似的 - 要么将数据与代码隔离开来,使其永远不会被执行,要么转义 "break out of" 预期标记的特殊字符。但是没有一组转义符可以使字符串在所有上下文中都是安全的,您必须以正确的方式为您在其中使用它的上下文准备它。

因此,在您的情况下,在数据库层中使用参数化查询可防止 SQL 注入,但它与数据将如何包含在 HTML、JS 或什至中无关未来 SQL 调用 - 输出的文本与输入的文本相同。