Where to find or duplicate code that produces HttpRequestValidationException - asp.net

I have some PageMethods (static methods in a page marked with <WebMethod>) defined on some pages and call them using an ajax call. This POST to the server apparently doesn't trigger the ASP.NET code that would raise HttpRequestValidationException if the data sent is deemed possible XSS, so I'd like to duplicate that checking code to run it in my page methods.
Anyone know the details of that code or where I can find it? I looked in the MS AntiXss library, but it only does encoding, not actually checking input, AFAIK.
Edit: Or point me in the direction of code or a library that does some similar checking.

Analyzing the stack trace when a System.Web.HttpRequestValidationException is raised we can find out what code is throwing it.
System.Web.HttpRequestValidationException (0x80004005): A potentially dangerous Request.Form value was detected from the client (IdentifierTextBox="
at System.Web.HttpRequest.ValidateString(String value, String collectionKey, RequestValidationSource requestCollection)
Using Reflector we find that ValidateString is calling: RequestValidator.Current.IsValidRequestString, which in turn calls CrossSiteScriptingValidation.IsDangerousString which is:
internal static bool IsDangerousString(string s, out int matchIndex)
{
matchIndex = 0;
int startIndex = 0;
while (true)
{
int num2 = s.IndexOfAny(startingChars, startIndex);
if (num2 < 0)
{
return false;
}
if (num2 == (s.Length - 1))
{
return false;
}
matchIndex = num2;
char ch = s[num2];
if (ch != '&')
{
if ((ch == '<') && ((IsAtoZ(s[num2 + 1]) || (s[num2 + 1] == '!')) || ((s[num2 + 1] == '/') || (s[num2 + 1] == '?'))))
{
return true;
}
}
else if (s[num2 + 1] == '#')
{
return true;
}
startIndex = num2 + 1;
}
}

Related

Loop program if user enters wrong input

I just started learning C# and while loops are confusing me. Unlike Java, where I can use a while loop to loop a program if a user entered a invalid input, it's not acting the same way in C#.
using System;
namespace first {
class Program {
static void Main(string[] args) {
Console.WriteLine("Hi! What is your name");
string userName = Console.ReadLine();
Console.WriteLine("oh! you are:" + userName);
Console.WriteLine("let play a game");
string answer="Y";
while (answer == "Y") {
Random random = new Random();
int correntNumber = random.Next(1, 2);
int guess = 0;
Console.WriteLine("Guess a number");
while (guess != correntNumber) {
string userGuess = Console.ReadLine();
//validate input method 1
try {
guess = int.Parse(userGuess);
} catch (Exception e) {
Console.WriteLine("Invalid inout", e);
}
//validate input method 2
//if(!int.TryParse(userGuess, out guess)) {
// Console.WriteLine("invalid input");
//}
if (guess != correntNumber) {
Console.WriteLine("try again!");
}
}
Console.WriteLine("Yes! corrector");
Console.WriteLine("Play again?");
//string answer;
answer = Console.ReadLine().ToUpper();
if(answer == "Y") {
continue;
} else if (answer == "N") {
Console.WriteLine("bye");
return;
} else if (answer != "Y" || answer != "N") {
Console.WriteLine("y or n");
answer = Console.ReadLine().ToUpper();
continue;
}
}
}
}
}
When I enter a value other than y or n, the message appears,Console.WriteLine("Y or n only");, but the game restarts while it shouldn't.
I am sorry this is a simple and rather silly question, but I can't pin point where I am going wrong.
the problem is that after printing to the user "y or n only" message you take the input but you don't actually do anything with it
so the loop just restarts regardless of the input , to fix this issue you could replace the last if part with this code
while(answer != 'Y' && answer != 'N'){
Console.WriteLine("y or n only");
answer = Convert.ToChar(Console.ReadLine().ToUpper());
}
if(answer == 'Y')
{
continue;
}
else if(answer == 'N')
{
Console.WriteLine("goodbye");
return;
}
so after you read the first input answer of him for repeating or no you check if it's a valid input or not and if it's not you keep asking him for "y or n only" till he enters "Y" or "N" and then you process this answer for whether it's a "Y" or "N" in the if part

http request return value not getting all data flutter

I am working with http request. suddenly on my request, i was getting response status code as "200" so that my api is working.. but, upon my response body that return is incomplete. by the way, this is my resources used.
String APILink = "http://10.12.50.46:9191";
String compressedString2;
Future<SuccessData> getSession() async {
http.Response response2=await http.post(
Uri.encodeFull(APILink+"/Mobile/StartSession"),
headers:{
"Auth-Key":"InSys-dev-key-001 ",
},body:compressedString2,
);
print("Compressed JSON:"+compressedString2);
print(response2.statusCode);
var dataGather2 = json.decode(response2.body);
print(response2.body);
}
this is my actual responseupon using insomnia (Rest API)
and here is my print data upon my logcat:
if you notice, my return data upon "ResultSet" is not complete.. also the other data do be fetch like status, errormsg,and tag is not viewed.
Print function will not print everything
You can see print() statements in Flutter are truncated in flutter run output
https://github.com/flutter/flutter/issues/22665
Solution 1:
From https://github.com/flutter/flutter/issues/22665#issuecomment-580613192
You can use the following two code snippet
void logLongString(String s) {
if (s == null || s.length <= 0) return;
const int n = 1000;
int startIndex = 0;
int endIndex = n;
while (startIndex < s.length) {
if (endIndex > s.length) endIndex = s.length;
print(s.substring(startIndex, endIndex));
startIndex += n;
endIndex = startIndex + n;
}
}
https://github.com/flutter/flutter/issues/22665#issuecomment-513476234
void printWrapped(String text) {
final pattern = new RegExp('.{1,800}'); // 800 is the size of each chunk
pattern.allMatches(text).forEach((match) => print(match.group(0)));
}
Solution 2:
In Android Studio Debug mode, set break point and copy variable content in Variables window

Finding duplicates in Array of structure

I am using QT to search for duplicate entries in a structure.I have a struct as follows:
struct information{
QString fname;
QString lname;
QString gender;
QString age;
QString cod;
};
I have this code here which has bool variable for each variable in the structure and changes the bool value to true if data in the two arrays are the same and checks to see if all the bool values are true and prints out the two lines where duplicates are.
for (int i=0; i<numlines; i+=1){
for (int j=i+1; j<numlines; i+=1){
bool fname = false;
bool lname = false;
bool age = false;
bool cod = false;
bool gender= false;
if (person[i].fname == person[j].fname){
fname = true;
//qDebug() <<fname;
}
if (person[i].lname == person[j].lname){
lname = true;
//qDebug() <<lname;
}
if (person[i].gender == person[j].gender){
gender = true;
//qDebug() <<gender;
}
if (person[i].age == person[j].age){
age = true;
//qDebug() <<age;
}
if (person[i].cod == person[j].cod){
cod = true;
//qDebug() <<cod;
}
if (fname==true && lname==true && gender==true && age==true && cod==true){
//print out where duplicate are.
//duplicates at line i+1 and j+1
}
}
}
When I click my duplicate check button which activates the code it enters the loop once and terminates the program unexpectedly. Any suggestions?
for (int i=0; i<numlines; i+=1){
for (int j=i+1; j<numlines; i+=1){
// ^
Simple problem (probably cut'n'paste error) - you need to increment j, not i.
And, as an aside, you could probably refactor your code to make it a bit simpler since, if any field doesn't match, you can just move to the next, something like (pseudo-code):
for i = 0 to (sz - 2) inclusive:
for j = (i + 1) to (sz - 1) inclusive:
if person[i].fname != person[j].fname: continue
if person[i].lname != person[j].lname: continue
if person[i].age != person[j].age: continue
if person[i].cod != person[j].cod: continue
if person[i].gender != person[j].gender: continue
// they're all equal at this point, log the fact.
This removes the need for those boolean variables.
But, if you do decide to keep the booleans, you can make your code more readable by choosing their names carefully. I tend to prefer booleans to be readable such as customerIsDead or managerHasPsychopathicTendencies. That way, they "flow" easier when reading the code:
if (sameFName && sameLame && sameGender && sameAge && sameCod) {
You should generally never have compare a boolean value with true or false since that just gives you another boolean and, as per reductio ad absurdum, where do you stop?
if ((((x == true) == true) != false) == true) ...

How to count statements in C ignoring the comments

int Emptylines(FILE *fp);
int Numberofstatements(FILE *fp);
int main() {
FILE *fp = NULL;
FILE *fp1 = NULL;
int n1, n2;
char fname[255], fname1[255];
printf("Enter file name for reading");
fflush(stdin);
scanf("%s", &fname);
fp = fopen(fname, "r");
if (fp == NULL) {
printf("File with name %s couldn't be open", fname);
exit(1);
}
n1 = Emptylines(fp); // this is for empty lines
n2 = Numberofstatements(fp);
printf("Insert file name for writing");
fflush(stdin);
scanf("%s", &fname1);
fp1 = fopen(fname1, "w+");
fprintf(fp1, "The number of empty lines=%d", n1);
fprintf(fp1, "The number of statements=%d", n2);
fclose(fp);
fclose(fp1);
return 0;
}
int Numberofstatements(FILE *fp) {
char line[128];
int nofstatements = 0;
while (fgets(line, sizeof line, fp) != NULL) {
if (strstr(line, "if") != 0)
nofstatements++;
}
return nofstatements;
}
I need to count all statements like if, do, while, break, etc. as well as empty lines and then save the result in a new file. I succeed in counting the empty lines but I have no idea how to count the statements. I tried 2 different ways but both failed.
I also need to ignore comments while reading the code, so if there is a for, while, etc. in the comments it shouldn't be counted.
A very basic answer addressing the fundamental issue (although there are others).
When you call int Numberofstatements(FILE *fp) you already reached the end of file in int Emptylines(FILE *fp); so you must add the statement
rewind(fp);
before trying to parse the file for a second time. Good luck with developing this.
OP asks: "Any ideas ?"
To do properly, suggest reading 1 char at a time. Keep track if you are in 1) on an include line, 2) inside a " " 3) inside a ' ' 4) in a // comment 5) inside a /* comment or 6) just plain code (watch for escape sequences). When in plain code look for the keywords do, while, etc. and all the while count the '\n'.
To do correctly - this is not an easy task - about 10x the code you have posted.
Sample beginning of a state machine.
state = plaincode;
while ((c = getc()) != EOF) {
switch (state) {
slashslash_commnet:
if (c == '\n) state = plaincode;
break;
plaincode:
if (c == '/') {
c2 = getc();
if (c2 == '/') { state = slashslash_commnet; break; }
else if (c2 == '*') { state = slashstar_commnet: break; }
else unget(c2);
else if (c == '\"') {
...

ASP.NET MVC UrlHelper.GenerateUrl exception: "Cannot use a leading .. to exit above the top directory"

I am using the IIS 7 Rewrite module to rewrite an incoming url like:
http://server/year/all
to
http://server/application/controller/year/all
Everything works fine, except when, while processing the rewritten request, I use MVC's UrlHelper.GenerateUrl() method:
UrlHelper.GenerateUrl(
"Assets",
"Css",
"Asset",
new RouteValueDictionary(new { site = site.Name, assetPath = assetPath }),
RouteTable.Routes,
controllerContext.RequestContext,
false);
Calling this method results in an HttpException:
System.Web.HttpException: Cannot use a leading .. to exit above the top directory.
at System.Web.Util.UrlPath.ReduceVirtualPath(String path)
at System.Web.Util.UrlPath.Reduce(String path)
at System.Web.VirtualPath.Combine(VirtualPath relativePath)
at System.Web.VirtualPathUtility.Combine(String basePath, String relativePath)
at System.Web.Mvc.PathHelpers.GenerateClientUrlInternal(HttpContextBase httpContext, String contentPath)
at System.Web.Mvc.PathHelpers.GenerateClientUrl(HttpContextBase httpContext, String contentPath)
at System.Web.Mvc.UrlHelper.GenerateUrl(String routeName, String actionName, String controllerName, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, Boolean includeImplicitMvcValues)
Looking at the RequestContext, it seems that all of the request paths are correct (ie, have the rewritten values). I can't seem to figure out why it's trying to exit out of the top level directory... There's nowhere we are using .... in a path.
I've also made sure the RewriteModule is in above the UrlRouting module in IIS.
While I can step into the framework methods, I can't examine any of the local variables (either in VS or WinDbg) because it's been compiler optimized.
Any thoughts?
This is a grotesque workaround involving private implementation details, but add this:
HttpContext.Current.Request.ServerVariables.Remove("IIS_WasUrlRewritten");
This avoids the internal check done in PathHelper.GenerateClientUrlInternal to see if the request was rewritten. It's quite likely that this will break some scenarios, as hinted at by this comment in the reference sources:
// Since the rawUrl represents what the user sees in his browser, it is what we want to use as the base
// of our absolute paths. For example, consider mysite.example.com/foo, which is internally
// rewritten to content.example.com/mysite/foo. When we want to generate a link to ~/bar, we want to
// base it from / instead of /foo, otherwise the user ends up seeing mysite.example.com/foo/bar,
// which is incorrect.
Working solution is to insert the line before Url.Content/UrlHelper.GenerateContentUrl (best place is in Application_BeginRequest):
System.Web.HttpContext.Current.Items.Add("IIS_WasUrlRewritten", "false");
My answer is the result of 2 above answers (Rick Schott and Thom). Both was quite right but that didn't help.
I learned source code at https://github.com/aspnet/AspNetWebStack/blob/master/src/ of two classes (System.Web.WebPages.Utils.UrlRewriterHelper.cs and System.Web.WebPages.Utils.UrlUtil.cs) that are in my stack trace:
System.Web.HttpException (0x80004005): Cannot use a leading .. to exit above the top directory.
at System.Web.Util.UrlPath.ReduceVirtualPath(String path)
at System.Web.Util.UrlPath.Reduce(String path)
at System.Web.VirtualPath.Combine(VirtualPath relativePath)
at System.Web.VirtualPathUtility.Combine(String basePath, String relativePath)
at System.Web.WebPages.UrlUtil.GenerateClientUrlInternal(HttpContextBase httpContext, String contentPath)
at System.Web.WebPages.UrlUtil.GenerateClientUrlInternal(HttpContextBase httpContext, String contentPath)
at System.Web.WebPages.UrlUtil.GenerateClientUrl(HttpContextBase httpContext, String basePath, String path, Object[] pathParts)
There is code in System.Web.WebPages.Utils.UrlUtil.cs - GenerateClientUrlInternal method:
if (!wasRequestRewritten)
{
return contentPath;
}
// Since the rawUrl represents what the user sees in his browser, it is what we want to use as the base
// of our absolute paths. For example, consider mysite.example.com/foo, which is internally
// rewritten to content.example.com/mysite/foo. When we want to generate a link to ~/bar, we want to
// base it from / instead of /foo, otherwise the user ends up seeing mysite.example.com/foo/bar,
// which is incorrect.
string relativeUrlToDestination = MakeRelative(httpContext.Request.Path, contentPath);
string absoluteUrlToDestination = MakeAbsolute(httpContext.Request.RawUrl, relativeUrlToDestination);
return absoluteUrlToDestination;
You could see strange lines with author's comment for url rewritten paths. Also, original client path is in HttpContext.Request.RawUrl but in Url it is rewritten.
Look forward at System.Web.WebPages.Utils.UrlRewriterHelper.cs:
if (httpContext.Items.Contains(UrlWasRewrittenServerVar))
{
return Object.Equals(httpContext.Items[UrlWasRewrittenServerVar], UrlWasRequestRewrittenTrueValue);
}
else
{
HttpWorkerRequest httpWorkerRequest = (HttpWorkerRequest)httpContext.GetService(typeof(HttpWorkerRequest));
bool requestWasRewritten = (httpWorkerRequest != null && httpWorkerRequest.GetServerVariable(UrlWasRewrittenServerVar) != null);
if (requestWasRewritten)
{
httpContext.Items.Add(UrlWasRewrittenServerVar, UrlWasRequestRewrittenTrueValue);
}
else
{
httpContext.Items.Add(UrlWasRewrittenServerVar, UrlWasRequestRewrittenFalseValue);
}
return requestWasRewritten;
}
If we write dummy value to HttpContext.Items[UrlWasRewrittenServerVar] with "false" value we make skipped httpWorkerRequest.GetServerVariable(UrlWasRewrittenServerVar) != null check.
So Url.Content is working now.
Not sure if it helps but here is the code throwing the exception:
internal static string ReduceVirtualPath(string path)
{
int length = path.Length;
int startIndex = 0;
while (true)
{
startIndex = path.IndexOf('.', startIndex);
if (startIndex < 0)
{
return path;
}
if (((startIndex == 0) || (path[startIndex - 1] == '/')) && ((((startIndex + 1) == length) || (path[startIndex + 1] == '/')) || ((path[startIndex + 1] == '.') && (((startIndex + 2) == length) || (path[startIndex + 2] == '/')))))
{
break;
}
startIndex++;
}
ArrayList list = new ArrayList();
StringBuilder builder = new StringBuilder();
startIndex = 0;
do
{
int num3 = startIndex;
startIndex = path.IndexOf('/', num3 + 1);
if (startIndex < 0)
{
startIndex = length;
}
if ((((startIndex - num3) <= 3) && ((startIndex < 1) || (path[startIndex - 1] == '.'))) && (((num3 + 1) >= length) || (path[num3 + 1] == '.')))
{
if ((startIndex - num3) == 3)
{
if (list.Count == 0)
{
throw new HttpException(SR.GetString("Cannot_exit_up_top_directory"));
}
if ((list.Count == 1) && IsAppRelativePath(path))
{
return ReduceVirtualPath(MakeVirtualPathAppAbsolute(path));
}
builder.Length = (int) list[list.Count - 1];
list.RemoveRange(list.Count - 1, 1);
}
}
else
{
list.Add(builder.Length);
builder.Append(path, num3, startIndex - num3);
}
}
while (startIndex != length);
string str = builder.ToString();
if (str.Length != 0)
{
return str;
}
if ((length > 0) && (path[0] == '/'))
{
return "/";
}
return ".";
}

Resources