I don't know if I am doing this right. I first time build something to prevent attack on page.
I will start from the bottom:
I have property:
public string Description {get;set;}
User can set it's value through tinyMCE
tinyMCE.init({
mode: "textareas",
theme: "advanced",
encoding : "xml"...
In controller before I save this in database I do:
model.Description = HttpUtility.HtmlDecode(model.Description);
In database I have a value like:
<p>bla bla bla</p>
I added AntiXSS library to my project:
public class AntiXssEncoder : HttpEncoder
{
public AntiXssEncoder() { }
protected override void HtmlEncode(string value, TextWriter output)
{
output.Write(Encoder.HtmlEncode(value)); // on breakpoint code always get in here
}
...
When I display data from database I use:
#Html.Raw(Model.Place.Description)
And it works fine I see only text. No Html tags. Breaklines work fine. I can style text with bold, italic etc.
But If I enter:
<script>alert(open to attack);</script>
I got alert window. I don't understand do I need to do something more to prevent this?
I added AntiXSS library to my project
And where are you using it?
Make sure that you have not only added AntiXSS but you actually used it:
#Html.Raw(Microsoft.Security.Application.Sanitizer.GetSafeHtmlFragment(Model.Place.Description))
But remember that the new version of the AntiXSS library is a bit too restrictive and will strip tags like <strong> and <br> out which might not be desired.
As an alternative to the AntiXSS library you could use HTML Agility Pack to do this job. Rick Strahl blogged about a sample implementation.
First off you are displaying RAW Html- not encoded in any manner.
If you want to display Html you should ideally be doing several things.
Sanitize it with the antixss Sanitizer class using GetSafeHtmlFragment.
Note that this wont protect you completely.
Do this before saving to the DB.
Implement the not yet fully supported headers to prevent other script from running. This is limited to only some of the modern browsers.
Or... Dont allow html or don't allow any HTML outside of known character tags. Ie a whitelist approach so you allow <strong> and nothing outside of other alphanumeric chars is allowed.
Related
In a Vaadin 14 application there is a Login form (com.vaadin.flow.component.login.LoginForm). The application uses LoginI18n (LoginI18n i18n = LoginI18n.createDefault();) and sets the texts (e.g. i18n.setAdditionalInformation("Some additional information");).
That works fine.
Now I want to add some HTML (contact details with an email anchor) into that additional information.
But putting plain HTML into that setter results in showing the HTML (with all its tags and so on) in the login form.
I guess that I could operate at the loginform by using getElement() and exchange text at the HTML elements. But as there is this I18n mechanism I think that it would be the right thing to use it, even for some HTML.
Is there some convenient way of using HTML in this case?
You can't.
As you could see in the Source code of LoginI18n additionalInformation is a simple string:
private String additionalInformation;
According to OWASP XSS page, one needs to use different XSS protection techniques for different contexts. However, in ASP.NET MVC Razor views, we only have the # sign to escape data in the context of HTML element inner content. What about HTML attributes, CSS, javascript contexts and others?
HTML element content
This is safe and will work as expected:
<div>#data</data>
HTML element attribute
This is not safe and can be exploited:
<div style="background: #color"></div>
JavaScript
While this is not safe:
<script>
var value = #value;
</script>
Safe solution is:
<script>
var value = #Json.Encode(value);
</script>
CSS
This is not safe and can be exploited:
<style>
.box { background : #color; }
</style>
A great thing about razor is that it does all the HTML encoding by default. Unless you use #Html.Raw(), it is pretty difficult to make your page vulnerable. You generally have to explicitly make variables render as html.
You also have Html.Encode() if you need it. There is also HttpUtility.JavaScriptStringEncode()
Regarding the updated vulnerable code:
#{var js = "alert(1);";}
<script>var value = #js</script>
I think you would be violating rule 0 with this code. You are inserting arbitrary strings into a script tag, and expecting it not to be executed. I actually get a syntax error (warning) with your example, but it will still run. If you wrapped it in quotes, you would be safe.
#{var js = "\"alert(1);";}
<script>var value = "#js"; alert(value);</script>
output:
"alert(1);
Notice that the quote that I put in the string gets escaped to ", making me unable to break out of the string, so I cannot inject js.
I'd be interested to see if someone has a way of sanitizing this without putting it in quotes, but I am skeptical.
update 2:
Dealing with CSS
The examples you give are not about escaping strings, it is more about inserting untrusted CSS into your page. To do that, you will need something that can parse CSS. For example, it is not that you want the value to be encoded, you just want it not to include the dangerous stuff like url(javascript:), behavior, binding, etc. You'll need a CSS filtering tool for that.
HTML attributes
you are safe if you do this:
<div data-color="#color"></div>
Since razor encodes quotes, you won't be able to terminate the string early. That's as simple as it is to prevent XSS (barring some unknown vulnerability in razor). Your Json.Encode() uses the same idea.
BUT, you are doing somehting risky if you do this:
<div #attribute></div>
Again, it's not that you need an escaped string here, you want something that filters your attributes on any dangerous content. The fact is, that doing things this way is really messy, and I would advise against it. It is bad design because it is screwing up your separation of concerns and making it hard to secure your app from XSS. What you should do instead is add CSS classes if you want to change the style. If you need to set an attribute based on a variable in razor, use something else rather than injecting it into your HTML and hoping to filter it.
ex:
#{
var disabled = isDivDisabled ? "disabled" : "";
}
<div #disabled><div>
I wish to create an MVC wrapper around jqPlot.
I want to have a helper object to render the required html container element and the required java scripts to draw the chart.
Something that will look like this:
#Html.jqPlot()
.ChartType(eChartTypes.PieChart)
.ChartData(someData)
.RenderChart();
Now I'm only at the initial design phase and I know what the jqPlot object should look like to achieve that, the problem I'm having is with the java script that suppose to be emitted to draw the actual chart using jqPlot.
Suppose I will render the following script in my .RenderChart() method
public string RenderChart()
{
string chartCode = string.format(#"
<script type="text/javascript" src="../src/plugins/jqplot.canvasTextRenderer.min.js"></script>
<script type="text/javascript" src="../src/plugins/jqplot.canvasAxisLabelRenderer.min.js"></script>
$(document).ready(function(){
var plot1 = $.jqplot ('{0}', [{1}]);
});
",this.ChartGuid, this.ChartData);
return chartCode;
}
The above is not actual code but just a general representation of the idea.
So the problem is that i don't want the Helper to emit the JS code into the body of the Html document, furthermore i cannot let it do that becuse some of the required scripts may be at the bottom of the html (as the best practice states).
Any suggestions ?
What would be the best way to emit JS code using an HTML helper if the situation requires it (like this one) ?
I think, listening to an even will be a possible solution, in this case the even of outputting or finishing the rendering of the footer. so maybe your code will give as an option to listen to an event and render at that moment, but this is of course platform dependent. I also worked on a php wrapper you can fork it here: https://github.com/oumsofiane1/jqplotPHPwrapper.git
and just implemented a helper, but of course you can extend that :-)
Hope this helps
With a grails app and from a local database, I'm returning some text in a xml format.
I can return it well formed in a <textarea></textarea> tag with the correct indenting (tabulation, line return,...etc.)
I want to go a bit further. In the text I'm returning, there are some <img/> tags and I'd like to replace those tag by the real images themselves.
I searched around and found no solution as of now. I understood that you can't add an image to a textarea (other then in a background), and if I choose a div tag, I won't have the indenting anymore (and therefore, harder to read)
I was wondering if using a <g:textField/> or an other tag from the grails library will do the trick. And if so, How can I append them to a page using jquery.
For example, how to append a <g:textField/> in jquery. It doesn't interpret it and I get this error
SyntaxError: missing ) after argument list [Break On This Error]...+doc).append("<input type="text" id="FTMAP_"+nb_sec+"" ...
And in my javascript file, I have
$("#FTM_"+doc).append("<g:textField id='FTMAP_"+nb_sec+"' ... />
Any possible solutions ?
EDIT
I did forget to mention that my final intentions are to be able to modify the text (tags included) and to have a nice and neat indentation so that it is the easiest possible for the end user.
You are asking a few different questions:
1. Can I use a single HTML tag to include images inside pre-formatted text.
No. You will have to parse the text and translate it into styled text yourself.
2. Is there a tag in the grails standard tags to accomplish this for me?
No.
3. How can I add grails tags from my javascript code.
Grails tags are processed on the server-side, and javascript is processed on the client. This means you cannot directly add grails tags via javascript.
There are a couple methods that can accomplish the same result, however:
You can set a javascript variable to the rendered content of a grails tag. This solution is good for data that is known at the time of the initial request.
var tagOutput = "${g.textField(/* etc */)}";
You can make an ajax request for the content to be added. Then your server-side grails code can render the tags you need. This is better for realtime data, or data that will be updated more than once on a single rendered page.
I am using FckEditor in Create.aspx page in asp.net mvc application.
Since I need to show rich text in web pages, I used ValidateInput(false) attribute top of action method in controller class.
And I used Html.Encode(Model.Message) in Details.aspx to protect user's attack.
But, I had result what I did not want as following :
<p> Hello </p>
I wanted following result not above :
Hello
How can I show the text what user input?
Thanks in advance
The short answer is that HTMLEncode is making your markup show like that. If you don't HTMLEncode, it will do what you want.
You need to think about whether or not you need full control of markup, who is entering the markup, and if an alternative like BBCode is an option.
If your users using the editor are all sure to be 'safe' users, then XSS isn't likely to be as much a concern. However, if you are using this on a comment field, then BBCode, or something like SO itself uses is more appropriate.
You wont be able to use a WYSIWYG editor and do HTMLEncode though... (without BBCode, or some other token system)
It seems the user entered "<p> Hello </p>" (due to pressing Enter?) into the edit control, and it is displaying correct in the HTML as you have done an Html.Encode. E.g. the paragrahs are not rendered, they are outputted as "<p>..</p>" as the string is HTML encoded into something like "<p> Hello <p>".
If you do not want tags, I would suggest searching the text string for tags (things with <...>) and removing them from the inputted text. Do this before HTML.Encode.
...or am I missing something?
You can use HttpServerUtility.HtmlEncode(String)