How to fix Veracode error for InnerHtml - c#

When running Veracode, it generated a bunch of errors pointing to the lines with InnerHtml.
For example, one of those lines is:
objUL.InnerHtml += "<tr><td></td><td class=\"libraryEdit\">" + HttpUtility.HtmlEncode(dtitems.Rows[currentitem]["content"].ToString()) + "</td>";
What do alternatives exist to fix it without using html server controls?

What exactly are you trying to do, and what exactly does Veracode say?
Most likely, it is complaining that you could end up with an arbitrary code injection vulnerability if the data passed into your InnerHtml is untrusted and could contain malicious JavaScript.
The tool may not complain if you manually construct the DOM elements using the JavaScript createElement function to build each DOM element manually.

I have faced this issue in my ASP.NET Webforms application. The fix to this is relatively simple.
Install HtmlSanitizationLibrary from NuGet Package Manager and refer this in your application.
At the code behind, please use the sanitizer class in the following way.
For example if the current code looks something like this,
YourHtmlElement.InnerHtml = "Your HTML content" ;
Then, replace this with the following:
string unsafeHtml = "Your HTML content";
YourHtmlElement.InnerHtml = Sanitizer.GetSafeHtml(unsafeHtml);
This fix will remove the Veracode vulnerability and make sure that the string gets rendered as HTML. Encoding the string at code behind will render it as 'un-encoded string' rather than RAW HTML as it is encoded before the render begins.

Related

How to include CDATA parameter into a C# soap call

I have a soap client and in order to make a call to a service of my company I need, among others, a parameter containing a CDATA string.
Simple version of the C# code I have is the following:
ServiceRef.GetArraySoapClient client = new ServiceRef.GetArraySoapClient();
String codes = #"
<Codes>
<Code><Batch>AAA</Batch><Item>YYY</Item></Code>
<Code><Batch>BBB</Batch><Item>XXX</Item></Code>
</Codes>";
client.GetArray("uname", "pword", "<![CDATA[" + codes + "]]>");
When I did the same using SoapUI, it works. But within the C# code, it gives me an error that goes like "error in the format of Code items".
I don't understand what is wrong with defining CData like this?
Okay, apparently I don't need to add something special before and after 'codes' while sending the request.

watin not working with live.com

I am trying to use watin to mimic login to live.com using c#. code is below.
IE myIE = new IE("http://login.live.com/");
myIE.TextField(Find.ByName("login")).TypeText("abc#abc.com");
myIE.TextField(Find.ByName("passwd")).TypeText("1234");
myIE.Button(Find.ByValue("Sign in")).Click();
However it always failed to find the textfield:
WatiN.Core.Exceptions.ElementNotFoundException: Could not find INPUT (hidden) or INPUT (password) or INPUT (text) or INPUT (textarea) or TEXTAREA element tag matching criteria: Attribute 'name' equals 'login' at http://login.live.com/
The sample code in home page of http://watin.org/ works fine for www.google.com.
Did I miss something or is there anything special on http://login.live.com that prevents watin to work?
PS: I am running windows 7 64bit. VS 2008 with .net 3.5
You're hitting issues because the email field you're trying to type in is an HTML5 element.
Create the TextFieldExtended class as defined in this SO question: WatiN support for HTML5 tags
Then your code will be like the below:
ie.GoTo("http://login.live.com/");
ie.ElementOfType<TextFieldExtended>(Find.ByName("login")).TypeText("thisismyusername#here.com");
ie.TextField(Find.ByName("passwd")).TypeText("thisismypassword");
ie.Button(Find.ByValue("Sign in")).Click();
Tested on Watin2.1, IE9, Win7-64.
You may want to try this: I got it to work on my end:
ie.Div(Find.ByCustom("innertext","someone#example.com")).Click();
ie.TextField(Find.ById("i0116")).TypeText("hello");
ie.TextField(Find.ById("i0118")).Click();
ie.TextField(Find.ById("i0118")).TypeText("Hello!");
I recommend using this test Recorder. It will give you the elemnt names to use in your source:
http://www.codeproject.com/Articles/19180/WatiN-Test-Recorder
Edit:
I was also able to get this to work when finding by divID.
ie.Element(Find.ById("idDiv_PWD_UsernameExample")).Click()

