ASP.Net - A potentially dangerous Request from submitting HTML data - c#

I'm working on a web form which works in a following way.
Read email template from database
Display email template on a web form in HTML format
User adds additional information to the web form and clicks on submit button
Before I get to a method which will process that request, I get A potentially dangerous Request.Form
I have looked at few articles that advise using .Net 2.0 in one of the web.config sections - that didn't work. I have set requestValidation = "false" for that page and it didn't work either.
My gut feeling is that I'm doing something fundamentally wrong...
HTML template is stored as VarChar(4000) in a database.
I have tried encoding text in a method before I send an email, but that didn't work either because the web form never got to executing that method.
What other options do I have? I have tried storing plain text in database, but then I have issue of tabs and returns etc.
Thank you

The remedy is in two parts and you MUST action both:
To disable request validation on a page add the following directive to the existing "page" directive in the file (you will need to switch to the HTML view for this):
ValidateRequest="false"
for example if you already have:
<%# Page Language="vb" AutoEventWireup="false"
Codebehind="MyForm.aspx.vb"
Inherits="Proj.MyForm"%>
then this should become:
<%# Page Language="vb" AutoEventWireup="false"
Codebehind="MyForm.aspx.vb"
Inherits="Proj.MyForm"
ValidateRequest="false"%>
In later versions of Visual Studio the value of this property is available via the page properties, so simply set "ValidateRequest" to "False". Either method of setting this achieves the same result.
Alternately, you can globally turn request validation off (but in which case be sure to implement item two below). To globally turn request validation off add the following to your web.config file:
<pages validateRequest="false" />
From: http://www.cryer.co.uk/brian/mswinswdev/ms_vbnet_server_error_potentially_dangerous.htm

As a first security lesson, never trust user input,so if you setting request validation to false then always HTML encode the input.
In basic either use: OnClientClick on submit and replace, < with & lt; and > with & gt; (no space with & and gt/lt)
or on submit method, use Server.HTMLEncode(inputtext)..or however you process it.

Related

asp:HiddenField being cached server-side somewhere?

