Safely capture URL Encoded String for Search Input? - php

I basically have a search form with input:
<input type="text" name="search" />
This ends up sending the user off to:
/search/[URL_ENCODED_STRING]
So if they searched for
http://www.stackoverflow.com/
The url would be:
/search/http%253A%252F%252Fwww.stackoverflow.com%252F
My problem comes with knowing if the input I then read later is safe. I would then on the search page use Drupal's inherent ways of reading the value (arg(1)). But even without drupal, the result would be essential the same. I would end up with:
$variable = urldecode($input);
If I then print out $variable, it will show:
http://www.stackoverflow.com/
My question is, what kind of sanitizing must I apply to this string before using it in SQL? Is it simply "addslashes"? Or should I remove all non alphanumeric and number values?
NOTE
I haven't gotten to that part yet, but I'm fairly certain Drupal will apply it's own sanitization if I pass this variable to the built-in search function, but I still would like to know what the right way is to sanitize this input to avoid malicious users doing strange things on the website.
UPDATE
I got to the part and Drupal does take care of the prepared statement part. But I still don't know how I would sanitize the string when printing it here:
<div id="searchedFor">
<span class="preLabel">You searched for</span>
<h2><?php print $_REQUEST['search']; ?></h2>
</div>
What is the most correct way to print that out?

To sanitize to the page, use htmlentities() or strip_tags() or htmlspecialchars():
<div id="searchedFor">
<span class="preLabel">You searched for</span>
<h2><?php echo htmlentities($_REQUEST['search'], ENT_QUOTES); ?></h2>
</div>
Example:
<?php echo htmlentities("<script>NastyJS('code');</script>", ENT_QUOTES); ?>
<!-- Shows in browser this way -->
<script>NastyJS('code');</script>
<!-- but shows in source this way -->
<script>NastyJS('code');</script>

Related

Writing HTML / PHP Code inside an input/Textarea

I have found out that if a user writes in an input php/HTML code the code will excecute in my admin panel. Can this damage my system ? And if yes how can I disable it?
I will appreciate any answers!
You can remove HTML and PHP tags with
<?php
$text = '<p>Test paragraph.</p><!-- Comment --> Other text';
echo strip_tags($text);
echo "\n";
// Allow <p> and <a>
echo strip_tags($text, '<p><a>');
?>
result:
Test paragraph. Other text
<p>Test paragraph.</p> Other text
source: https://www.php.net/manual/pt_BR/function.strip-tags.php
It is a good practice to always filter data that comes from outside the application. So I mean every input that is given to the application. Particular attention must be given by the programmer to the way in which to execute the queries to the database. Since database queries can also be made using parameters that come from the user or more generally from outside the application.
Remove all HTML tags from the input before they are used to run queries or saved to the DATABASE.
https://www.php.net/manual/en/function.strip-tags.php
strip_tags ( string $string , array|string|null $allowed_tags = null )
Pay particular attention to the formatting of queries and input parameters before running database queries to avoid SQLinjection
an interesting article about it : https://www.ptsecurity.com/ww-en/analytics/knowledge-base/how-to-prevent-sql-injection-attacks/
Cyber ​​Security is a very broad topic and I don't think it can be expressed here in just one answer.
Dealing with this topic requires more and more IT requirements such as, for example, knowing Programming
This answer is intended to be a starting point to deepen the subject
Yes, definitely it effect the project, not only html and PHP also SQL queries and JavaScript code also.
For prevention you have to validate the input using JavaScript or jQuery.

use a href inside html entities

