Here is an example of a vulnerable php code that is used for authentication:
Above script takes username
and password
directly from the POST request and passes it to the query directly.
We can use libraries such as mysql_real_escape_string()
to sanitize user input, rendering injected queries.
This function escapes characters such as '
and "
.
We can validated the input based on the data used to query to ensure it matched the expected form such as @email.com
.
Below is a vulnerable code:
port_code
parameter is being used in the query directly.
Since port_code
parameter can only consist of letters or spaces, we can restrict user input as such:
Above code used preg_match()
function to check if the input matched the given pattern or not.
User Privileges
We have to ensure that the user querying the database only has minimum permissions.
Superusers and users with administrative privileges should never be used with web applications.
Firewall
WAF could be used to detect malicious input and reject any HTTP requests containing them.
Parameterized Queries
Parameterized queries contain placeholders for the input data, which is then escaped and passed on by the driver: