How to Prevent SQL Injection in Wordpress

How to prevent SQL Injection in Wordpress?

From the WordPress Codex on protecting queries against SQL Injection attacks:

<?php $sql = $wpdb->prepare( 'query' , value_parameter[, value_parameter ... ] ); ?>

If you scroll down a bit farther, there are examples.

You should also read the database validation docs for a more thorough overview of SQL escaping in WordPress.

Does WordPress escape data to prevent SQL injections when using the Settings API?

Yes, when you're using the WP API (not just for settings, but the other functions too, like update_post_meta, wp_insert_post etc), WP will make sure that data is properly escaped before it is sent to the database.

The few exceptions will state explicitly that you can input SQL (e.g. the posts_orderby filter).

Unless you have unsafe characters (single quotes!) in your data, you won't see a change before and after escaping. Note that the sanitize_* functions don't deal with SQL injections, but try to clean up the content.

sql injection attack on wordpress

Wordpress does support prepared statements (also known as parameterized queries), using $wpdb->prepare().

global $wpdb;

// Add record
if(isset($_POST['submit'])){
$name = $_POST['txt_name'];
$uname = $_POST['txt_uname'];
$email = $_POST['txt_email'];
$tablename = $wpdb->prefix."myplugin";

if($name != '' && $uname != '' && $email != ''){
$check_data = $wpdb->get_results( $wpdb->prepare(
"SELECT * FROM {$tablename} WHERE username = %s ;"
, [$uname]
));
if(count($check_data) == 0){
$insert_sql = $wpdb->prepare(
"INSERT INTO {$tablename}(name,username,email) values(%s, %s, %s) ;"
, [$name, $uname, $email]
);
$wpdb->query($insert_sql);
echo "Save sucessfully.";
}
}
}

Two things to note:

  • All parameters in this case were strings and therefore were replaced by %s, but you can also use %d for integers and %f for float, just as in PHP sprintf().
  • You do not need to add quotes around the string placeholders (%s). The $wpdb->prepare() method takes care of that.

How to prevent SQL Injection for Input Fields?

It will be tag striped only this time (setting value to HTML input field -- assuming this is done server-side when generating HTML content). You have to do same thing when accessing database with parameters.

Does using the WordPress get_results() database function prevent sql injection

Ok so as tadman explained the get_results does not prevent the sql injection attack.

the prepare function needs to be used.

I have re written the above code to prevent sql injection:

global $wpdb;
$offset = (isset($_POST["moreSearchResults"])) ? $_POST["searchOffset"] : 0;

$querySearchVals = "
SELECT DISTINCT post_title, ID
FROM {$wpdb->prefix}posts
WHERE (";

$sVals = array();
$sVals = explode(" ", $searchVal);

$lastIndex = intval(count($sVals)) - 1;
$orderByCaseVals = "";
for($i = 0; $i<count($sVals);$i++)
{
$queryPrep = $wpdb->prepare(" post_title LIKE '%%%s%%' ", $wpdb->esc_like( $sVals[$i] ));
$querySearchVals .= $queryPrep;
if($i != $lastIndex)
$querySearchVals .= " OR ";

$queryPrep = $wpdb->prepare(" WHEN post_title LIKE '%%%s%%' THEN ($i + 2) ", $wpdb->esc_like( $sVals[$i] ));
$orderByCaseVals .= $queryPrep;
}

$querySearchVals .= ")
AND {$wpdb->prefix}posts.post_type = 'post'
AND post_status = 'publish'
ORDER BY CASE";

$queryPrep = $wpdb->prepare(" WHEN post_title LIKE '%%%s%%' THEN 1 ", $wpdb->esc_like( $searchVal ));
$querySearchVals .= $queryPrep;
$querySearchVals .= "
$orderByCaseVals
END
";

$queryPrep = $wpdb->prepare(" LIMIT %d, 12", $offset);
$querySearchVals .= $queryPrep . ";";

How can I prevent SQL injection in PHP?

The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don't fully understand the details, you should always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.

You basically have two options to achieve this:

  1. Using PDO (for any supported database driver):

    $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
    $stmt->execute([ 'name' => $name ]);

    foreach ($stmt as $row) {
    // Do something with $row
    }
  2. Using MySQLi (for MySQL):

    $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
    $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'
    $stmt->execute();

    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
    // Do something with $row
    }

If you're connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, pg_prepare() and pg_execute() for PostgreSQL). PDO is the universal option.



Correctly setting up the connection

PDO

Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4', 'user', 'password');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

In the above example, the error mode isn't strictly necessary, but it is advised to add it. This way PDO will inform you of all MySQL errors by means of throwing the PDOException.

What is mandatory, however, is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).

Although you can set the charset in the options of the constructor, it's important to note that 'older' versions of PHP (before 5.3.6) silently ignored the charset parameter in the DSN.

Mysqli

For mysqli we have to follow the same routine:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // error reporting
$dbConnection = new mysqli('127.0.0.1', 'username', 'password', 'test');
$dbConnection->set_charset('utf8mb4'); // charset


Explanation

The SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute, the prepared statement is combined with the parameter values you specify.

The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn't intend.

Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains 'Sarah'; DELETE FROM employees the result would simply be a search for the string "'Sarah'; DELETE FROM employees", and you will not end up with an empty table.

Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.

Oh, and since you asked about how to do it for an insert, here's an example (using PDO):

$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement->execute([ 'column' => $unsafeValue ]);


Can prepared statements be used for dynamic queries?

While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.

For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.

// Value whitelist
// $dir can only be 'DESC', otherwise it will be 'ASC'
if (empty($dir) || $dir !== 'DESC') {
$dir = 'ASC';
}

Is this correct way to prevent SQL injection?

In your example, I see that you are using Wordpress functions so going that route you should consult the documentation for what you are doing, specifically prepare()
https://developer.wordpress.org/reference/classes/wpdb/prepare/

Which states "Prepares a SQL query for safe execution..."

So essentially yes you are protecting your query albeit by trusting that Wordpress is doing it correctly internally.

Is this code protected for SQL injection?

I take it for granted that $wpdb is from the WordPress project.

Then as explained by the documentation, the very purpose of these placeholders is to prevent SQL injections.

Hence you can consider your code safe against SQL injections.

Personally I like to cast my values in the right type as soon as possible, now maybe this is the purpose of filter_input, which I don't know about.

$asd = (int) filter_input(INPUT_POST, 'TypeM', FILTER_SANITIZE_NUMBER_INT);
$zxc = (int) filter_input(INPUT_POST, 'mailFor', FILTER_SANITIZE_NUMBER_INT);


Related Topics



Leave a reply



Submit