Is Mustache XSS-proof? - xss

I was thinking about my app's XSS vulnerability. On the server side I don't sanitize either input or output, so
<script>alert(document.cookies)</script>
is stored in database exactly so. To view this value on the client side I use Mustache. If this script was executed by an admin, it is of course easy to hijack his session. However I've noticed that Mustache by default escapes these values & \ " < > when you use the {{}} syntax. Do I need to worry about XSS, when the value from the database would be inserted into
<p>{{value}}</p>
or even
<p data-id='{{value}}'>something</p>
? Should I perhaps review my Mustache templates to look for any vulnerable code, or unless I'd use
<script>{{value}}</script>
I am safe?

Well, you should always worry :) But yes, Mustache accomplishes the goal you are talking about here, protecting your examples from XSS (except where you're outputting the value directly into a <script> tag).
Note: check that the Mustache implementation you're using escapes single quotes. It's apparently not in the spec to do so (https://github.com/mustache/spec/issues/69) but the major implementations thankfully escape it anyway.

Related

How to prevent XSS attack in django

I'm trying to prevent XSS attack in Django, is it ok to use {{ body|escape }} in my HTML file only? How can I do some filtration in the backend?
Not every case is the same security-wise. So hard to give complete advice without seeing your application and the use cases and the Version of Django you use.
If you use the Django's template system and make sure that auto-escaping is enabled (it is enabled by default in recent versions), you're 9x% percent safe. Django provides an auto-escaping mechanism for stopping XSS: it'll automatically escape data that are dynamically inserted into the template. You still have to be aware of some issues:
All the attributes where dynamic data is inserted. Do <img alt="{{somevar}}"> instead of . Django's auto-escaping will not cover your unquoted attribute values.
Data inserted into CSS (style tags and attributes) or Javascript (script blocks, event handlers, and onclick attributes), you must manually escape the data using escaping rules that are appropriate for CSS or Javascript (Probably using a custom filter on the Python side).
Data inserted into a URL attribute (href, img src), you must manually validate the URL to make sure it is safe by checking the protocol against a whitelist of allowed protocols (e.g. https:, mailto:, ... but never javascript:).
Avoid setting html attributes from user input.
If you use mark_safe, make sure you know what you are doing and the data is really "safe".
There is always more but this covers the most known issues. Always make sure to refer to OWASP to understand the different XSS attacks and how they apply to your specific application:
https://owasp.org/www-community/attacks/xss/
https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html

Vue: keep linebreaks and indentation intact

I'm working on a Vue app that (obviously ;)) loads Vue templates, lets the user fill in content and then export the markup of those templates/components. However, all linebreaks and indentation are lost in the process.
Is there any way to make Vue keep that information? So far at least I achieved to keep (conditional) comments via the
comments: true
option. There are several other options like expectHTML or shouldDecodeNewlines, but they don't seem to be documented and none of them seem to help me accomplish what I want.
The problem is that we're in part handling email templates (meh...) and it's a client requirement that "input === output" (well, markup-wise), because indeed a space or linebreak here or there can indeed make a difference in fussy mail clients. So simply running the markup through a beautifier is not an option.
I know, I know... That's not really what Vue is made for, and markup !== DOM... But the tool itself is written in Vue and I love to currently be able to use all the magic of Vue syntax inside the templates being processed as well.
If all else fails, I might have to resort to using mustache (or any other template system - recommendations welcome) - but I would really like to keep the templating as it is right now, for the aforementioned reasons.

Measures to prevent XSS vulnerability (like Twitter's one a few days before)

Even famous sites like Twitter are suffering from XSS vulnerability, what should we do to prevent this kind of attack?
The #1 Thing you can do is set your cookies to HTTP Only ... which at least protects against session cookie hijacking. Like someone stealing your cookie when you are likely admin of your own site.
The rest comes down to validating all user input.
RULE #0 - Never Insert Untrusted Data Except in Allowed Locations
RULE #1 - HTML Escape Before Inserting Untrusted Data into HTML Element Content
RULE #2 - Attribute Escape Before Inserting Untrusted Data into HTML Common Attributes
RULE #3 - JavaScript Escape Before Inserting Untrusted Data into HTML JavaScript Data Values
RULE #4 - CSS Escape Before Inserting Untrusted Data into HTML Style Property Values
RULE #5 - URL Escape Before Inserting Untrusted Data into HTML URL Attributes
Very lengthy subject discussed in detail here:
http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
http://www.owasp.org/index.php/Cross_site_scripting
XSS is only one of many exploits and every web dev should learn the top 10 OWASP by heart imho
http://www.owasp.org/index.php/Top_10_2007
Just like you can make SQL injection a non-issue by using prepared statements, you can make XSS non-issue by using templating engine (DOM serializer) that does similar thing.
Design your application so that all output goes via templating engine. Make that templating engine HTML-escapes all data by default. This way you'll have system that's secure by default and does not rely on humans (and rest of the large system) being diligent in escaping of HTML.
I don't what you write your code with, but if your use asp.net, you are partly covered.
asp.net has what they call request validation that when enabled, it prevent malicious script to be introduced via user input.
But sometimes, you'll have to allow some kind of text editor like the one you typed in this question. In this case, you'll have to partly disable request validation to allow some "rich text" html to be input by the end user. In this case you will have to build some kind of white list filtering mechanism.
FYI, I don't know about others but Microsft has library called Anti-Xss.

How do you decide what to use: UDF or Custom Tag?

WACK says:
If you feel you need to have lots of arguments, consider creating a CT instead.
...
CT are significantly more powerful and
flexible than custom functions. Try to
use UDFs for simple matters... Use CT
and Components for more involved
processes, especially those you can
think of as discrete actions rather
than simple "massaging"
Okay, but how are you usually making decisions? Interesting to know real-life practice and examples.
For me it happens when a function has many not-required arguments, so I have to call them myFunc(arg1="foo", arg2="bar"). Sometimes <cfmodule> syntax simply becomes more readable, but not always.
Other reason is that I don't like long (say, more than 2 screens of code) UDFs.
But all these thoughts are very subjective, that's why I'm interested in reading other people opinions. Maybe there's better rules for that?
Thanks in advance.
There a probably plenty of people in the community that would disagree with me, but here is how I generally think about it. If what you need to do involves output to the screen, and if it makes sense to "wrap" this around some other code or text, then a custom tag might be in order. In all other cases a UDF works fine and generally better. That being said, in close to 8 years of CF development, I really haven't ever came across a very good reason for a custom tag. I'm not saying the reasons don't exist, but I would say that they are rare.
If you have a very long UDF, is it safe to assume that this is something where you are outputting to the screen by calling this UDF (not really returning a value I mean)? I would consider breaking that UDF into smaller more manageable parts if that could make sense, but like you are alluding to, what matters in the end is what is the most readable, to you, your team and those who may come after you.
Update: Out of curiosity, which CFWACK book are you referring to (version and volume) and which page?
As I remember things, custom tags can be called at any time, where as UDFs have to be defined before you can use them. This makes custom tags easier generally. If you had huge libraries of UDFs it would be burdensome to make sure they are all included and potentially hard work for the server to parse them all (in olden days at least).
However UDFs can be used in a more compact way
<cfif myUdf(myVariable)>
The advantage of custom tags is that they can sit nicely with your markup.
<h1>Order Page</h1>
<cf_basket_nav>
<ul>
<cfloop ...>
<li>
<cf_basket_item item="#items[i]#">
</li>
</cfloop>
</ul>
</cf_basket_nav>
Generally nowadays I would have a 'utils' CFC with methods for what were your UDFs.
one consideration on the use of custom tags over udfs or cfc methods is when you find that a subroutine needs to be passed an array of child items, you can use nested custom tags to associate a child custom tag and its elements to a parent custom tag. this allows you to do very nice clean coding thats easy to read:
<cfmenubar ... >
<cfloop array="menuitems" ...>
<cfmenubaritem url="#i.url#">
#i.label#
</cfmenubaritem>
</cfloop>
</cfmenubar>
yes,yes i know we have nicer dhtml stuff like menus and tabs, this is simply to point out an example. you can use cfassociate in the custom tag to "pass" the attributes to the parent custom tag and then in the executionmode="end" access all the dynamically generated child items in the array of associated attributes. this is where you would loop and output the menu to the screen in this example.
also, as another commented, allows you to do some clever things... one thing in particular i use is that i set prefix="" and then i can essentially force simple html tags (like the <a> tag) to get kicked through a custom tag handler at runtime - so an html tag becomes intelligent at runtime... i do this so i can analize the href and the target attributes and decide if i want to display a pdf icon (or other mime type icon) next to the link... its pretty slick! this is especially helpful in a content management system or when 7you have html developers using dreamweaver or contribute and you want to have their tags fire smart coldfusion tags without them doing anything outside of standard html - the editor doesnt know any difference and they dont need to go into "code" view to make some fairly powerful functionality.
finally, in a custom tag you can choose to suppress output (or use a cache), so this can be very useful to wrap around chunck of dynamically generated html... access the thistag.generatedcontent variable in the executionmode EQ "end" mode
dont throw out the baby with the bathwater on this one ... i agree their usage is much less frequent since we have cfcs, however there is still some powerful functionality in custom tags... i usually have one or 2 in every application (and at least dozens of cfcs)
hth
jon
cfmodule has no advantage over functions; cfinvoke works just the same.
Of course, with cfimport you can enable a nice tidy namespaced CT syntax - and this is when custom tags are good: when working with clear open/close construct, or if nested logic is important.
For everything else, especially when returning results, functions are easier to handle.
Jeremy pointed to useful option: wrapping HTML by CT. But this feature seems to be so rarely used. Any way, it's a plus for CT.
Also I thought that I prefer function because I love cfscript coding. Few times I had to wrap legacy CT into UDF only to be able to use it at totally cfscript-ed page. It's a plus for UDF.
Simple reusable code can go into a UDF. This might include things like string formatting, data structure manipulation, etc etc.
For anything more complex than that, I would consider using CFCs instead of a custom tag. You'll be able to write much cleaner code in an OO model. You can always wrap the logic in your CFCs with a custom tag if you want to provide ease of use for someone who is more used to working with tags.
Not sure why I fell into this pattern, but in general I use Custom Tags (always with cfmodule) for anything that outputs HTML and UDFs for anything that merely returns simple data/objects. I realize that UDFs can do output as well, but I don't like my functions to have any side effects and this feels like one. For similar reasons, I now use Custom Tags anywhere where previously I would have used a cfinclude, since they provide encapsulation of data.

How do you allow the usage of an <img> while preventing XSS?

I'm using ASP.NET Web Forms for blog style comments.
Edit 1: This looks way more complicated then I first thought. How do you filter the src?
I would prefer to still use real html tags but if things get too complicated that way, I might go a custom route. I haven't done any XML yet, so do I need to learn more about that?
If IMG is the only thing you'd allow, I'd suggest you use a simple square-bracket syntax to allow it. This would eliminate the need for a parser and reduce a load of other dangerous edge cases with the parser as well. Say, something like:
Look at this! [http://a.b.c/m.jpg]
Which would get converted to
Look at this! <img src="http://a.b.c/m.jpg" />
You should filter the SRC address so that no malicious things get passed in the SRC part too. Like maybe
Look at this! [javascript:alert('pwned!')]
Use an XML parser to validate your input, and drop or encode all elements, and attributes, that you do not want to allow. In this case, delete or encode all tags except the <img> tag, and all attributes from that except src, alt and title.
If you end up going with a non-HTML format (which makes things easier b/c you can literally escape all HTML), use a standard syntax like markdown. The markdown image syntax is ![alt text](/path/to/image.jpg)
There are others also, like Textile. Its syntax for images is !imageurl!
#chakrit suggested using a custom syntax, e.g. bracketed URLs - This might very well be the best solution. You DEFINITELY dont want to start messing with parsing etc.
Just make sure you properly encode the entire comment (according to the context - see my answer on this here Will HTML Encoding prevent all kinds of XSS attacks?)
(btw I just discovered a good example of custom syntax right there... ;-) )
As also mentioned, restrict the file extension to jpg/gif/etc - even though this can be bypassed, and also restrict the protocol (e.g. http://).
Another issue to be considered besides XSS - is CSRF (http://www.owasp.org/index.php/Cross-Site_Request_Forgery). If you're not familiar with this security issue, it basically allows the attacker to force my browser to submit a valid authenticated request to your application, for instance to transfer money or to change my password. If this is hosted on your site, he can anonymously attack any vulnerable application - including yours. (Note that even if other applications are vulnerable, its not your fault they get attacked, but you still dont want to be the exploit host or the source of the attack...). As far as your own site goes, it's that much easier for the attacker to change the users password on your site, for instance.