I have two ASPX pages; they use the same DLL and class, so the first line of each file looks like:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="CustomPage.aspx.cs" Inherits="CustomPageCode.CustomPage" %>
(maybe this is bad form to have two *.aspx pages sharing the same codebehind, but I don't want to have two separate classes with identical code)
I'm 'configuring' each page through a hidden field --
Page1.aspx has the line:
<asp:HiddenField ID="DepartmentName" value="DepartmentOne" runat="server" />
and Page2.aspx has the line:
<asp:HiddenField ID="DepartmentName" value="DepartmentTwo" runat="server" />
My CodeBehind reads DepartmentName.Value to do a bunch of codebehind things, like SQL queries, based on the value of the HiddenField specific to each department, and also Javascript reads that value to do department-specific things as well. I'm doing it this way to simplify configuring each page -- the way the page is configured is right there in the ASPX page and the same value is visible to both ASPX and Javascript.
However, if either page does a POST event -- now DepartmentName.Value ONLY returns the value from the page that did the POST for any page with the same codebehind. Page1.ASPX, even though the asp:HiddenField value in the source is still clearly "DepartmentOne", if Page2.ASPX did the POST, DepartmentName.Value will be "DepartmentTwo" regardless of which page is opened.
The funky thing is: if I open the same page in Chrome, Page One will still have Page Two's DepartmentName.Value, even if the POST event never occurred in Chrome; clearing the IE cache doesn't fix it either. This is definitely something happening on the server side, getting cached somewhere. An IIS reset resolves it.
Google has told me that ASP.NET caches a bunch of things from a POST event but doesn't exactly say how it's handled, or how to enable/disable it, or which of the many cache locations it is located in, and many examples look like I'd have to specifically tell it to start caching things in a persistent way. The closest thing I've found is ModelState.Clear(); in a !IsPostBack at the beginning of the Page_Load, but that doesn't resolve it, I'm not using MVC in my code as far as I know.
So, my question is, how do I force that the GET uses the hidden value in the source code, and not some cached value from an old POST event?
It's probably ViewState, but I'd have to see more of your code for this to be more than a wild guess. I do see this:
I don't want to have two separate classes with identical code)
Yep, that's a good thing. But it sounds like maybe you have too much code in the page class itself that should be moved to a separate utility class, where two separate pages can now share that same utility code. Alternatively, you want a single Department.aspx page that takes a URL argument, like this: /Department.aspx?deptid=Department1 or /Department.aspx?deptID=Department2
Then key off of the url argument, rather than a hidden field. If you don't like the ugly URL, you can use routing to get prettier URLs like this: /Departments/Department1 or /Departmennts/Department2
I discovered my problem:
After wrestling with ViewState, it turns out my problem wasn't hidden fields being cached, it was what was being done with the hidden fields.
At the beginning of my class, I have a variable:
public static Dictionary<string, string> ThisDictionary = new Dictionary<string, string>();
that my code uses ThisDictionary.Add() to add values from ASPX hidden fields to -- but I never declared ThisDictionary as 'new' in my actual function, so every time I added an element to the Dictionary of hidden fields, it was persistent across multiple pages using the same class.
So, when I load my values from what I think is the hidden field, the codebehind is reading the hidden field correctly, but when it takes action in C#, it is using the data in the Dictionary with a bunch of other pages' data in it, hence the appearance that hidden field values are being cached somewhere.
By adding a statement to declare it as a new Dictionary<string,string>() at the beginning of my Page_Load function, it now wipes the dictionary clean with each page load and now it's behaving how I would expect, containing only values from the hidden fields on the particular page.
(I acknowledge what I should probably do is have a separate class with these variables in it, rather than lumping it all into the main ASPX class that gets called when the page loads. Something for the next version)

Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventvalidation =”true” %>

I am getting the below detailed error:
Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventvalidation =”true” %> in a page. For security purpose, this feature verifies that arguments to postback or callback events originate from the server that originally rendered them.
I am having a webpart page with a webpart where i do have a UPdatePanel and a button Upon Button click i am getting this error.
the same package(wsp) which we are using in one of our environment is working fine and the same is not working in another environment.
Help in this is highly appreciable.
Without code it will be incredibly difficult to diagnose your issue.
You mentioned that your utilizing an Update Panel, which in essence will automatically store your page in memory, then it will render the proper Ajax to hide the Postback. The Microsoft Developer Network (MSDN) basically warns you when you use the EnableEventValidation with Client-Side modification.
If you write client script that changes a control in the client at run
time, you might have to use the RegisterForEventValidation method in
order to avoid false event validation errors.
Also if you initialize out of your web.config and directly in code, you should ensure that you call the validation before the page has been initialized. So I would potentially use:
protected void Page_PreInit()
{
// Before Page Initialization
}
Which would potentially eliminate any errors from the front-end, without code can't be of more assistance.
Ok without some code to go on I'll fire some rounds off into the dark, I know next to nothing about SharePoint so I maybe missing something obvious here:
Firstly, check your environments, one may have a different web.config which has EnableEventValidation set to false.
Secondly on Page_Load are you doing any DataBind? Depending on whatever your code is doing you may need make sure it's not binding on PostBack - or if it is already; try binding on PostBack.
Thirdly; any html or < > characters being included anywhere in the form? Also line breaks in data (my memory is a bit hazy on this one) I seem to remember, something like:
<option value="
my value
">select this</option>
Could cause it too. So doing a Trim() on data is recommended.
Lastly: Tag bleed out, check none of your tags are unclosed, something like <span <asp:TextBox [...] /> this could be the cause too.
add EnableEventValidation="false" in page directive <%# Page EnableEventValidation="false" %>

Asp.Net Invalid postback or callback argument.

I am receiving this error when I click on the button to log into Facebook from my website.
Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
When searched Google and found these two links so I can understand the error message. However they did not fix the problem.
asp.net: Invalid postback or callback argument
http://blogs.msdn.com/b/amitsh/archive/2007/07/31/why-i-get-invalid-postback-or-callback-argument-errors.aspx
So I took apart the page section by section until I found what was causing the error. It was this:
iframe name="ContentIFrame" class="IFrameStyle"
When I delete the iframe, everything works. However, I need the iframe on the page. Can anyone assist why the iframe is causing this error? It has nothing to do with Postback.
While I have seen suggestions to disable event validation (setting EnableEventValidation=false), I do not recommend that approach as it could create security problems. In my case, what resolved the problem was to use an asp:PlaceHolder instead of directly placing the iframe into the ASPX. Then, in the C# code, I add a new HtmlIframe control to the placeholder's ControlCollection:
Place the following in the ASPX:
<asp:PlaceHolder runat="server" ID="myPlaceholder" />
Then, place the following in the postback handler:
using System.Web.UI.HtmlControls;
HtmlIframe newIframe = new HtmlIframe();
newIframe.Src = "somewhere/some_page.html";
myPlaceholder.Controls.Add(newIframe);
An alternative is to place the iframe directly into the ASPX and to set the HTML element as runat="server". Once runat="server" has been set, you should be able to access the control's ID from within your code to set the src attribute.

How do I insert html tags/script to sql as a text?

I'm trying to work on a 'practice' app wherein the textbox value will be inserted to the database.
What happen is that when I insert the textbox.text value.
Ex. text =
<script>alert('Hello')</script>
I get an error: A potentially dangerous Request.Form value was detected from the client (TextBox1="alert('XSS')...").
I'm already using sql parameters so values like ' " /// \\ are not a problem as of now.
Set ValidateRequest="false" for your page, for allowing html.
At page level:
<%# Page Language="c#" ValidateRequest="false" AutoEventWireup="false" CodeBehind="TestPage.aspx.cs" Inherits="TestPage" %>
Also, for ASP.NET 4.0, you need to add the following to your web.config:
<httpRuntime requestValidationMode="2.0" />
If is only for testing purposes you may disallow ASP.NET validator so it will stop looking for HTML/XML tags that could be potentially dangerous. To do that, set ValidateRequest to false in your aspx page.
<%# Page Title="" Language="C#" ValidateRequest="false"
This is not recommended for production environments but in your case can do the trick. More info in the following MSDN Link
It's not a (potential) sql problem that asp.net is warning about. When you accept that value and later show it in your page without encoding, then that unwanted script will fire.
At this moment it will show a harmless alert, but if you allow any user to type in these values then who knows what will happen.
You can just insert the tag broken in a concatenate string. like in:
Insert into table values('<'+'h2'+'>'+'Another One'+'<'+'/'+'h2'+'>')

ASP.net not posting back to correct page

So I have a slightly unorthodox application type.
I have an aspx page called AddNewBlog.aspx. This page generates XML data from database queries and it include the file AddNewBlogXSL.aspx which is an xsl style sheet.
The effect is that the AddNewBlog XML data is transformed by AddNewBlogXSL on the client side into XHTML.
So although the requested page is AddNewBlog.aspx, the layouts and controls and forms are on AddNewBlogXSL.aspx since it contains all the layout and formatting.
When on AddNewBlogXSL.aspx I do an asp:button it tries to post back to AddNewBlogXSL.aspx as is understandable.
The problem is that page is an xslt stylesheet not a webpage.. I need it to post back to AddNewBlog.aspx as this is the proper page which includes AddNewBlogXSL.aspx
The only thing I seem to be able to do is allow the default behaviour which is to submit to AddNewBlogXSL.aspx, process the page, and redirect them to the proper page AddNewBlog.aspx but then it makes it hard to handle error messages and such since I have no control over AddNewBlog.aspx after I have simply redirected to it from AddNewBlogXSL.aspx
Any ideas at all?
You are looking for PostBackUrl property.
<asp:button id="Button2"
text="Post value to another page"
postbackurl="~/Path/To/AddNewBlog.aspx"
runat="Server">
</asp:button>
EDIT:
To address your comment, IsPostBack will not be true in this scenario because it isn't a postback, it's just a post to another page. You have to access the values via the Page.PreviousPage property as outlined in the MSDN article I listed.
During a cross-page postback, the contents of the source page's controls are posted to the target page, and the browser executes an HTTP POST operation (not a GET operation). However, in the target page, the IsPostBack property is false immediately after a cross-page post. Although the behavior is that of a POST, the cross-posting is not a postback to the target page. Therefore, IsPostBack is set to false and the target page can go through its first-time code.
Also per MSDN, you would check the PreviousPage.IsCrossPagePostBack property instead of the Page.IsPostBackProperty
if(PreviousPage.IsCrossPagePostBack == true)
{
//Get values from PreviousPage
text = ((TextBox)PreviousPage.FindControl("TextBox1")).Text;
}
Cross Page Posting Details
I went ahead and wrote a little test harness (aka, I took the example off the MSDN page, :-0 )to verify and results are as follows when cross page posting:
It's not an ideal situation and it kludgey to access your values as listed, but for the model you have designed, it's the best I can think of.
In addition to the above answer, Can you please confirm that the "AutoEventWireUp" is false in this page. If so, override the page load method in this case.

Categories