Calling javascript from codebehind c# & Asp.Net

Am unable to understand why Cannot the below javascript code is not called from code behind
I have a simple javascript block like this
function callsCox(res) {
alert(res);
}
From my code behind :
....
string res="COX23";
string script = String.Format("callsCox({0})", res);
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Cox",script,true);
Am I missing anything? There aren't any exceptions or errors.
Page.ClientScript.RegisterStartupScript looks OK to me (might have missed something). Things to try
Add apostrophes to the call - it's coming through as an object. Try as a string
string script = String.Format("callsCox('{0}')", res);
Is the string script Page.ClientScript.RegisterStartupScript being called after an update panel partial postback. That could effect it
I have know functions not been found if they are in the same page. Try moving to an external js file. Don't asked me why this has resolved issues but it has a couple of times in the past for me.
Just for debug purposes take the function out of the equation all together, Try to get the alert working like this. It will at least isolate the problem if it does work
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Cox","alert('Does this work?')",true);
View the source of the page. Is the function even written into the page (or alert from point 4). It should be. If you put a breakpoint on the this.Page.ClientScript.RegisterStartupScript method is it being hit? Seems like it might not be.
Apologies for not giving you a 'hey this is the solution' type of answer. I've had stuff like this in the past and I've found it a matter of stripping things down until the problem has been isolated. Someone else may be able to spot an immediate problem of course. Good luck.
This works for me:
public static void ShowAlert(Page page, String message)
{
String Output;
Output = String.Format("alert('{0}');",message);
page.ClientScript.RegisterStartupScript(page.GetType(), "Key", Output, true);
}

HtmlHelper.Button(..., string onClickMethod, ...) HTML-encodes single-quotes!

I'm upgrading an old project from MVC 1.0 to MVC 3.0 (yes, it's that old), and I've run into an issue where calling HtmlHelper.Button(..., onClickMethod, ...) HTML-encodes single quotes into '
I can see how this would not be an issue if onClickMethod was just the name of a method to be called in javascript, however this is how we are using it:
return helper.Button(name, buttonText, HtmlButtonType.Button,
string.Format("window.location='{0}'", url));
which obviously is now broken.
Is there any way to bypass this encoding? I can see hacking it by changing the return type of the method to string, and doing:
return string.Format(helper.Button(name, buttonText, HtmlButtonType.Button,
"window.location={0}").ToString(), "'" + url + "'");
but this is more or less a hack, and not elegant.
Having the ' should work. Even though the document stream contains the encoded value the browser unencodes it when it builds the DOM. You can use a DOM inspection tool to see yourself.
If I put the following on a page I see the alert box just fine upon click:
<input type="button" onclick="alert('Hello');" />
You can use the URI class to convert html codes into regular text
Uri.UnescapeDataString(string);

Generating JavaScript in C# and subsequent testing

