【问题标题】:Security issues in PHP/SqlPHP/Sql 中的安全问题
【发布时间】:2022-07-30 18:45:56
【问题描述】:

我是初学者。我写了这篇文章,并被告知我的 find() 方法存在安全漏洞。我认为我的 queryType 方法的 if else 阻止了 Sql 注入尝试。

    public function queryType(string $sql, array $attributes = null)
    {
        ## instance of Database singleton
        $this->Database = Database::getInstance();

        if($attributes !== null) {
            ## if attr, prepared request
            $query = $this->Database->prepare($sql);
            $query->execute($attributes);
            return $query;
        }else{
            ## else, simple request
            return $this->Database->query($sql);
        }
    }

    ## SECURITY ISSUE /!\ ?? queryType if/else doesn't prevent ??

    public function find(int $id)
    {
        return $this->queryType("SELECT * FROM {$this->table} WHERE id = $id")->fetch();
    }

我该如何解决?

【问题讨论】:

  • 您的 queryType 方法是,这允许在其中执行原始查询,并且您的 find 不使用占位符,尽管有类型提示,但它没有被正确使用。并小心{$this->table},如果这是用户提供的,您需要将其与您的表一起列入白名单或仅定义它

标签: php sql sql-injection


【解决方案1】:

代码仅在您实际使用时才提供安全性。因为您没有传递任何参数,所以显示的查询将属于“else, simple request”的情况,因此queryType supports 参数这一事实是无关紧要的。这就像在您的门上安装一个沉重的铁螺栓,但永远不要将其滑入到位 - 它不会阻止任何人。

在这种情况下,$id 保证是一个 int,所以风险很小,但你应该养成always using parameters 的习惯:$this->queryType("SELECT * FROM {$this->table} WHERE id = ?", [$id])

但是,您还有另一个动态部分,can't be a parameter:$this->table 如果用户有任何方法可以选择该值,那将是一个巨大的安全漏洞。如果这是针对某种“ORM”,其中每个表都有一个类,那么使用类常量可能是明智的(例如$tableName = static::TABLE_NAME;);这样,子类可以定义一个值,但它永远不会在运行时计算,因此您不会意外地将用户控制的值放入其中。

【讨论】:

  • 我在其他地方写过,框架可以防止 SQL 注入,就像牙刷可以防止蛀牙一样。
【解决方案2】:

感谢您的提示。我想知道修改我的 queryType() 方法的 if/else 是否是一个很好的解决方案。喜欢:

    public function queryType(string $sql, array $attributes = null)
    {

        $this->Database = Database::getInstance();

            $query = $this->Database->prepare($sql);
            $query->execute($attributes);
            return $query;
    }

还是问题出在方法参数默认值 on null (string $sql, array $attributes = null) 上?

【讨论】:

    猜你喜欢
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多