Issue
I'm trying to access entries from the database with variable column names.
I have this table containing vehicles that can belong to one of three categories (car, bike, truck):
| vehicle | car | bike | truck |
|---|---|---|---|
| Car 1 | x | ||
| Car 2 | x | ||
| Bike 1 | x | ||
| Truck 1 | x |
With OOP and PDO, I'm trying to access the vehicles that belong to a category. Like so:
User-input:
URL: ?category=cars
All of the following is inside a class called "Vehicles".
Constructor of class Vehicles:
public function __construct() {
$this->category = $_GET["category"] ?? "cars";
switch ($this->category) {
default: //Avoiding db-error messages by setting default category to "car"
case "cars":
$this->category = "car";
break;
case "bikes":
$this->category = "bike";
break;
case "trucks":
$this->category = "truck";
break;
}
I then access the entries from the db that correspond to the category:
public function getVehiclesFromCategory() {
$sql = "SELECT * FROM vehicles WHERE $this->category IS NOT NULL";
$stmt = $this->connect()->query($sql);
while ($row = $stmt->fetch()) {
$row["vehicle"]."<br>";
}
}
I then create the object to get the output from the chosen category:
$Vehicles = new Vehicle();
$Vehicles->getVehiclesFromCategory();
I'm basically relating the user input to a predefined value. Is this sufficient to avoid SQL-injections?
I do realize I'm using a bad db-design, as the user is not supposed to get any hints about the names of the db-columns. I am also aware that I should avoid db-related error messages that can be useful for hackers (which is why I use the default-switch) - but I need a quick fix for now with the current db-model.
Solution
It looks as though this question ("is it safe?") has been answered already. However, the how and why seem to be a bit up in the air so here's some further information...
Why it's safe
The ONE thing that is saving you from SQL injection in this case is the fact that you set a default case in your switch statement. Without that one word you would be wide open to SQL injections. Let's play it out:
Valid input example
- User input
bikes - Your code sets the
categoryproperty tobikes - Your
switchruns andbikesis found so it returnsbikeas thecategory
Invalid input example
- User input
hairStraightener - Your code sets the
categoryproperty tohairStraightener - Your
switchruns andhairStraightenerisn't found so it returnscaras thecategory; which is thedefaultcase
Invalid case without default
- User input
hairStraightener - Your code sets the
categoryproperty tohairStraightener - Your
switchruns andhairStraightenerisn't found socategoryisn't updated and remains ashairStraightener
Now, imagine a user had put something like:
1; DROP TABLE vehicles; --
// OR...
1; UPDATE TABLE vehicles SET price = 1; --
Now you've lost a load of data or everything in your shop costs £1 (bargain!)
Improving things
You're on the right lines: if you need to input a variable directly into the SQL query you need to whitelist acceptable items and only use those. There are different ways of doing it...
- As you have with a
switch/case - With a
match(PHP 8+) - With an
arrayand lookup - By checking variables against the DB schema
Switch
The biggest problem I see with the way you've done is that if someone comes along and looks at your code they may well see that you've effectively set a default before the switch and therefore remove the default case; which would leave you open to SQL injection.
So you should update your code accordingly:
- Don't ever set the user input to the
categoryproperty - Set the default property of
categoryon declaration
E.g.
public $category = "car";
public function __construct()
{
switch ($_GET["category"] ?? null) {
case "cars":
$this->category = "car";
break;
case "bikes":
$this->category = "bike";
break;
case "trucks":
$this->category = "truck";
break;
}
}
Match
As commented by @Dharman if your server is running PHP 8+ you can use match. Which, in this case, you can think of as a type sensitive switch statement:
Note: match will throw an error if you don't supply the default case; or rather if a value is supplied that can't be matched!
function __construct()
{
$this->category = match($_GET["category"] ?? "cars") {
"cars" => "car",
"bikes" => "bike",
"trucks" => "truck",
default => "car"
};
}
Array lookup
private $allowedFields = [
"cars" => "car",
"bikes" => "bike",
];
public function __construct()
{
$this->category = $this->allowedFields[$_GET["category"] ?? "cars"];
}
DB Schema
Finally, you could auto-generate the safe fields by checking the DB schema (something like DESCRIBE vehicles) and checking the input matches one of the column names. In your case though this probably isn't the best idea because you could still have someone input a real field which wasn't intended. Maybe it wouldn't be catastrophic, but it definitely isn't intended!
Fixing things long term
As others have said this is a largely flawed DB design. Presumably looking something like:
vehicles
id
make
model
price
...
bike
car
van
truck
...
When it should look more like:
vehicle < vehicleType > type
id id id
make vehicle_id name
model type_id
price
...
You then update your SQL to look something like:
SELECT
vehicle.id, vehicle.make, vehicle.model, vehicle.price,
type.name
FROM vehicle
JOIN vehicleType on vehicle.id = vehicleType.vehicle_id
JOIN type on vehcileType.type_id = type.id
WHERE type.name = ?
Now you can used a prepared statement to be fully safe
N.B.
It may seem like creating two tables and updating the existing one into them is a time consuming process. But in reality it won't take that long. The process:
- Create the tables with appropriate datatypes, properties, etc.
DESCRIBEthevehiclestable and extract the different types (car,bike, etc.)- Insert the types into the table
type- This can all be done automatically with a few lines of PHP, for example
- Write a short script to loop through each line of your vehicles table and
insertrecords into thevechicleTypetable based on what columns arenot null - Check your data (backup as required)
- Remove the no longer needed columns from
vehicles
Answered By - Steven Answer Checked By - Terry (sql.easybugfix Volunteer)
Post a Comment
Post a Comment