Dangerous Request.Cookies value was detected from the client - c#

I am in quite the situation here at work as I´m all of a sudden starts getting this error:
An exception of type 'System.Web.HttpRequestValidationException' occurred in System.Web.dll but was not handled in user code
Additional information: A potentially dangerous Request.Cookies value was detected from the client (CustomerRegionName="&#214").
I know that there are several threads about this issue already, and I´ve tried all of the answers I have seen, the most common being the following:
Use
httpRuntime requestValidationMode="2.0"
in your web.config (keeping any attributes you already have on that element, if it's already there). ASP.NET4.0 ignores ValidateRequest otherwise.
Taken from: Here
I am building a website where most input is in Swedish, so to prevent browserproblems I encode all cookie values with the help of HttpUtility class.
That means that A value like "Örebro" will be encoded to something like this: %c3%96rebro.
And for some reason .net framework thinks that this is some kind of dangerous value.
I have absolutely no idea what to do here... Any help would be greatly appreciated.

To avoid this error, convert your string into a hexadecimal representation of the string. This can be done with code like this:
string ConvertedString = BitConverter.ToString(Encoding.Default.GetBytes(YourString));
Note that this string will have the hex separated into pairs with "-" (i.e., 4f-cc-12-ab).
When you read it back, restore it to the original string with code like this, assuming your read the encoded string back into string zBackInHex:
string zHex = (zBackInHex.Replace("-", "");
byte[] ba = new byte[zHex.Length / 2]; //One byte for each two chars in zHex
for(int ZZ = 0; ZZ < ba.Length; ZZ++){
ba[ZZ] = Convert.ToByte(zHex.Substring(ZZ * 2, 2), 16);
}
string zBackIn = Encoding.ASCII.GetString(ba); //The original string
I got the idea for this method from another post. I'd give credit, but I don't remember where I originally saw it.

Why don't you try to replace strings with IDs, that will remove all the hassle with encoding. Create lookup table with region ID, RegionName. Pass ID to your cookie, and there will be no problem with dangerous requests.

Related

FromBase64 string length must be multiple or 4 or not?

according to my understanding, a base64 encoded string (ie the output of encode) must always be a multiple of 4.
the c# Convert.FromBase64String says that its input must be a multiple of 4
However if I give it a 25 character string it doesnt complain
[convert]::FromBase64String("ei5gsIELIki+GpnPGyPVBA==")
[convert]::FromBase64String("1ei5gsIELIki+GpnPGyPVBA==")
both work. (The first one is 24 , second is 25)
[convert]::FromBase64String("11ei5gsIELIki+GpnPGyPVBA==")
fails with Invalid length exception
I assume this is a bug in the c# library but I just want to make sure - I am writing code that is sniffing strings to see if they are valid base64 strings and I want to be sure that I understand what a valid one looks like (one possible implementation was to give the string to system.convert and see if it threw - why reinvent perfectly good code)
Yes, this is a flaw (aka bug). It got started due to a perf optimization in an internal helper function named FromBase64_ComputeResultLength() which calculates the length of the byte[] result. It has this comment (edited to fit):
// For legal input, we can assume that 0 <= padding < 3. But it may be
// more for illegal input.
// We will notice it at decode when we see a '=' at the wrong place.
The "we will notice" remark is not entirely accurate, the decoder does flag an '=' if one isn't expected but it fails to check if there's one too many. Which is the case for the 25-char string.
You can report the problem at connect.microsoft.com, I don't see an existing report that resembles it. Do note that it is fairly unlikely that Microsoft can actually fix it any time soon since the change is going to break existing programs that now successfully parse bad base64 strings. It normally requires a major .NET release update to get rid of such problems, like it was done for .NET 4.0, there isn't one on the horizon afaik.
But yes, the simple workaround for you is to check if the string length is divisible by 4, use the % operator.

Simple ASP.NET password hashing class troubles

I am attempting to apply some security to a project I'm completing for college. This security is somewhat glancing so I'm tempted to give up, save passwords as plaintext or converted to base64, and do something more user-obvious.
Before I give up, I'm asking SO. This is my first attempt at asking anything here so please be gentle.
I decided that implementing this MSDN code wouldn't be too hard.
http://msdn.microsoft.com/en-us/library/aa545602%28v=cs.70%29.aspx
Turns out, it really is. I'm getting the error
System.FormatException: Input string was not in a correct format.
For code
binarySaltValue[0] = byte.Parse( salt.Substring( 0, 2 ), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture.NumberFormat );
I'm going to be honest, I don't fully understand this code.
What is SaltValueSize supposed to be? The provided code doesn't supply it, neither do any References. Also it's capitalised, so is it an object? Or a field in some object somewhere?
The variable "hash" is not defined anywhere, so I just filled it with new MD5CryptoServiceProvider(). Is this a mistake?
If I'm reading it right, the string "salt" is supposed to hold binary, but it doesn't at runtime, it has garbled text, meanwhile the line everything crashed at is trying to parse binary from "salt"? Why?
If anyone can fix this or supply an idiot-proof asynchronous hashing class I'd appreciate it.
( apologies for my random user name, I have no idea how that happened )
Here's a basic method (no salt) to at least get you started. It just "hashes" the string coming in.
private string GetHashedString(string _PW)
{
string _HashedPW = "";
SHA512 sha = new SHA512CryptoServiceProvider();
byte[] result;
StringBuilder strBuilder = new StringBuilder();
sha.ComputeHash(ASCIIEncoding.ASCII.GetBytes(_PW));
result = sha.Hash;
for (int i = 0; i < result.Length; i++)
{
strBuilder.Append(result[i].ToString("x2"));
}
_HashedPW = strBuilder.ToString();
return _HashedPW;
}

Reserved Symbol (&, /, etc) in URL Sharepoint Rest Query - Bad Request

One problem I have been facing off and on for the past few weeks was trying to search SharePoint for a list item value and kept getting bad request error. I had two symbols causing problems, one was that I could not search for something with anh & symbol, and the other was a / (forward slash).
My code looked like:
ServiceContext context = new ServiceContext(new Uri("http://URL/_vti_bin/listdata.svc"));
context.Credentials = CredentialCache.DefaultCredentials;
var requestType = (System.Data.Services.Client.DataServiceQuery<ListTypeValue>)context.ListType
.Where(v => v.Value.Equals(search));
After searching the internet, nothing valid came back besides saying change IIS settings, or convert it to ASCII Html value (NOTE: converting & to %27 still causes bad request error).
I would really not recommend using the combination of StartsWith and Length - performance could become a real issue in that case. Assuming you need a string key and that you want your keys to be able to contain special characters, Peter Qian has blogged about the best recommendation we can give. (This behavior actually comes from a combination of IIS and the .NET stack.)
Check out http://blogs.msdn.com/b/peter_qian/archive/2010/05/25/using-wcf-data-service-with-restricted-characrters-as-keys.aspx for more details, but your problem should be solved by turning off ASP.NET request filtering. Note that this has non-trivial security risks. Peter points out some of them, and security filtering tools like asafaweb.com will complain about this solution.
Long story short: if you can use integers or avoid the restricted characters in keys, your Web application will be more secure.
I found this article and it gave me an idea. I was going to try and use HEX, but since I am using a web service, I couldn't figure anything out. Finally I thought, hey, someone stated how they used substringof, why not try startswith!
Finally! A solution to this problem.
INVALID:
http://URL/_vti_bin/listdata.svc/ListType('Search & Stuff')
VALID:
http://URL/_vti_bin/listdata.svc/ListType() $filter=startswith(Value,'Search & Stuff')
I took it a step further since this could potentially return not what I wanted. I added length is equal to the strings length and it is working perfectly!
My C# Code looks like this now:
ServiceContext context = new ServiceContext(new Uri("http://URL/_vti_bin/listdata.svc"));
context.Credentials = CredentialCache.DefaultCredentials;
var requestType = (System.Data.Services.Client.DataServiceQuery<ListTypeValue>)context.ListType
.Where(v => v.Value.StartsWith(search) && v.Value.Length == search.Length);
Hopefully this helps someone else out and saves some hair pulling!
UPDATE:
After getting replies from people, I found a better way to do this. Instead of the standard LINQ method of querying, there is another option. See MSDN Article
System.Data.Services.Client.DataServiceQuery<ListTypeValue> lobtest = context.ListType
.AddQueryOption("$filter", "(Value eq '" + CleanString(search) + "')");
Now I will implement link posted from Mark Stafford and parse out reserved characters.

C# parse string "0" to integer

I have a new laptop at work and code that worked earlier in the week does not work today.
The code that worked before is, simplified:
while (dr.Read())
{
int i = int.Parse(dr.GetString(1))
}
Now it fails when the database value is 0. Sometimes, but not reliably, this will work instead:
while (dr.Read())
{
int i = Convert.ToInt32(dr["FieldName"]))
}
Am I missing something stupid?
Oddly enough, ReSharper is also having tons of weird errors with the same error message that I am getting with the above code: "input string was not in the correct format." (Starts before I even load a project.)
Any ideas? Anyone having any SP issues? I did try to make sure all my SPs were up-to-date when I got the machine.
EDIT: I understand how to use Try.Parse and error-handling. The code here is simplified. I am reading test cases from a database table. This column has only 0, 1, and 2 values. I have confirmed that. I broke this down putting the database field into a string variable s and then trying int.Parse(s). The code worked earlier this week and the database has not changed. The only thing that has changed is my environment.
To completely simplify the problem, this line of code throws an exception ("input string was not in the correct format"):
int.Parse("0");
EDIT: Thanks to everyone for helping me resolve this issue! The solution was forcing a reset of my language settings.
A possible explanation:
Basically, the problem was the
sPositiveSign value under
HKEY_CURRENT_USER\Control
Panel\International being set to 0,
which means the positive sign is '0'.
Thus, while parsing the "positive sign
0" is being cut off and then the rest
of the string ("") is parsed as a
number, which doesn't work of course.
This also explains why int.Parse("00")
wasn't a problem. Although you can't
set the positive sign to '0' through
the Control Panel, it's still possible
to do it through the registry, causing
problems. No idea how the computer of
the user in the post ended up with
this wrong setting...
Better yet, what is the output of this on your machine:
Console.WriteLine(System.Globalization.NumberFormatInfo.GetInstance(null).PositiveSign);
I'm willing to bet yours prints out a 0... when mine prints out a + sign.
I suggest checking your Control Panel > Regional and Language Options settings... if they appear normal, try changing them to something else than back to whatever language you're using (I'm assuming English).
I think it's generally not considered a good idea to call Convert.ToInt32 for the value reading out of database, what about the value is null, what about the value cannot be parsed. Do you have any exception handling code here.
Make sure the value is not null.
Check the value can be parsed before call Int32.Parse. Consider Int32.TryParse.
consider use a nullable type like int? in this case.
HTH.
Edit:
#Mike's response made me think that is extremely odd behavior and a simple google search yielded this result: int.Parse weird behavior
An empty string would also cause this issue.
You could check for dbnull before parsing, also it is good to validate parsed data.
You could use a default value and TryParse..
int i = -1;
if(!int.TryParse(dr["MyColumn"] as string, out i))
//Uh Oh!
Edit:
I posted this as a comment in #Chris' answer, but if the sql datatype is int then why not just use the GetInt32 method on the DataReater instead of retrieving it as a string and manual parsing it out?
Are you sure it's "0" and not "null"? What exception do you get?
EDIT:
Just out of curiosity, if it is really faulting on int.Parse("0"), can you try int.Parse("0", CultureInfo.InvariantCulture);?
Otherwise, post your query. Any joins?
you should check dr["FieldName"] != DBNull.Value and you should use TryParse if it passes the DBNull test...
if ( dr["FieldName"] != DBNull.Value )
{
int val = 0;
if ( int.TryParse( dr["FieldName"], out val ) )
{
i = val;
}
else
{
i = 0; // or some default value
}
}
I have seen this issue crop up with .NET Double class, parsing from string "0" as well.
Here's the really wacky part: you can get past the issue by using a different user account to run the program, and sometimes if you destroy and re-create the current user account on the machine, it will run fine.
I have yet to track this down, but you might get past it this way at least.
This is way out of left field, but check your localization settings. I had a number of "input string was not in a correct format" when I moved a web site to a Canadian server. The problem was in a DateTime.Parse method, and was fixed by setting the culture to "en-US".
Yes, your situation is different — but hey, you never know.
are you checking for null ?
if(!dr.IsNull("FieldName")){
int i = Convert.ToInt32(dr["FieldName"]))
}

