【问题标题】:is this dynamic (column & table) PHP select query safe?这个动态(列和表)PHP 选择查询安全吗?
【发布时间】:2012-10-14 17:38:50
【问题描述】:

不能使用 PDO ->bindParam() 绑定表和列名称,但我相信不止一个人愿意这样做。这有点晚了,但我早点写了这个,到目前为止它有效。我是 php 的新手,想知道您的想法以及它是否安全。

$type = "defaultTableName";
$sortBy = "defaultColumnName";
$orderBy = "ASC";

//whitelisting unsafe input
if(isset($_GET['orderBy'])&&($_GET['orderBy']=="ASC"||$_GET['orderBy']=="DESC"))
    $orderBy = $_GET['orderBy'];
$tableNames = array("defaultTableName", "tableName2", "tableName3");
$unsafeType= $_GET['type']; <---unsafe input
$unsafeSortBy = $_GET['sortBy']; <---unsafe input

try {
    $pdo = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    //if input is not valid this will use default table to render a table in html.
$stmt = $pdo->prepare("DESCRIBE $type");
$stmt->execute();
$table_fields = $stmt->fetchAll(PDO::FETCH_COLUMN);

 //Whitelisting user input against table names (will require table names updates)
    if (in_array($unsafeType, $tableNames)) {
    $stmt = $pdo->prepare("DESCRIBE $unsafeType");
    $stmt->execute();
    $table_fields = $stmt->fetchAll(PDO::FETCH_COLUMN);

 ///Whitelisting the column name to sort by against the description of the table.
        if (in_array($unsafeSortBy, $table_fields)) {
        $stmt = $pdo->prepare("SELECT * FROM $unsafeType ORDER BY $unsafeSortBy $orderBy");
    }
    else    {
        $stmt = $pdo->prepare("SELECT * FROM $type ORDER BY $sortBy $orderBy");
    }
} else {
    $stmt = $pdo->prepare("SELECT * FROM $type ORDER BY $sortBy $orderBy");
}
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
 }

我看到的唯一问题是您在更改表格时需要添加/删除/更改表格名称数组。我有一个中小型应用程序,不是很复杂。

注意:我在 stackoverflow 中的编辑也很糟糕,所以如果你知道一种使它更好的方法,请继续编辑或让我知道。

【问题讨论】:

    标签: php web pdo sql-injection


    【解决方案1】:

    没有。这不安全。您直接将用户提交的数据放入查询字符串中。 任何时候您都容易受到 sql 注入攻击。

    但是,由于您不能对这些特定值使用占位符,因此您必须自己使用 pdo::quote 转义数据,例如

    $safeType = $pdo->quote($_GET['type']);
    

    仅仅因为它是一个表名或一个 sort-by 子句值并不意味着它不能被注入。任何进入未通过占位符引用/转义或插入的字符串的用户数据都是攻击向量。

    【讨论】:

    • 我终于明白了……在我验证它之前。可以转义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    相关资源
    最近更新 更多