Value of omitting ?> in PHP only files [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP closing tag
I've read recently that the ?> should be omitted from files that contain ONLY PHP
In fact even the Zend Framework code standard strongly discourages using ?> in files containing only PHP because:
For files that contain only PHP code, the closing tag ("?>") is never
permitted. It is not required by PHP, and omitting it´ prevents the
accidental injection of trailing white space into the response.
Is the injection of trailing white space really that bad? And it is really a hideous crime to not omit the ?> from files containing only PHP? It simply seems unnatural for me to do so.

If you inject white space in an include and then try to use header() (or something else that depends on running before content is output) then you'll be entering debug hell. This is a quick and easy technique for avoiding that.

If accidental injection happens you cannot send header or start session but errors will show you that. If that happens on every file you have then you have some problems

As far as I know there are no code police running around chopping off people's hands for doing something like this. I say write good code and leave the ?> in.

Related

htmlentities before inserting to database [duplicate]

This question already has answers here:
HTML/XSS escape on input vs output
(2 answers)
Should htmlspecialchars() be used on information on input or just before output?
(2 answers)
Closed 7 years ago.
I want to get my website safe against XSS attacks.
I have one module which allows the user to insert a text (with special chars) into the database. This text is displayed on the start page.
Now my question: Should I use htmlentities($_POST["userinput"], ENT_QUOTES, 'UTF-8') before inserting the userinput into the database?
Or can I insert the userinput directly into the database and just display it with htmlentities?
Some people argue that you should sanitize against XSS on input and output. I think this is not really very valuable. For one, it only really matters that you do it on output, since that's where the vulnerability exists that you are trying to mitigate. Any solution that relies on treating the stuff coming from the database as trusted input is broken in my opinion.
The issue is that somewhere down the line, you (or the person who comes after you) may decide they need to insert the data differently - some external API - who knows. The point is, now your page has a security vulnerability in it, because you decided to trust data from the database.
The argument against doing it on the way in and the way out for me is two parts:
You aren't adding any additional security, so you are really only making people feel like it is twice as safe - this is not a feeling we ever want to create. We want to prove something is safe, not just make it feel double safe.
You also may write a bug that screws up the original data. If this happens when you are rendering it, it's not as big of a deal, because you can fix it and show it correctly. If it happens when you store it, then that data is irrecoverable.

Bypass PHP's str_replace() when replacing a single character

So, I am studying some PHP security using DVWA (http://www.dvwa.co.uk/). Right now I'm on an exercise where the author tries to teach us to execute commands on vulnerable applications. In this level, it adds a very simple blacklist which removes important characters:
$substitutions = array(
'&&' => '',
';' => '',
);
I obviously can use some other characters to still get code executed (like |, ||, &, etc.), but I wanted to know how I'd evade the substitution for the single character ";". I've seen some examples around which fools the substitution with code like "<scr<script>ipt>" and I've tried stuff like ";;;"; tried to encode in hex and base64 and such but it didn't work.
Is there a way to evade str_replace() when it is looking for a single character? This is PHP 5.5.3.
I found this page to be useful when I was doing this. It turns out there are other operators which can be used other than ';' to plug your own command in!
The "hard" setting on this is currently causing myself some trouble, I think there may be a workaround using URL encoded characters or something of the sort, but it remains to be seen.
I'm not sure why the author is showing how to use a black-list, its too easily subverted, perhaps this idea is shredded further on in the tut. http://en.wikipedia.org/wiki/Secure_input_and_output_handling
Although the example you link to is the 'medium' level, even the 'harder' level does not use PHPs Filter FILTER_VALIDATE_IP
Even a REGEX would do a better job. See half way down the page of: http://www.regular-expressions.info/examples.html
If you are trying to protect against XSS attacks (you mention a mangled script tag) then white-listing is the way to go. Validate against what you expect to get, or abort.
EDIT
Hmmm.. now I see the site is called Damned Vulnerable Web App, perhaps the idea is to teach you all the poor examples ...

How to force line-breaks on ?

Sometimes text on my pages looks very strange, real example:
trained professionals and paraprofessionals coming together
...While the parent div is quite narrow so the text is just sticking out of it.
And it looks quite strange, because actually represents a space.
So, I wonder if it's possible to make the browser account these characters as actual spaces and break the line where necessary without actually replacing them?
EDIT
Why a blind replacing is a problem?
Because may be needed sometimes.
Consider the following example:
Ranks:<br>
Marshall<br>
Leutenant<br>
Sergeant
If I just use a preg_replace on them it would look differently in the end.
(I would also consider some suggestions if you have any ideas on replacing them smartly (for php platform) If you could think of some algorithm that wouldn't affect formatting.)
By definition, is a non-breakable space. It's very meaning is not to be broken across line endings. If this is not what you intend then I suggest fixing the HTML instead of trying to force the browser into non-standard behaviour.

Preventing server-side scripting, XSS

Are there any pre-made scripts that I can use for PHP / MySQL to prevent server-side scripting and JS injections?
I know about the typical functions such as htmlentities, special characters, string replace etc. but is there a simple bit of code or a function that is a failsafe for everything?
Any ideas would be great. Many thanks :)
EDIT: Something generic that strips out anything that could be hazardous, ie. greater than / less than signs, semi-colons, words like "DROP", etc?
I basically just want to compress everything to be alphanumeric, I guess...?
Never output any bit of data whatsoever to the HTML stream that has not been passed through htmlspecialchars() and you're done. Simple rule, easy to follow, completely eradicates any XSS risk.
As a programmer it's your job to do it, though.
You can define
function h(s) { return htmlspecialchars(s); }
if htmlspecialchars() is too long to write 100 times per PHP file. On the other hand, using htmlentities() is not necessary at all.
The key point is: There is code, and there is data. If you intermix the two, bad things ensue.
In the case of HTML, code is elements, attribute names, entities, comments. Data is everything else. Data must be escaped to avoid being mistaken for code.
In case of URLs, code is the scheme, the host name, the path, the mechanism of the query string (?, &, =, #). Data is everything in the query string: parameter names and values. They must be escaped to avoid being mistaken for code.
URLs embedded in HTML must be doubly escaped (by URL-escaping and HTML-escaping) to ensure proper separation of code and data.
Modern browsers are capable of parsing amazingly broken and incorrect markup into something useful. This capability should not be stressed, though. The fact that something happens to work (like URLs in <a href> without proper HTML-escaping applied) does not mean that it's good or correct to do it. XSS is a problem that roots in a) people unaware of data/code separation (i.e. "escaping") or those that are sloppy and b) people that try to be clever about what part of data they don't need to escape.
XSS is easy enough to avoid if you make sure you don't fall into categories a) and b).
I think Google-caja maybe a solution. I write a taint analyzer for java web application to detect and prevent XSS automatically. But not for PHP. I think Learning to using caja not bad for web developer.
No, there isn't. Risks depend on what you do with data, you can't write something that makes data safe for everything (unless you want to discard most of the data)
is there a simple bit of code or a function that is a failsafe for everything?
No.
The representation of data leaving PHP must be converted / encoded specifically according where it is going. And therefore should only be converted/encoded at the point where it leaves PHP.
C.
You can refer to OWASP to get more understanding of XSS attacks:
https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
To avoid js attacks, you can try this project provided by open source excellence:
https://www.opensource-excellence.com/shop/ose-security-suite.html
my website had the js attacks before, and this tool helps me block all attacks everyday. i think it can help you guys to avoid the problem.
Further, you can add a filter in your php script to filter all js attacks, here is one pattern that can do job:
if (preg_match('/(?:[".]script\s*()|(?:\$\$?\s*(\s*[\w"])|(?:/[\w\s]+/.)|(?:=\s*/\w+/\s*.)|(?:(?:this|window|top|parent|frames|self|content)[\s*[(,"]\s[\w\$])|(?:,\s*new\s+\w+\s*[,;)/ms', strtolower($POST['VARIABLENAME'])))
{
filter_variable($POST['VARIABLENAME']);
}
To answer to your edition: everything except <> symbols has nothing to do with XSS.
And htmlspecialchars() can deal with them.
There is no harm in the word DROP table in the page's text ;)
for clean user data use
html_special_chars(); str_replace() and other funcs to cut unsafe data.

What is "enough sanitization" for a URL [duplicate]

This question already has answers here:
Best way to handle security and avoid XSS with user entered URLs
(12 answers)
Closed 9 years ago.
The URL would be
Saved to a MySQL database
Used to display a picture on the user's profile
would strip_tags() and mysql_real_escape_string() be enough?
"Enough sanitization" thoroughly depends on what environment you're talking about. Sanitization for MySQL should be considered entirely separate from sanitization for web output, and you should handle them separately to avoid a lot of hassle.
Sanitizing for MySQL
mysql_real_escape_string() will sanitize a piece of data and make it safe to put inside an SQL query.
Any other type of malicious data, such as HTML tags inside the string, should be absolutely ignored. Trying to manipulate it here will lead you to headaches as you try to "un-manipulate" it later after getting it out of the database. Bad "web data" cannot harm your database.
Sanitizing for output
htmlspecialchars($val) at output time will prevent any malicious tags from being rendered, because < and > characters are converted into their entity representations and not rendered as tag delimiters.
Use the ENT_QUOTES modifier if you are outputting something that is inside an HTML element's quoted attribute, such as <input name="email" value="<?php echo htmlspecialchars($email,ENT_QUOTES); ?>" />
That should be all you need, unless you have special requirements. strip_tags() shouldn't really be used for sanitization, as it can be fooled with badly formed HTML. Sanitization is a worthy goal, and if you can keep your contexts separate, you'll run into fewer problems with data manipulation between them.
It's probably safer and better to call htmlentities() on the string instead of counting on strip_tags().
strip_tags() won't remove html special chars like '"&
e.g., if your code is:
<img src="<?= strip_tags($myVar) ?>">
and
$myVar = '">something goes here<';
then you end up with:
<img src="">something goes here<">
Which is pretty obviously the root of an XSS hole; an actual exploit is left as an exercise for the reader.
I initially upvoted Frank's answer, but thought of a problem: htmlentities() will break legal urls like this:
http://www.mywebsite.com/profile?id=jojo&w=60&h=60
Perhaps stripping angle brackets + mysql_real_escape would be sufficient?

Categories