URLParameter value bug in Intelligencia.UrlRewriter - c#

my rewrite rule is
**<rewriter>
<rewrite url="~/categories/([0-9,A-Z,a-z,-]+)/(.+).aspx" to="~/inventory/product-list.aspx?categorycode=$1" processing="stop"/>
</rewriter>**
it works for url with
/category/abc/abc.aspx
but causes problem with
/category/con/abc.aspx
i dont understand why?
if we pass "con" as url parameter value in any site used by Intelligencia.UrlRewriter.
you may find similar problem.

Have researched so much and found an answer.
Actually IIS restricts us from use certain keywords in URL like
COM1-9, LPT1-9, AUX, PRT, NUL, CON
but we can solve this by using following settings in web.config file.
<configuration>
<system.web>
<httpRuntime relaxedUrlToFileSystemMapping="true"/>
</system.web>
</configuration>
It solved my problem.

Related

Preventing "A potentially dangerous Request.Path" in web api

I have this controller.
public string Status([FromBody]StatusRequest p)
{
string ps= HttpContext.Current.Request["params"];
return ps;
}
It receives this post parameter value (The value is xml. Beneath is just part of it):
params=<Transaction hash=9
I get this infamous error:
A potentially dangerous Request.Form value was detected from the client
I tried a few solutions.
I tried to bind the post parameter. But there is no luck, it wont bind it so the value of 'p' is always null.
I tried setting web.config in the directory where my controller is:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime targetFramework="4.5" requestPathInvalidCharacters="?" />
<pages validateRequest="false" />
</system.web>
</configuration>
Those configurations have no effect on the files inside the directory.
Does anyone knows how to solve this?
This is really nasty exception because it reveals Server header even if you hide it so big bad guy can use that info against you.
I've found two solutions which help me. Let me explain both by using asterisk as example of dangerous symbol (but you can handle any single symbol or set of symbols in this way)
1st way is really ugly and I can't recommend it to anyone. But here it is:
Add to Global.asax.cs code
protected void Application_Error(object sender, EventArgs e)
{
if(Context.Request.RawUrl.Contains("*"))
{
Server.ClearError();
}
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
if(!Context.Request.RawUrl.Contains("*"))
{
return;
}
var newPath = Context.Request.RawUrl.Replace("*", "");
base.Context.RewritePath(newPath);
}
That's it. For any url with asterisk you'll omit this annoying exception and just replace dangerous symbol with anything you want.
2nd way is slightly trickier, but as for me, much better. Just keep in mind, that you can't use it if you don't have possibilities to install URL Rewrite module for IIS. Check next article for the details. Article is a little bit dated, if you use IIS 10 as I do, you need to get URL Rewrite module here.
So first of all you have to install this module. After that add this section to your web config file in system.webServer section:
<rewrite>
<rules>
<rule name="Rewrite URL to remove asterisk from path.">
<match url="^(.*)\*(.*)$" />
<conditions logicalGrouping="MatchAny" />
<action type="Rewrite"
url="{R:1}{R:2}" />
</rule>
</rules>
</rewrite>
That's all. Now almost any malformed url with asterisk will work without this annoying error.
Why almost? Because you'll still get exception if dangerous symbol presents in the name of, for example, IIS virtual directory.
So both ways handle errors like http://localhost/WebApplication1/api*/Values
And both ways fails with url like this http://localhost/WebApplication1*/api/Values
Just remove asterisk from requestPathInvalidCharacters under Web.config
...
<system.web>
<httpRuntime requestPathInvalidCharacters="<,>,*,%,&,:,\,?" />
...

What is ConfigurationManager.AppSettings?

I'm using this, as a sample Authentication to try out. What I want to know is what happens in this line. i.e. ConfigurationManager.AppSettings["ActiveDirectory.ResourceId"]). Would somebody be kind enough to explain it?
You can set the default configurations for your application in web.config file and access them using the ConfigurationManager.AppSettings property.
e.g.
web.config
<configuration>
<appSettings>
<add key="highestScore" value="200" />
<add key="defaultSport" value="Cricket" />
</appSettings>
</configuration>
Code
int maxScore = Convert.ToInt32(ConfigurationManager.AppSettings["highestScore"]);
string Sport = ConfigurationManager.AppSettings["defaultSport"].ToString();
The ActiveDirectory.ResourceId app setting for the AuthBot example you referenced is:
<add key="ActiveDirectory.ResourceId" value="https://graph.windows.net/" />
The reason the .ResourceId is graph.windows.net as opposed to graph.microsoft.com is explained some here: https://github.com/matvelloso/AuthBot/pull/10
They are both valid. It only depends on which one you configure your
application in AAD for. Not everybody has Office 365 and therefore not
everybody will have graph.microsoft.com so I'd rather just leave it
with the option that is more likely going to work for most people
--Matt Velloso

Web.config httpredirect is inserting a backslash when I don't want one

I'm updating a site into a more dynamic version of the site. And in the new site I use hash tags rather than a new page for every change in content.
I'm using web.config files in directories to redirect but it's adding a backslash. Is there anyway to avoid this? I'm already handling it in the redirect, but I feel it's kinda kludgy.
Here is an example web.config
<?xml version="1.0"?>
<configuration>
<system.webServer>
<httpRedirect enabled="true" destination="/legal/#!terms-of-use" />
</system.webServer>
</configuration>
Edit: It's worth mentioning, that instead of going to "/legal/#!terms-of-use" it goes to "/legal/#!terms-of-use/" Note the backslash at the end.
Turn on exactDestination in your redirect element, as below:
<httpRedirect enabled="true" destination="/legal/#!terms-of-use" exactDestination="true" />

Setting Culture for ASP.NET MVC application on VS dev server and IIS

