This question already has answers here:
How can I sanitize user input with PHP?
(16 answers)
Closed 2 years ago.
I own an online game where you have a status box. Which you can update it on how you're feeling. The problem I have had was that users were putting java script tags into messages and into status. So when another user came to their page, a pop up box would pop up saying haha or whatever they wanted.
I then stopped that by using
$status = mysql_real_escape_string($_POST['status']);
$foo = preg_replace('/[^a-z]/i', null, $status );
That has now stopped any JavaScript being ran but now when someone sends someone a message, it takes the spaces out so for the message "how are you " It will show "howareyou". Of course this is safe but users can't read messeges. Is there any other way from stopping script tags being inserted into the virable but still allow spaces?
I'm also real scared of someone hacking me with XSS. Because before, I was told a user could enter something in a message then when the other user opens it, it will send them there password.....
First of all using mysql_real_escape_string() on all external input prevents all SQL injections - no preg_replace needed at all! But that's only for preventing SQL injection.
In order to prevent scripting / HTML injection on your website, you should always use htmlspecialchars() to escape all text that comes from user input before you present it to a visitor of your site. (e.g. immediately after SELECT from database)
Please take this serious: If you find the time, go and google for SQL injection! It is not complicated and you'll understand it easily. If you create websites - no matter for whom - and store user input in a database, you will observe that someone tries to do SQL injection. It is easy to do, and there is automated software out in the web that can easily try all sorts of SQL injection on hundreds or thousands of websites automatically! And for a client it definitely is not acceptable if the developer doesn't prevent SQL injection at all, so take your time for this issue.
The same goes for script injection! As with SQL injection, preventing this is really very easy. All you have to do is convert all text that comes from user input into HTML, so that when some evil guy enters <script>...</script>, your visitors will simply see exactly this, because for example the < gets converted into < and thus prevents the script from being interpreted by the browser as javascript.
$foo = htmlspecialchars($status);
Related
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 3 years ago.
I saw a lot of websites in google on which i found vulnerability for SQL injection. Of course most of them were index.php?id=1 or something similar. Why is it that something tells me that even if i use prepared statement on such page, i will still be vulnerable for SQL injection? I mean... how can there be so many websites vulnerable for SQL injection. Is that link safe if i use prepared statements??
Seeing so many vulnerable sites using such link just blows my mind. I ask myself, there is no way people can be that stupid? How can they code so professional looking websites with vulnerabilities like this. I know how the prepared statements work. When you use prepared statements, you prevent the database to read the input as code. It's just the fact that i saw so many websites vulnerable for attacks.. it made me have heavy doubts in my mind about my website. I use exactly the same method for my users page, here is my code.
<?php
// Setting the input ID to variable
if(isset($_GET['id'])){
$the_input_id = $_GET['id'];
}else{
header("location: ?page=error1");
exit;
}
global $db;
$stmt = $db->prepare("SELECT * FROM users WHERE id=:id");
$stmt->execute([':id' => $the_input_id]);
$result = $stmt->fetchAll();
$db = null;
// Checking if there is result ...
if (!$result){ // If there is no result ...
header("location: ?page=usernotfound");
exit;
}else{ // If there is result ...
// Show the user profile
}
?>
This is the code from my users page, this is based on the user's input but as you can see i am using prepared statement. I am still worried about it. Maybe there is something more that i need to know about the security? I keep having heavy doubts in my mind after the sites i saw today.
I also saw some forums that are not using links like index.php?id=1. They use something like this "www.randomforum.com/index.php?/user/1029498/". Well, how does that work? That link cannot be SQL injected i think. I am not so experienced in this so i need someone to explain to me how does that kind of link work. I think that works the following way:
-Each time user gets registered, a new file get's created in the "user" folder. The file name is the ID of the account of the user. And that file just contains the user's page.
This is my explanation of how that forum works... but i am sure i am wrong. Please give me some opinions. Thank you for your time.
From my experience, the best way to keep your site 99% safe from these sorts of attacks is to:
1) Escape parameters in mysql queries.
You are currently doing this. Prepared statements will escape it for you, as long as you put them in the execute([]) array.
2) Escape HTML on output.
If someone inserts HTML into your table, you need to escape its output. The best way of doing this is to use htmlspecialchars()
More info here:
http://php.net/manual/en/function.htmlspecialchars.php
3) GO OVER ALL OF YOUR CODE! You want to make sure you aren't accepting raw user input, as one faulty form could ruin it all.
The site creators you're talking about may be really good at creating form styles, but MAY need a little more help with their php coding.
Good luck with your site!
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 1 year ago.
I'm a newbie in PHP development. I created a site using PHP, HTML & Css which has a contact us page. Since last couple of days someone from a particular country (I don't want to mention the country name) is creating support message and entering some unusual or suspicious messages.
The contact from has four fields such as Full Name, E-mail, Subject & Message.
Someone is sending messages like
1st:
written as "Subject" & (select(0)from(select(sleep(6)))v)/*'+
(select(0)from(select(sleep(6)))v)+'"+(select(0)from(select(sleep(6)))v)+"*/
2nd:
-1' OR 2+582-582-1=0+0+0+1 or '0gX9xp3t'='
3rd:
1iY5zL4R'));select pg_sleep(3); --
4th:
1||UTL_INADDR.get_host_address('dns.'||'sqli.032682.7775.77.a4f00.1.bxss'||'.me')
And there are many, please anyone who is familiar with PHP or others tell me what is this going on. Also please share some security precautions which I should take to prevent any threats or hacking.
I have built my site using MYSQLi to prevent/minimize SQL injection threats.
Few methods you can take to make your form safe are:-
Use htmlspecialchars() to prevent XSS attacks.
Encrypt passwords and other personal information via md5() or other methods.
Use POST method instead of GET for transferring confidential information.
Do not transfer confidential data through URL.
Use certain tools to prevent spambots attack.
If possible, add recaptcha.
For more tips, kindly check out https://www.thoughtco.com/solutions-to-protect-web-forms-from-spam-3467469.
PS: I am also new to PHP, just sharing my thoughts! Trust it is helpful.
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 9 years ago.
I want to / am busy with completely re-writing my whole site. At this point I am working on what I call "members- and safety engine". I have been reading a lot about security and SQL injection, and it is pretty complicated.
ps. My site is more a hobby than a professional money making website with about 250+ members.
For username AND password I only allow the characters a-z, A-Z and 0-9. I check this in the if(isset(post))-function with:
if(ctype_alnum(mysql_real_escape_string(stripslashes($string))) == false) {
header to error-page; exit;}
else {continu with script}
This check is done for both the password and the username.
When somebody tries to login with a unknown username or a known username with a wrong password the action is logged (inserted) in a special table, including IP address. After 10 attempts to login with an unknown username, or 6 attempts with a wrong password the IP address is blocked from the members area and on all the non-member pages forms and submit of the forms are not shown and they are not useable because of this ip-block. I even have this ip-check as a line when the form is submitted... if the ip is in the table, header(to error page); exit;.
My questions:
Do I have to make a security check when I place the
IP address in a string? $xip = $_SERVER['REMOTE_ADDR']; this $xip is
inserted in the table when trying to log in with a unknown user or
with wrong password.
Is this a (pretty) safe environment against hacking and SQL injection?
If not? I really appreciate help and suggestions (writing the complete solution here is very much appreciated, but I learn a lot
more when you send me on the right path to the solution)
Do I also have to run the "ctype_alnum" check when I retrieve this info from the $_cookie or the $_session?
ps. I am dutch, so almost all of my table names, column names, form input-field-names etc etc etc have a dutch word for it. I am still working on it, but when the site is finished you will not find the word "password", "pass", "user", "userid", or anything like that on my site.
Using prepared statements with MySQLi or PDO is a must as a first step to preventing SQL injection, and the mysql_* commands are deprecated anyway.
But, the best place to answer your questions for best practices at preventing SQL Injection would be OWASP: They have many great resources for both general methodologies and review of code, as well as language-specific guidelines and libraries.
https://www.owasp.org/index.php/Guide_to_SQL_Injection
https://www.owasp.org/index.php/Reviewing_Code_for_SQL_Injection
No you don't have to, this variable is safe. Have a look at : Is it safe to trust serverremot addr
It depends, you will have to post the entire authentication code
Usually a good practice is to select every users from the DB, then iterate over them and compare username/password in order to find a match. That way you don't need to place user input in the SQL statement.
It depends what you do with the content of these
This question already has answers here:
Should I escape an expected integer value using mysql_real_escape_string or can I just use (int)$expectedinteger
(2 answers)
Closed 9 years ago.
I have a PHP script that depending on the value of an id in a GET variable will retrieve different data from a mysql database. The value of the id should be a number at all times. Instead of changing my current mysql query to use PDO, would running isnumeric on the Get variable and exiting the script if it is not a number be sufficient to protect against injection in all or most cases, ie, would it still be possible for some injection sql to slip through isnumeric?
Just a humble comment on the duplicate question issue, I looked at the suggested duplicate question and think that as a beginner it might not be clear on its face that my question is an exact duplicate of that one.
Yes, it would protect in this case. No, it would be a really, really bad idea unless you absolutely know what you're doing and document the choice properly in comments.
There are 2 strategies towards any kind of security:
Denial. Choose the lazy approach that works for the situation at hand instead of fundamentally fixing it. Now wait for the day you forgot this was your 'security', and you change the code and it becomes vulnerable all of a sudden, and kiddie porn is uploaded to your site.
Professionalism. Fix the problem thoroughly, validate the inputs and protect your database layer properly, by either escaping or using prepared statements.
Choose professionalism and thank me a year from now.
Seems like this question has already been answered. And yes, the isNumeric trick essentially would only allow sanitized inputs, thus shielding your application from SQL injection.
This question already has answers here:
How can I sanitize user input with PHP?
(16 answers)
Closed 9 years ago.
I'm very new to PHP, basically I'm trying to create a commenting system for my site. I have the following function:
$input = $_POST['comment'];
function cleanUserInput($input) {
$input = mysql_real_escape_string($input);
$input = htmlentities($input);
return $input; }
So the question is, is mysql_real_escape_string alone sufficient to prevent sql injection? and is htmlentities() sufficient to prevent scripts, html and styles entered by the user from having actual effect and just be shown as text?
Or do I need to add more to my function to make the input really harmless?
mysql_real_escape_string is NOT enough. You must also take into account how you structure your query. Consider the following simple login script:
$username = mysql_real_escape_string($_GET['username']);
$password = mysql_real_escape_string($_GET['password']);
$sql = "SELECT * FROM users WHERE username = $username AND password = $password";
without quotes around $username and $password, injection is STILL possible. (Consider a username = test; DROP TABLE users; --. Bye bye data! :(
mysql_real_escape_string is sufficient from a sanitization point IF you structure your query correctly. For a properly constructed query, this works fine.
A better question is "what are you trying to prevent?" You should also be aware of XSS (cross-site-scripting) stored and reflected. If you are storing input from users in your database and that data is rendered in the browser, you'll want to strip out <script> tags at the very least.
There are many filters and code available on line for this depending on your language. If you use Rails or CodeIgniter, it's done for you.
As far as this type of security is concerned, I recommend using the following:
download and install damn vulnerable web app. its an application designed to teach the ins and outs of web hacking (php-based)
always try to submit characters of a different charset
always try to submit the NULL byte
avoid passing too many parameters in the querystring (it can give away your data structure)
watch your logs
download burpsuite - you'll never look at a website the same way again
watch being chatty. mysql error messages are great for debugging, but they give away a ton of information - often times they reveal the whole query!
bottom line - if it comes from the user, it can't be trusted!
Both functions do solve a major part of the security issues regarding injections of any kind and some more problems, however, the amount of security bugs that your application can have is staggering.
If you are a security freak, then you're in for major problems, but you'll be allright by starting on checking Chris Shiftlett's website, who is one of the major authorities on PHP security around the world.
And finally you can check the OWASP web, and their Top Ten Project, where they keep track on the most common security threats and keep updates on hw to fight them,
Hope I can be of assistance.
If you're using PHP 5.2 or newer, you can use the built-in input sanitization.
For example:
$input = filter_input(INPUT_POST, 'comment', FILTER_SANITIZE_STRING);
References:
filter_input
Available filters