We are currently developing an ASP.NET MVC application which makes heavy use of attribute-based metadata to drive the generation of JavaScript.
Below is a sample of the type of methods we are writing:
function string GetJavascript<T>(string javascriptPresentationFunctionName,
string inputId,
T model)
{
return #"function updateFormInputs(value){
$('#" + inputId + #"_SelectedItemState').val(value);
$('#" + inputId + #"_Presentation').val(value);
}
function clearInputs(){
" + helper.ClearHiddenInputs<T>(model) + #"
updateFormInputs('');
}
function handleJson(json){
clearInputs();
" + helper.UpdateHiddenInputsWithJson<T>("json", model) + #"
updateFormInputs(" + javascriptPresentationFunctionName + #"());
" + model.GetCallBackFunctionForJavascript("json") + #"
}";
}
This method generates some boilerplace and hands off to various other methods which return strings. The whole lot is then returned as a string and written to the output.
The question(s) I have are:
1) Is there a nicer way to do this other than using large string blocks?
We've considered using a StringBuilder or the Response Stream but it seems quite 'noisy'. Using string.format starts to become difficult to comprehend.
2) How would you go about unit testing this code? It seems a little amateur just doing a string comparison looking for particular output in the string.
3) What about actually testing the eventual JavaScript output?
Thanks for your input!
We created a library specifically for the purpose of embedding JavaScript in a fluent-like syntax into our C# code, and then made it open source.
Have a look at Adam.JSGenerator.
I typically try to create a separate .js file for most/all of my javascript code. Usually I will need to have common bahvior applied to many elements that are dynamically created by ASP controls or server-side code, so I may not be able to code everything into a .js file.
I've found that the main reason that you want to generate javascript on the server is because you won't know the IDs of elements until the page renders. Therefore, I try to condense that dependency down as much as possibly so that I'm generating as little javascript as possible. For example, in traditional ASP.Net (not MVC) if I were rendering a set of forms such as in the example, each with multiple fields, then I would probably have something in the code behind such as this:
protected void FormRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Control form = e.Item.FindControl("MyForm");
ClientScript.RegisterStartupScript(this.GetType(), "prepareForm_" + form.ClientID, #"prepareForm('" + form.ClientID + "');", true);
}
A separate .js file would include the definition of the prepareForm function, which would be something like this:
// define a formPresenter "class" that encapsulates the behavior for a given form
function formPresenter(formId) {
this.setFirstName = function(value) {
$("#" + formId + "_FirstName").val(value);
}
this.setLastName = function(value) {
$("#" + formId + "_LastName").val(value);
}
// create other functions to handle more complicated logic
// clear fields
this.clearInputs = function() {
this.setFirstName("");
this.setLastName("");
//...
}
// receive Json object
this.handleJson = function(json) {
this.clearInputs();
// populate fields with json object
this.setFirstName(json.FirstName);
this.setLastName(json.LastName);
//...
}
// "constructor" logic
}
function prepareForm(formId) {
// create a new formPresenter object and shove it onto the specified element as the "presenter"
document.getElementById(formId).presenter = new formPresenter(formId);
}
Now almost all of your actual logic is in its own .js file, which should be much easier to maintain. If you need to access the formPresenter object for a given form, then you just need to get a reference to whatever element is referenced by the formId parameter and access the presenter variable:
"document.getElementById(" + form.ClientID + ").presenter.handleJson(json);"
Note: Since I've been using JQuery, I've found less of a need to even include any javascript generated by the server. Typically I can find the elements that I need by looking for a specific CSS class name (or something to that effect) and perform whatever setup/initialization I need.
We're doing a lot of JS generation in our project as well, and we're using StringBuilder to do it.
StringBuilder sb = new StringBuilder();
sb.Append("some javascript stuff")
.Append("some more")
.AppendFormat("formatted stuff {0}", "here");
return sb.ToString();
It's not pretty, but no solution is going to be.
And concerning testing, we don't actually do any unit tests on the generated code. Before release people go and test all the features to make sure they work as expected.
If you don't care about super duper performance you could use a templating language to generate the javascript.
Then for unit testing you would just fill the templates with their appropriate bindings/variables and then run it through a Javascript evaluator like Rhino or whatever the .NET equivalent is to at least test the syntax if not the actual JS code.
Other than that I would seriously question the design of software that is generating Javascript like this. It also looks like you are using JQuery but are referencing the $ directly which may lead to some problems down the line.
If compilers generating Javascript is one thing (ala GWT) but I would separate your client side JS code as much as possible from your .NET code (not to mention your .NET code looks like server side JS talk about confusing).
This in vogue kind of design of separating the client crap from the server is known as SOFEA. I let you google that.

Categories

Resources