Securing PHP data from various attacks - php

I am new to PHP security and trying to implement the solutions other than PDO.
I have read several articles here on stackoverflow and googled many articles.
I have tried to write my own code to secure the user input.
I would request the experts here to please have a look and guide me if I have left anything here or have i used anything unnecessary here.
Also I am missing CSRF prevention. Is there anything else other than random token generation? Can this be implemented using any functions?
extract($_POST);
$stuid = filter_input(INPUT_GET, 'stud_id', FILTER_SANITIZE_SPECIAL_CHARS); //php filter extension
$stuid = trim($stuid);
$stuid = strip_tags($stuid);
$stuid = iconv('UTF-8', 'UTF-8//IGNORE', $stuid); //remove invalid characters.
$stuid = htmlspecialchars($stuid, ENT_COMPAT, 'UTF-8'); // manual escaping
$stuid = mysql_real_escape_string($stuid);
$stuid = htmlspecialchars($stuid, ENT_COMPAT, 'UTF-8'); //Cross site scripting (XSS)
$email = filter_input(INPUT_POST, $email, FILTER_SANITIZE_EMAIL);
$pass=md5($pass);
Thanks in advance.

in a case where my user has submitted a piece of data for the database to store, then i need to be sure i have sanitized it and use a parametized query:
/* Prepare an insert statement */
$query = "INSERT INTO myTable (DangerousData, MoreDangerousData) VALUES (?, ?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param($val1, $val2);
// white listing is always the MOST secure since we control the data
switch ($_POST['DangerousData']) {
case 'Lamb': $val1 = 'Lamb'; break;
case 'Sheep': $val1 = 'Sheep'; break;
// so if they send something not allowed, we have a default
default: $val1 = 'WolfinsheepsClothing';
}
// otherwise, the parametization of the statement will
// clean the data properly and prevent any SQL injection
$val2 = $_POST['MoreDangerousData'];
/* Execute the statement */
$stmt->execute();
For the purposes of Email, you need to study examples on the internet of how to properly sanitize the input coming from the user for the purpose you wish to use it - most people use regular expressions for verifying the safety and validity of an email.
Stackoverflow can help you validate an email.
Stackoverflow can help sanitize user input, too.

Related

