Reputation: 595
How do you prevent a malicious user from changing URL or form data, specifically a record ID. For example:
http://example.com/deleteproduct.php?id=34
The user could change the ID value from 34 to say 69 and in doing so delete a record belonging to another customer. I guess the obvious protection is to validate the ID before performing the delete to make sure the user has access to that record but is there perhaps another approach that is consider better practice? The downside of validating the ID requires more database queries which would be great to avoid.
Upvotes: 3
Views: 98
Reputation: 5806
What you said is very dangerous.
In the first place you need to protect data and make it only available for the selected users. Please create or finetune your access list with roles and permissions.
In the second place, it's not a right approach to use internal id's public.
It's always good to hide your internal id's, because it makes your application more safe.
You have to access your data. The most simple idea is checking it in your query, like so:
DELETE FROM table WHERE id = 34 AND user_id = 1 // Delete only if id = 34 and user is 1
Do you understand the idea?
You can encode your id's by using existing algorithms. Decoding is only possible with your secret key. There are many solutions and packages.
Hashids is a small open-source library that generates short, unique, non-sequential ids from numbers. (http://hashids.org/php/)
Upvotes: 0
Reputation: 10975
I guess the obvious protection is to validate the ID before performing the delete to make sure the user has access to that record.
This is the only way to ensure that your user has access to delete these rows.
The downside of validating the ID requires more database queries which would be great to avoid.
Not necessarily. You can simply check when you're deleting to only delete rows that belong to your user.
For example, assuming your table structure looks similar to:
users
-----
id | username
1 | Dave
2 | John
products
-----
id | name | user_owner
1 | Milk | 1
2 | Cake | 2
So if Dave visited deleteproduct.php?id=2, the following query would execute:
DELETE FROM products WHERE id = 2 AND user_owner = 1;
It wouldn't delete anything, and $mysqli->affected_rows
would return zero.
When affected rows is zero it means that the product ID was invalid or the product didn't belong to the user, either way: you would display a message telling the user that the product id is invalid.
Upvotes: 1
Reputation: 5097
Do they have authorization to delete items? If so, does it matter? If it's per-record authorization... just check if they have authorization for the requested id. Long answer short: check if they're authorized and never trust user input.
Upvotes: 0