I use html entities to secure my site.
And my client want to add link in his post using the CMS.
how to make exception in html entities?
my code example:
<p><?php echo h($row['message']) ?></p>
//h is my function for htmlentities
My code display this message:
"You can click this link Link"
//And I dont know my data insert '\'
//It become Link
If my question is not clear please ask.
Really appreciate.
I believe what you want to do is pass into the DB with htmlentities() so it doesn't mess with your DB. To retrieve them you would use html_entity_decode(). The html_entity_decode() converts all strings with HTML entities back to there original string.
http://php.net/manual/en/function.html-entity-decode.php
Hopefully this answers your question.
Edit:
Raw data retrieved: http://www.example.com
Through htmlentities it spits out the HTML entities, which the browser cannot interpret when attempting to find that page. The use of htmlentities() (please if I'm wrong correct me) is to encode user input before passing it anywhere else.
User input: <script>hacks</script>
Passed though htmlentities:
&ltscript&gthacks&lt (whatever backslash is)script&gt
(This way it can't mess with anything in your database, better example is the use of PHP/MySQL but I'm not well versed to give that exact example at the moment.)
However this would expose your site when decoding it as well and other precautions would have to be taken.
Try this :
<?php
$link = h(stripslashes($row['message']));
?>
You can click this link <a href='<?php echo $link; ?>'>Link</a>

php echo php to browser, not showing up, security issue?

What happen if i use the following?
<?php echo "<?php echo date('Y'); ?>"; ?>
i could not find an answer anywhere, and when i try it myself, i get:
<?php echo date('Y'); ?></td></tr></table>
However, it does not show up on front browser, only source.
So my question is, does this affect the html/browser/server in any way?
as i do not want to end up creating a security issue should user post their
own php code in a html only format, like a bio page etc.
It's because of the chevrons ('<' and '>'), because the browser interprets them as tags.
There are 2 ways you could get round this.
Either use the codes for special characters, so you would do:
<?php echo "<?php echo date('Y'); ?>"; ?>
Or, an easier way, use the htmlspecialchars() function:
<?php echo htmlspecialchars("<?php echo 'hi'; ?>"); ?>
More info on the htmlspecialchars() function can be found at http://www.php.net//manual/en/function.htmlspecialchars.php
It is not a security problem and will not have any effects on browser or server, at least not because of PHP code. Even if the string contains PHP code it will just be sent to the client which will not attempt to execute it.
The real problem when echoing user-defined HTML is the risk of attacks such as XSS. Users could include arbitrary scripts or images or scramble the rest of the page by inserting arbitrary tags. In other words: Users could modify the whole page with a single line of HTML.
In general, it's a bad practice to allow such arbitrary input. Have a look at strip_tags which provides a very basic level of protection.

PHP: Scripting (XSS_in_URI.script)

When I check my script with Acunetix vuln scanner i see this XSS error :
This vulnerability affects /cms/search.php.
Discovered by: Scripting (XSS_in_URI.script).
Attack details
URI was set to "onmouseover='prompt(961413)'bad=">
The input is reflected inside a tag parameter between double quotes.
in search.php page i safe all user input with this:(safeXSS name of anti XSS function)
if (isset($_POST['search'])) {
$search = array_map ('safeXSS', $_POST);
}
else
{
$search = array_map ('rawurldecode', $_GET);
$search = array_map ('safeXSS', $search);
}
search form input:
<input type="submit" name="search" class="submit" value="search" />
I do not understand what's my problem?! how do i can fix this?
In your PHP template somewhere you will have code like:
<a href="<?php echo $uri ?>">
or:
echo "<a href=\"$uri\">";
HTML-escaping is missing here, so if a quote character is included in the value in $uri then that URI content escapes the attribute value it is supposed to be contained in, and you get dangerous output:
<a href=""onmouseover='prompt(961413)'bad=">">
You should fix this by calling htmlspecalchars() each and every time you output a plain text string into HTML text content or attribute values:
<a href="<?php echo htmlspecialchars($uri, ENT_QUOTES 'utf-8') ?>">
(You can make this less obtrusive by defining a short-named function like h() that calls echo htmlspecialchars for you. Or, in the longer term, prefer to use a template language that does this automatically for you.)
The filtering you've got on $_POST/$_GET is not at all effective. It is unclear what safeXSS is doing exactly, and I have absolutely no idea what rawurldecode is there for, but in general it is not possible to implement correct handling of string escaping at the input stage.
Using input ‘sanitisation’ to attempt to combat XSS is a common antipattern that should be avoided. (You may want to do custom input filtering for other reasons, but it's the wrong way to handle injection/escaping problems.) HTML-injection, JavaScript-injection, XML-injection and so on are output-stage concerns; the input stage doesn't know what contexts input is going to be used in yet, so can't treat the input in the correct way for that output context.

Back slashes appearing when data is picked from text-area in php

Here's what I am doing,
<?php
if(isset($_POST['submit'])){
$text_area= mysqli_real_escape_string($dbc, strip_tags(trim($_POST['text_area'])));
echo $text_area;
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<input type="textarea" name="text_area" style="width:280px;height:90px" id="myTextarea" />
<input type="submit" name="submit" Value="Submit"/>
</form>
But whenever I try to insert something like this: "Hello World" or 'Hello World', it outputs: \"Hello World\" or \'Hello world\'
where am I going wrong?
That's because you using the mysql-real-escape-string function. Use the stripslashes function on your data before displaying it to remove the slashes.
It seems you are outputting the value from the mysqli_real_escape_string method that escapes the string value for a SQL query to avoid SQL Injection. If you simply want to output anything that was inputted into the textarea then you can just purely show the value from the $_POST array but BEWARE if you don't do any checks you can easily fall victim to someone inputting some javascript etc. and have it appear on the page.
So for example to output just the pure text you sent to the server.
trim($_POST['text_area'])
and then you can call mysqli_real_escape_string again while building your query to make the string safe and avoid some common attacks.
You are using mysqli_real_escape_string incorrectly - it serves no purpose here.
Do not use it in this context, and the problem will go away. Use it only when entering data into a database.

Categories