Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is preventing XSS and SQL Injection as easy as does this

Question: Is preventing XSS (cross-site scripting) as simple using strip_tags on any saved input fields and running htmlspecialchars on any displayed output ... and preventing SQL Injection by using PHP PDO prepared statements?

Here's an example:

// INPUT: Input a persons favorite color and save to database
// this should prevent SQL injection ( by using prepared statement)
// and help prevent XSS  (by using strip_tags)
$sql = 'INSERT INTO TABLE favorite (person_name, color) VALUES (?,?)';
$sth = $conn->prepare($sql);
$sth->execute(array(strip_tags($_POST['person_name']), strip_tags($_POST['color'])));


// OUTPUT: Output a persons favorite color from the database
// this should prevent XSS (by using htmlspecialchars) when displaying
$sql = 'SELECT color FROM favorite WHERE person_name = ?';
$sth = $conn->prepare($sql);
$sth->execute(array(strip_tags($_POST['person_name'])));
$sth->setFetchMode(PDO::FETCH_BOTH);
while($color = $sth->fetch()){
  echo htmlspecialchars($color, ENT_QUOTES, 'UTF-8');
}
like image 293
TimTim Avatar asked Jan 03 '10 21:01

TimTim


People also ask

Is it easy to prevent SQL injection?

Preventing SQL Injection vulnerabilities is not easy. Specific prevention techniques depend on the subtype of SQLi vulnerability, on the SQL database engine, and on the programming language. However, there are certain general strategic principles that you should follow to keep your web application safe.

Is SQL injection the same as XSS?

What is the difference between XSS and SQL injection? XSS is a client-side vulnerability that targets other application users, while SQL injection is a server-side vulnerability that targets the application's database.

What is the best defense against SQL injection?

You should always use parameterized statements where available, they are your number one protection against SQL injection. You can see more examples of parameterized statements in various languages in the code samples below.


2 Answers

It's even more simple. Just htmlspecialchars() (with quote style and character set) on user-controlled input is enough. The strip_tags() is only useful if you already want to sanitize data prior to processing/save in database, which is often not used in real world. HTML code doesn't harm in PHP source, but PHP code may do so if you use eval() on non-sanitized user-controlled input or that kind of evil stuff.

This however doesn't save you from SQL injections, but that's another story.

Update: to get clean user input from the request to avoid magic quotes in user-controlled input, you can use the following function:

function get_string($array, $index, $default = null) {
    if (isset($array[$index]) && strlen($value = trim($array[$index])) > 0) {
         return get_magic_quotes_gpc() ?  stripslashes($value) : $value;
    } else {
         return $default;
    }
}

which can be used as:

$username = get_string($_POST, "username");
$password = get_string($_POST, "password");

(you can do simliar for get_number, get_boolean, get_array, etc)

To prepare the SQL query to avoid SQL injections, do:

$sql = sprintf(
    "SELECT id FROM user WHERE username = '%s' AND password = MD5('%s')",
        mysql_real_escape_string($user),
        mysql_real_escape_string($password)
); 

To display user-controlled input to avoid XSS, do:

echo htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
like image 64
BalusC Avatar answered Oct 04 '22 12:10

BalusC


It depends on where and how you want to use the user data. You need to know the context you want to insert your data in and the meta characters of that context.

If you just want to allow the user to put text up on your website, htmlspecialchars suffices to escape the HTML meta characters. But if you want to allow certain HTML or want to embed user data in existing HTML elements (like a URL into a A/IMG element), htmlspecialchars is not enough as you’re not in the HTML context anymore but in the URL context.

So entering <script>alert("xss")</script> into a image URL field will yield:

<img src="&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt" />

But entering javascript:alert("xss") will succeed:

<img src="javascript:alert(&quot;xss&quot;)" />

Here you should take a look at the fabulous XSS (Cross Site Scripting) Cheat Sheet to see what contexts your user data can be injected in.

like image 22
Gumbo Avatar answered Oct 04 '22 10:10

Gumbo