I have created a textbox for my users to enter their comments. So, sometimes they copy the error that has been raised in the application and paste in the textbox along with comments. It may include illegal characters (eg. </11>) but it should be saved but my .aspx is not allowing. I don't know how to handle this. thanks!
If you want user to edit TextBox and enter html tags you can disable this via
<%# Page validateRequest="false" ...>
or in the web.config for your entire application:
<system.web>
<page validateRequest="false" />
</system.web>
Note that this ValidateRequest property is not existing without
reason. When you change its default value, insecure input will be
accepted. Because of that, you need to validate every user's input to
avoid cross-site scripting attacks, like inserting of malicious
JavaScript, ActiveX, Flash or HTML
Another smart solution is to replace via javascript text written by user to make it safe for validation.
< anyword> , instead of <anyword> is considered safe!
function validateTxt() {
$("textarea, input[type='text']").change(function () {
html = $(this).val(); //get the value
//.replace("a" , "b") works only on first occurrence of "a"
html = html.replace(/< /g, "<"); //before: if there's space after < remove
html = html.replace(/</g, "< "); // add space after <
$(this).val(html); //set new value
});
}
$(document).ready(function () {
validateTxt();
});
i assume you are talking about an exception message like "A potentially dangerous Request.Form value was detected from the client..."
that is the asp.net request validation in action. this can be disabled at the page or site level, but there are risks associated with doing so.
it is done with ValidateRequest="false" in the page directive or in web.config.
more information here:
http://www.asp.net/learn/whitepapers/request-validation
You can try to encode the content in Base64 before transferring it. But i'm not sure my solution is really good.
http://nolovelust.com/post/classic-asp-base64-encoder-decoder.aspx
It could be due to the HTML being rejected server-side, as a security precaution.
You can disable this check by either:
Adding the following attribute to the page header <%# Page validateRequest="false" %>
or making the change application wide in the Web.Config:
<configuration>
<system.web>
<pages validateRequest="false" />
</system.web>
</configuration>
Related
So, I know how to do it with one thing like br
cmd.Parameters.AddWithValue("#text", TextBox1.Text.Replace("\n", "<br/>"));
But how can I add multiple replacements to it? I've tried..
cmd.Parameters.AddWithValue("#text", TextBox1.Text.Replace("\n", "<br/>").Replace("\b", "<b/>"));
But it does not work, gave me an error back
#Edit
the error I got
A potentially dangerous Request.Form value was detected
this is what I had inside of the textbox
test</b>
If you want to have your textbox value like this, you could try adding <httpRuntime requestValidationMode="2.0" /> to your web.config. Or maybe adding <pages validateRequest="false" /> to the <system.web> block inside your web.config would help you get rid of the error message.
Btw. if you want to replace </br> with \n you're doing it the wrong way. .Replace("\n", "</br>") replaces \n with </br>.
It seems to me you simply need to disable validation. Add this to the top of your aspx page:
<%# Page validateRequest="false" %>
Bear in mind that this is default true to protect your page from script attacks. Read this for more information: http://www.asp.net/whitepapers/request-validation
But for what you are trying to do this should do the trick, although I would not recommend in an application where security is a concern.
edit
For completeness sake, I think you can do something else without disabling the validation.
HttpUtility.HtmlEncode(TextBox1.Text).Replace("\n", "<br/>").Replace("\b", "<b/>"));
By the way, I think the last Replace won't do anything to the example text you posted, but that's out of the scope of the question I suppose.
I have a textfield which displays a string which contains < and >. The code throws an error because of that. How can I allow the usage of those chars in my textfield?
Thanks :)
Problem is that when this gets posted to server, it will not work, doesn't matter what you try. This is the ASP.NET XSS protection, which can be disabled like so:
<%# Page ... ValidateRequest="false" %>
Trouble is, you'll have to be very careful validating all the postback yourself. Easier way is to escape all the contents of textbox using javascript just before posting. You can escape it using same HTML escaping, then unescape in server side code.
Update:
Example of escaping. This will flash the changed text on screen before postback - ideal solution is to use a hidden field for this, i.e. assign value to a hidden field, instead of that same field. This is the simplest version:
<script>
function EscapeField(){
document.getElementById("your client control ID").value =
escape(document.getElementById("your client control ID").value);
}
</script>
And in code-behind:
this.ClientScript.RegisterOnSubmitStatement(this.GetType(),
"EscapeField", "EscapeField();")
Update:
Again, warning - if you save HTML in your database like this, and then just display it to the client, you are directly vulnerable to XSS attacks. There are worms out there that will find and exploit your web site. Make sure you cleanse the HTML you are getting.
If you're in an asp.net page, you can wrap the whole of the output text in a
Server.HtmlEncode("YourTextWith<and>Characters")
function and it will encode any dodgy characters for you.
If, for some reason, you're doing this in a .cs file, you can use System.Web.HttpUtility.HtmlEncode("YourTextWith<and>Characters")
before passing it to the presentation layer.
Convert them to < and >. In Html, < is converted to < and > is converted to > without it thinking it's part of the markup. So the string <Blah> will be <Blah>.
Edit: I forgot, to automatically convert them and escape all HTML characters (so this isn't an issue for other things), in Asp.net you can use Server.HtmlEncode(string) to automatically convert all characters that could cause issues to their HTML equivalent.
The easiest solution is to disable request validation in single pages
<%# Page ... ValidateRequest="false" %>
but don't forget to enable requestValidationMode="2.0"
<system.web>
...
<httpRuntime requestValidationMode="2.0" />
</system.web>
This solution could espose some threats.
Another smart solution is to replace via javascript text written by user to make it safe for validation: <tag> is considere dangerous, but < tag> is considered safe!
A javascript replacement can solve the problem.
function validateTxt() {
$("textarea, input[type='text']").change(function () {
html = $(this).val(); //get the value
//.replace("a" , "b") works only on first occurrence of "a"
html = html.replace(/< /g, "<"); //before: if there's space after < remove
html = html.replace(/</g, "< "); // add space after <
$(this).val(html); //set new value
});
}
$(document).ready(function () {
validateTxt();
});
<asp:TextBox ID="TextBox1" runat="server"><</asp:TextBox>
I don't know if your question is related to this or if you are getting a validateRequest issue
You can either use the TextBox.Text property which will HTML-encode whatever you enter
<asp:TextBox ID="TextBox1" runat="server" Text="<>"></asp:TextBox>
or you can enter the html names for < and >.
<asp:TextBox ID="TextBox1" runat="server"><</asp:TextBox>
or you can enter the html codes
<asp:TextBox ID="TextBox1" runat="server"><</asp:TextBox>
for the name and code conversions, check out this chart.
your problem is,you cannot use html tags in .net controls. so set the ValidateRequest="false" in your aspx page and encode the text before you saving the text.
//encode
private string Encode(string text)
{
byte[] encodedText = System.Text.Encoding.UTF8.GetBytes(text);
return System.Convert.ToBase64String(encodedText);
}
when you retrieving your text make sure to decode the encoded text.
// Decode:
private string Decode(string encodedText)
{
byte[] decodedText = System.Convert.FromBase64String(encodedText);
return System.Text.Encoding.UTF8.GetString(decodedText );
}
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'+'>')
Is it possible to load a User Control that was registered in the web.config file, rather than in the aspx file?
Here is an example of what I would do. In my aspx:
index.aspx
<%# Register TagPrefix="module" TagName="ModExample" Src="~/controls/example.ascx" %>
index.cs
protected void Page_Load(object sender, EventArgs e)
{
controls_example exmp = LoadContent("controls/example.ascx") as controls_example;
myContentPanel.Controls.Add(exmp);
}
I had to register my user control in the page, or else ASP would not know what "controls_example" was. However, I know you can change your web.config to look like this:
<configuration>
<system.web>
<pages>
<controls>
<add tagPrefix="module" tagName="ModExample" src="~/controls/contentModule.ascx"/>
<add assembly="Subtext.Web.Controls" namespace="Subtext.Web.Controls" tagPrefix="module"/>
</controls>
</pages>
</system.web>
</configuration>
So, here is the problem. How do I create a variable of type "controls_example" when it has been registered in the web.config file?
Do I need to:
add a "using namespace"?
change/add something in my web.config?
not define what the datatype of the variable is? (I would love to avoid this)
something else?
Your web.config looks fine. In the page you need to add a using with the namespace of your control. Then you can use the page's LoadControl method to get an instance of your control that you can then add as a child control to some container (I usually choose a asp:Placeholder to ensure its position is where I want it)
#Adrian, here is my response to your question. I have to say it here, because I will run far over my char limit.
Ok, the first problem I had was that I was using a ASP.NET Website, not a ASP.NET Application. I chaged this so I was using the latter. This made it so that all pages created from then on had a namespace by default (being the name of the folder they were in). I do not know if you can register controls using a namespace in a website, maybe because websites don't have namespaces by default.
So let's say I made a Web User Control called myControl.ascx, and saved it as ~/controls/myControl.ascx. Looking at the ascx file, the top line should read:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="myControl.ascx.cs" Inherits="myApplication.controls.myControl" %>. myApplication is the name of your website, and you can seed it added controls to the namespace because that is the folder it is in. Also, if you look at the code behind, the namespace will match.
Now, from here you have 2 options on how to register and use the control. The slow way is to register each control you want to use on each page you have, which is good if you only have a few of each. To do this, write the following line in the page you want to call the control from (like the index page, for example):
<%# Register TagPrefix="myC" TagName="myCoolControl" Src="~/control/myControl.ascx" %>
That is the slow way, but it works (unless I typed something wrong).
Here is what I was trying to do: make it so I don't have to type this a thousand times, and only do it once in the web.config file.
Configure your web.config file to look like this:
<configuration>
<system.web>
<pages>
<controls>
<add tagPrefix="myCont" namespace="myApplication.controls" assembly="myApplication" />
</controls>
</pages>
</system.web>
</configuration>
This will automaticly register any control made in the "myApplication.controls" namespace, which, if you set things up correctly, is any control made in the "controls" folder. Just remember, you don't have to call the folder "controls" for this to work, you may have any namespace listed here and it should work just fine.
Now open up a page you want to load a control from programmatic (like index). You are NOT going to write anything in the aspx file, including anything about registering the page. The control is already registered, so all we have to do is load it in the code-behind:
myControl myCont = LoadControl("~/controls/myControl.ascx") as myControl;
//feel free to use the variable, or add it to the page with a panel or something
I really hope this answered your question. It did take some digging around on my end to get it to work, so I'm glad to help others out with this problem. Thanks again to CyberDude, who got me going in the right direction.
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.