C# Why won't this substring work? Error: Input string was not in a correct format

The problem is with the convert of the txt box value, but why?
string strChar = strTest.Substring(0, Convert.ToInt16(txtBoxValue.Text));
Error is: Input string was not in a correct format.
Thanks all.
txtBoxValue.Text probably does not contain a valid int16.
A good way to avoid that error is to use .tryParse (.net 2.0 and up)
int subLength;
if(!int.TryParse(txtBoxValue.Text,out subLength)
subLength= 0;
string strChar = strTest.Substring(0, subLength);
This way, if txtBoxValue.Textdoes not contain a valid number then subLength will be set to 0;
One thing you may want to try is using TryParse
Int16 myInt16;
if(Int16.TryParse(myString, out myInt16)
{
string strChar = strTest.Substring(0, myInt16);
}
else
{
MessageBox.Show("Hey this isn't an Int16!");
}
A couple reasons the code could be faulty.
To really nail it down, put your short conversion on a new line, like this:
short val = Convert.ToInt16(txtBoxValue.Text);
string strChar = strTest.Substring(0, val);
Likely the value in txtBoxValue.Text is not a short (it might be too big, or have alpha characters in it). If it is valid and val gets assigned, then strTest might not have enough characters in it for substring to work, although this normally returns a different error. Also, the second parameter of substring might require an int (not sure, can't test right now) so you may need to actually convert to int32 instead of 16.
What is the value of txtBoxValue.Text during your tests?
ASP.NET offers several validation controls for checking user input. You should use something like a CompareValidator or RegularExpressionValiditor in your WebForm if you're expecting a specific type of input, eg, an Integer.

Categories

Resources