This is more specific and cleaner version of this question - Different DateTimeFormat for dev and test environment
In the Application_BeginRequest() method of global.asax.cs in my ASP.NET MVC project there is code:
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
When I set a breakpoint on Controller Action I see the following value of Thread.CurrentThread.CurrentCulture:
In VS dev server - "en-GB"
In IIS - "en-US"
Question is - What settings in IIS are responsible for this and how can I override it?
Rather than setting the Thread's culture, you can specify it in the web.config like so:
<configuration>
<system.web>
<globalization uiCulture="en-GB" culture="en-GB" />
</system.web>
</configuration>
That is a more "proper" way of specifying the culture in ASP.NET.
Well, I didn't actually find what IIS setting is responsible, but I've overridden it in Application_PreRequestHandlerExecute() and it finally worked:
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
I think it is a good option to just let the client (i.e. user agent / browser) decide what culture he wants.
This can be done by setting the culture and uiCulture attribute of the globalization element in web.config to auto. See "Version 1".
You can also do something like: Take the broswers setting, but if not possbile use en-US as fallback value. See "Version 2".
Version 1:
<configuration>
<system.web>
<globalization culture="auto" uiCulture="auto"/>
</system.web>
</configuration>
Version 2:
<configuration>
<system.web>
<globalization culture="auto:en-US" uiCulture="auto:en-US" />
</system.web>
</configuration>
See also this article for more info: Auto Detecting and Setting ASP.NET Locale based on Browser Locale
To set a default Culture for your App in MVC, you can easily add this route in your RouteConfig class:
foreach (var route in routes.Cast<Route>().Where(route =>
route.GetType() == typeof(MultiLingualRoute)))
{
route.Url = "{language}/" + route.Url;
route.Defaults.Add("language", "YOUR-DEFAULT");
}

Using ELMAH and URLRewritingNet Together

I have ELMAH setup on my production server and it has done a fantastic job of letting me know about any niggles - as well as any creative SQL injection!
I've decided to introduce URl Rewriting and went for http://www.urlrewriting.net/ in the end. It was nice and easy to setup and it's doing exactly what I want with the customer-facing site.
The problem is ELMAH. Because I've set the urlrewritingnet node in my config like so:
<urlrewritingnet
rewriteOnlyVirtualUrls="true"
contextItemsPrefix="QueryString"
defaultPage = "default.aspx"
defaultProvider="RegEx"
xmlns="http://www.urlrewriting.net/schemas/config/2006/07" >
...ELMAH likes to do this to it's axd links;
http://www.mydomain.com/elmah.axd/stylesheet/default.aspx
Does anyone have any idea how to either
a) stop the re-writer following the .axd; or
b) add rules to the re-writer to get ELMAH to work
Any ideas? I'm happy to hack about with the httpHandlers...
I had the same issue - urlrewritingnet messing up my elmah - but found an answer here: http://markmail.org/message/ctbh6ozzqpe4qn6j#query:+page:1+mid:ctbh6ozzqpe4qn6j+state:results
Basically set defaultPage to empty like this:
Before (shortened):
<urlrewritingnet defaultPage="default.aspx" ... >
After (shortened):
<urlrewritingnet defaultPage="" ... >
Now all css styles work for Elmah.
I came up with a simpler solution if others are interested.
I just modify the source code directly and add in some basic logic to ignore specific rewrite rules.
I kind of solved this, but not in the way I wanted too. For the reference of others, I will provide a breakdown of what I did and the resources;
ELMAH: http://code.google.com/p/elmah/
URLRewritingNet: http://www.urlrewriting.net/149/en/home.html
This was really the only available option to me: http://csharpin.blogspot.com/2009/03/using-urlrewritingnet-and-elmah.html, but I had untold difficulty to get the code into my existing architecture without other adverse affects. I did try adding rules to the ExternalRewrite.config (URL Rewrite) to ignore *.axd, but that didn't pan out either. I was getting all sorts of weird behaviour.
I then decided to use Health Monitoring: https://web.archive.org/web/20211020102851/https://www.4guysfromrolla.com/articles/031407-1.aspx instead of ELMAH. Sorry ELMAH :(
Health Monitoring was a snip to setup and then all I had to do was solve the nasty postback problem on rewritten URLs;
Health Monitoring web.config;
<!--he-mon-->
<healthMonitoring enabled="true">
<eventMappings>
<clear />
<add name="All Errors" type="System.Web.Management.WebBaseErrorEvent" startEventCode="0" endEventCode="2147483647" />
</eventMappings>
<providers>
<clear />
<add connectionStringName="healthMonitoringConnectionString" maxEventDetailsLength="1073741823" buffer="false" name="SqlWebEventProvider" type="System.Web.Management.SqlWebEventProvider" />
<add type="System.Web.Management.SimpleMailWebEventProvider" name="EmailWebEventProvider" from="xxx" to="yyy" bodyHeader="zzz" bodyFooter="000" buffer="false" />
</providers>
<rules>
<clear />
<add name="All Errors Default" eventName="All Errors" provider="SqlWebEventProvider" profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:00:00" />
<add name="All Errors Default Email" eventName="All Errors" provider="EmailWebEventProvider" profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:00:00" />
</rules>
</healthMonitoring>
<!--he-mon-->
Add the connection string to the connectionString node too.
To fix the rather nasty postback on URL rewritten strings, I tried ScottGu's suggestion; Handling ASP.NET PostBacks with URL Rewriting: http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx, but I couldn't get that to work at all.
Starting to really regret getting into URL Rewriting, I finally added this to the one problematic page I had; Me.Form.Action = Me.Request.RawUrl within the Page_Load and it worked a treat.
I know this doesn't directly answer the question, but I hope it helps. I hope someone finds my information at least somewhat useful.

Categories