Question while reading Learning PHP, MySQL & JavaScript by Robin Nixon RE: Sanitizing Input PHP [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 years ago.
I'm currently reading and learning PHP from a book that offers this as the proper way to sanitize input from forms:
function mysql_entities_fix_string($connection, $string)
{
return htmlentities(mysql_fix_string($connection, $string));
}
function mysql_fix_string($connection, $string)
{
if (get_magic_quotes_gpc()) $string = stripslashes($string);
return $connection->real_escape_string($string);
}
Which is great, except I know that get_magic_quotes_gpc() is deprecated in the current version of PHP. From looking at a few different resources I learned that instead of using get_magic_quotes_gpc() I should just use an sql prepared statement. That confuses me though because I would presume that we still need to do some functional cleaning of the string.
Unless I'm wrong(it happens, I'm relatively new at this) this is a big no-no, regardless of the prepared statement:
$username = $_POST['username'];
$stmt = $conn->prepare("SELECT password FROM users WHERE username=?");
$stmt->bind_param("s", $username");
$stmt->execute();
...
but if that's the case, is this an acceptable sanitation process:
function get_post($conn, $var) {
return $conn->real_escape_string($_POST[$var]);
}
...
$username = get_post($conn, 'username');
$stmt = $conn->prepare("SELECT password FROM users WHERE username=?");
$stmt->bind_param("s", $username);
$stmt->execute();
...
or do I need to add some other escaping function on top of it?
Uh no. That sanitization code is garbage.
Your proposed sanitization process with PDO statements is fine. That is all you need.

PHP prepared statements clarification

Can you mix user input data with fixed data in a prepared statement security wise or does each query condition have to have a placeholder?
For example:
$code = htmlspecialchars($_GET['code']); // USER INPUT DATA
$status = 'A'; // FIXED
$stmt = $connect->prepare("SELECT s_id FROM events WHERE s_code = ? AND s_status = ?") or die(mysqli_error());
$stmt->bind_param('ss', $code, $status);
$stmt->execute();
$stmt->bind_result($reference);
Or is this also acceptable?
$code = htmlspecialchars($_GET['code']); // USER INPUT DATA
$stmt = $connect->prepare("SELECT s_id FROM events WHERE s_code = ? AND s_status = 'A'") or die(mysqli_error());
$stmt->bind_param('s', $code);
$stmt->execute();
$stmt->bind_result($reference);
Both approaches are acceptable. Obviously there's no security impact in binding a fixed value from your code, but it may have some performance benefits if various parts of your application (or even different applications) use different hard-coded values for that query.
To complement the answer provided by Mureinik, you should also focus on the user input a bit. Prepared statements are effective at preventing SQL injection attacks, but they are not a universal antidote against all types of attacks.
Judging by your example I would say you expect the $_GET['code'] to be an integer. As an extra layer of security you can (and should) sanitize and also validate the user input. Something along these lines:
// avoid accessing directly super-globals like $_GET, $_POST
// #see Sanitize filters: http://nl1.php.net/manual/en/filter.filters.sanitize.php
$code = filter_input(INPUT_GET, 'code', FILTER_SANITIZE_NUMBER_INT);
// #see Validate filters: http://nl1.php.net/manual/en/filter.filters.validate.php
$options = array(
'options' => array(
'min_range' => 1,
'max_range' => 1000000,
));
if (!filter_var($code, FILTER_VALIDATE_INT, $options)) {
echo 'Invalid code!';
}

Apostrophe issue when inserting into MySQL

I have a script where I submit some fields that get entered into a MySQL database when I submit it now it goes through successfully but never gets inserted into the database if one of the fields has an apostrophe. What can I modify to get this to work?
if ($_POST) {
$name = trim($_POST['your_name']);
$email = trim($_POST['your_email']);
$answers = $_POST['answers'];
$i = 0;
foreach ($answers as $a) {
if (trim($a))
$i++;
}
if ($name && $email && $i >= 40) {
$array = array();
$q = mysql_query("select * from fields");
while($f = mysql_fetch_array($q))
$array[$f['label']] = $answers[$f['ID']];
$array = serialize($array);
$time = time();
$ip = $_SERVER['REMOTE_ADDR'];
$token = md5($time);
$result = mysql_query("insert into data (submit_name, submit_email, submit_data, submit_confirm, submit_time, submit_ip, submit_token)
values ('$name', '$email', '$array', '0', '$time', '$ip', '$token')");
You need to escape characters with special meaning in MySQL in your data.
The quick and dirty way to improve your code would be to pass all your strings through mysql_real_escape_string before inserting them into your string of SQL.
The better approach would be to switch away from mysql_query to something that allows the use of bound parameters (preferably with prepared statements).
Use mysql_real_escape_string(), as this will both fix your apostrophe issue and at least partly help avoid SQL injection attacks. If you don't want to get your hands dirty with PHP's built-in PDO library, you might consider a Database Abstraction Layer (DBAL). ADODB is an example.

Is this vulnerable to SQL injection

I realize there are a lot of questions already about this. But my method isn't the same as theirs, so I wanted to know. I think I understand SQL, but I don't want to risk making a mistake in the future, so thanks for any help. (This is just a project I'm doing, not homework or anything important).
function checkLogin($username, $password) {
$username = strtolower($username);
connectToDatabase();
$result = mysql_query("SELECT * FROM `users` WHERE username='$username'");
$dbpassword = "";
while($row = mysql_fetch_array($result))
{
$rowuser = $row['username'];
if($username != $row['username']) continue;
$dbpassword = $row['password'];
}
if($dbpassword == "") {
return false;
}
$genpass = generatePassword($password);
return $genpass == $dbpassword;
}
So hit me with your best shot :)
And I don't think my method is as efficient as it could be. I don't understand php enough to understand what $row = mysql_fetch_array($result) is doing unfortunately.
Because you are taking an arbitrary string and placing it directly into an SQL statement, you are vulnerable to SQL injection.
( EDITED based on a comment below. )
The classic example of SQL injection is making a username such as the following:
Robert'); DROP TABLE users;--
Obligatory XKCD link
Explanation:
Given the "username" above, interpolation into your string results in:
SELECT * FROM `users` WHERE username='Robert'); DROP TABLE users;--'
The comment symbol -- at the end is required to "get rid" of your closing quote, because I just substituted one of mine to end your select statement so that I could inject a DROP TABLE statement.
As #sarnold pointed out, PHP's mysql_query only executes a the first query in the string, so the above example (known as query stacking) does not apply. The function is explained here: http://php.net/manual/en/function.mysql-query.php.
A better example can be found here. Here they use a username of
' OR 1 OR username = '
which interpolated becomes
SELECT * FROM `users` WHERE username='' OR 1 OR username = ''
and which would cause your application to retrieve all users.
The short answer is yes.
A perhaps more helpful answer is that you should never trust user input; prepared statements are the easiest way to protect against this, if you have PDO available. See PDO Prepared Statements
<?php
$stmt = $dbh->prepare("SELECT * FROM `users` WHERE username=?");
if ($stmt->execute($username)) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>
The other answers are an excellent description of your problem, however, I think they both overlook the best solution: use PHP's PDO Prepared Statements for your queries.
$stmt = $dbh->prepare("SELECT * FROM users where username = ?");
if ($stmt->execute(array($username))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
This is a small, simple example. There are more sophisticated ways of using PDO that might fit your application better.
When you use PDO prepared statements you never need to manually escape anything and so long as you use this slightly different style, you will never write an SQL injection vulnerability and you don't have to maintain two variables per underlying "data" -- one sanitized, one as the user supplied it -- because only one is ever required.
I would say yes it is open to SQL injection.
This is because you are taking user input in the form of $username and putting it into your SQL statement without making sure it is clean.
This is a function that I like to use in my applications for the purpose of cleaning strings:
function escape($data) {
$magicQuotes = get_magic_quotes_gpc();
if(function_exists('mysql_real_escape_string')) {
if($magicQuotes) {
$data = stripslashes($data);
}
$data = mysql_real_escape_string($data);
}
else {
if(!$magicQuotes) {
$data = addslashes($data);
}
}
return $data;
}
Then you can use it like this:
$username = escape(strtolower($username));
connectToDatabase();
$result = mysql_query("SELECT * FROM `users` WHERE username='$username'");

Is there an SQL injection protection by default in PHP?

PHP controls that with get_magic_quotes_gpc();, however my question is: Is any SQL injection protection enabled by default when installing PHP > 5.xxxx?
I guess it is since I can't recall if I have enabled/disabled any options when dealing with this issue. On a side note, MySQL doesn't seem to be doing anything, since I tried to execute some simple SQL injection in ASP.net/C# with MySQL (community...5 something...) And it worked.
However when I tried the same in PHP - it was escaped with . Also, that was attempted on Windows 7.
Magic quotes is NOT a solution to prevent SQL Injection. It is by far insufficient to do proper character escaping. Just disable it and use prepared SQL statements with bound parameters. See example using PDO:
$pdo = new PDO("mysql:dbname=my_database", $dbUser, $dbPassword);
$sql = "SELECT * FROM users WHERE login = :login AND password = :password";
$stmt = $pdo->prepare($sql);
$stmt->bindValue("login", $_POST["login"]);
$stmt->bindValue("password", md5($_POST["password"]));
$stmt->execute();
$rows = $stmt->fetchAll();
Or be sure to properly escape the inserted values:
$pdo = new PDO("mysql:dbname=my_database", $dbUser, $dbPassword);
$sql = "SELECT * FROM users WHERE login = " . $pdo->quote($_POST["login"]) . " AND password = " . md5($_POST["password"]);
$rows = $pdo->query($sql)->fetchAll();
I recommend using http://php.net/manual/en/function.mysql-real-escape-string.php
I always use that whenever I get an input from a user.
SQL Injection can not be prevented by the PL or the Platform or even the Framework if the programmer doesn't keep it in mind,
There are two general programmatic methods of SQLi prevention :
escape all dynamic strings and then concat them to the query (a little unsafe)
use prepared statements to separate data from query
To use the former try :
$cond = mysql_real_escape_string($cond);
mysql_query("SELECT * FROM table WHERE {$cond}");
To use the latter, you could use PDO in PHP, which has prepared statements supported in.
What all the other answers didn't metion, mysql_real_escape_string WORKS ONLY FOR STRINGS.
I've seen something like this at least over 9000 times.
$id=mysql_real_escape_string($_GET['id']);
mysql_query("SELECT foo FROM bar WHERE foobar=$id");
Keep in mind, that you should explicit cast to an int in this case.
$id=(int)$_GET['id'];
Use a database class which does basic sanitation in case you forgot to do it e.g. mysql_real_escape_string.
I personally use something like this for text inputs (it is not recursive for arrays).
function escape($mixed){
if(is_array($mixed)){
foreach($mixed as $m => $value){
$mixed[$m] = mysql_real_escape_string(htmlspecialchars($value, ENT_QUOTES, "UTF-8"));
}
}else{
$mixed = mysql_real_escape_string(htmlspecialchars($mixed, ENT_QUOTES, "UTF-8"));
}
return $mixed;
}
But you should manually sanitize every input using preg_replace for example using this...
function replace($string, $type = "an", $custom = ""){
switch($type){
case "n": $regex = "0-9"; break;
case "a": $regex = "a-zA-Z"; break;
case "an": $regex = "a-zA-Z0-9"; break;
}
return preg_replace("#([^$regex$custom]+)#is", "", $string);
}
$_POST["phone"] = "+387 61 05 85 05";
$phone = replace($_POST["phone"], "n"); // 38761058505
There is no silver bullet for this.

Categories