Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cballou/3055102 to your computer and use it in GitHub Desktop.
Save cballou/3055102 to your computer and use it in GitHub Desktop.
PHP MySQL LIKE Query DoS Attack Example
<?php
// client side: assume user has maliciously used the following values in a form search input field and submitted
$field = '<input type="text" name="query" value="%slow_your_db" />';
// server-side: assume retrieval of form search input value
$search_term = !empty($_GET['query']) ? $_GET['query'] : NULL;
// try to escape the input before querying, but we fail to escape the qualifier
// and it remains "%slow_your_db"
$search_term = mysql_real_escape_string($search_term);
// perform a query which will skip all indexing you may have, slowing
// your queries to a hault on a large database (DoS attack)
mysql_query("SELECT * FROM my_table WHERE query LIKE '{$search_term}%'");
<?php
/**
* To fix the flaw with LIKE queries and mysql_real_escape_string, we must
* escape the special qualifiers % and _ ourselves. We'll use the previous
* attack example to show the fix.
*/
// client side: assume user has maliciously used the following values in a form search input field and submitted
$field = '<input type="text" name="query" value="%slow_your_db" />';
// server-side: assume retrieval of form search input value
$search_term = !empty($_GET['query']) ? $_GET['query'] : NULL;
// escape the input before querying, term remains "%slow_your_db"
$search_term = mysql_real_escape_string($search_term);
// additionally add slashes to escape the qualifiers % and _
$search_term = addcslashes($search_term, "%_");
// perform the safe query with escaped % and _ quantifiers
mysql_query("SELECT * FROM my_table WHERE query LIKE '{$search_term}%'");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment