Say we have a typical prepared statement query like so:
$db->query("SELECT * FROM users WHERE id = :id");
$db->bind(':id', "x ' OR 'x' = 'x");
$db->execute();
Question
What is the mechanism that works behind the scenes to ensure SQL injection is avoided?
Namely, I understand that SQL and Data have to be merged back at some point for data retrieval process to work. What is the mechanism of this merge, and which subsystem is responsible for the merge?
Program & Data Separation
I hear and it has been noted that the inherent separation between Program
and Data
remove the possibility of such and injection. This is not getting to me because I can write a program that simply joins SQL & Data back together.
To drive the point home, here's some code to illustrate this point.
//receive SQL statement and data *separately*
function setSQL($sql) {$this->sql = $sql;}
function setData($data) {$this->data = $data;}
function executeStatement()
{
//simplified code that shows that we can
//blindly replace named parameter with supplied
//data inside SQL and execute it
db_execute(str_replace(':id', $this->data, $this->sql));
}
Are we protected? Well, do we have a program? yes. Do we have the Data sent separately? yes... do we still have injection attack? yes....? did I miss something? The part I am missing is at the heart of the question.
Data has to be joined with the SQL or the Program somehow, and I seek to find how it is done at code/pseudocode level, and what subsystem is responsible for merging this data together.
I am looking for "Fill in this gap in my knowledge" type of answer, where the mechanism of joining data back is exposed enough to cover up this gap.
答案 0 :(得分:1)
您需要了解的是代码和数据之间的区别。
代码是您编写的程序,而数据是此程序正在使用的数据。他们从不干涉。
想象一下典型的PHP脚本,比如
echo "Hello ". $name;
无论$ name包含什么,此内容都不会更改您的程序。它将始终保持不变。即使$ name包含类似
的内容<?php unlink(__FILE__);
它不会造成伤害。因为它只是不被解释为程序的数据。因此,此代码将简单地回显到浏览器,并可在源代码中看到。
使用[native]预处理语句完全相同。
你有一个程序(一个SQL查询),你有一些数据。后者仅由程序使用但永远不能改变它。