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.
Related
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="<,>,*,%,&,:,\,?" />
...
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
Intro
I'm developing a WebApp built on C# ASP.NET.
I've been researching creating a "Custom Configuration" section with child elements in the Web.config file, and I've hit a bit of a snag when it comes to consuming the keys/values in the data.
I seem to be going round in circles and I don't know how to tackle the issue I'm having.
Situation
I have a few different Connection Strings defined in the Web.Config file, in the <connectionStrings> section. They are for dev, test, and live databases.
<connectionStrings>
<add name="connectionOne" connectionString="..." providerName="..." />
<add name="connectionTwo" connectionString="..." providerName="..." />
<add name="connectionThree" connectionString="..." providerName="..." />
</connectionStrings>
The WebApp is currently hard-coded to use one of these connection strings - if I need to change which one to use, I need to re-compile.
Desired Functionality
I'd like to define a section in the Web.config, let's say DbSettings.
In that, I'd then like to be able to define some child elements for, let's say DbSettings, in which I could define dbConnectionName, foo, bar etc. as attributes.
For example:
<dbSettings>
<dbSetting key="DbSetting1"
dbConnectionName="connectionOne"
foo="fooOne"
bar="barOne" />
... and so on
</dbSettings>
Then, perhaps in the <appSettings> section, define which of these DbSettings elements I want to use to get the settings from:
<appSettings>
<add name="dbSettingsKey" value="DbSetting1" />
</appSettings>
Desired Web.config section
Here is a fuller example of what I'd imagine my Web.config file to look like:
Connection Strings
<connectionStrings>
<add name="connectionOne" connectionString="..." providerName="..." />
<add name="connectionTwo" connectionString="..." providerName="..." />
<add name="connectionThree" connectionString="..." providerName="..." />
</connectionStrings>
App Settings
<add key="dbSettingsKey" value="DbSetting1" /> // or 2, or 3 etc.
DbSettings (custom section)
<dbSettings>
<dbSetting key="DbSetting1"
dbConnectionName="connectionOne"
foo="fooOne"
bar="barOne" />
<dbSetting key="DbSetting2"
dbConnectionName="connectionTwo"
foo="fooTwo"
bar="barTwo" />
<dbSetting key="DbSetting3"
dbConnectionName="connectionThree"
foo="fooThree"
bar="barThree" />
</dbSettings>
My question...
How the devil am I going to get this desired functionality in the C# code?
I've read loads on "creating your own custom section", and similarly "creating a custom config collection". But, I just can't seem to glue it all together to apply for my situation.
I'd like to be able to have a class (like the one I'm using at the moment with the hard-coded strings), which I can reference necessary properties (as I am doing, at the moment) - and then the code can dynamically load the correct settings at run-time from the sections I've described above.
As always, thank you in advance for your suggestions and help.
I agree with the comments. The way this is usually done is you deploy a different web.config to each environment. When your deployment group (or you) deploys, you deploy everything EXCEPT the web.config unless you have changes to push.
In answer to your other question, adding a custom section is not trivial. It's quite a bit of work. Custom section handler which requires a whole bunch of configuration element classes and a bunch of configuration element collection classes... and then, if you want it to "work" correctly, you also need to create a schema and register that with the IDE, etc.
For your particular case, I'd just do it the "normal" way :).
I'm trying to check if a string has any kind of injection.
The problem is that i am new c#, so i don't know if im doing it right.
The text could be one of the next things:
usernames (numbers and alphabet in english/hebrew).
names.
addresses
descriptions(plain text with basic haracters like dots comas etc)
heres what i've done so far:
https://www.regex101.com/r/tQ0iK1/2
What I'm trying to do is simply to protect my inputs against injections.
So if there is another way, ill do it.
And if it is not necessary to protect inputs using c# then forgive me, i come from the world of web development.
Thanks ahead :)
And if it is not necessary to protect inputs using c# then forgive me,
i come from the world of web development.
Instead of trying to use a regex to do this you can leverage built in IIS functionality.
You can use a security config block in System.webServer to take care of most of it:
E.g. this would block script> and script<
<system.webServer>
<!-- other blocks -->
<security>
<requestFiltering>
<denyQueryStringSequences>
<add sequence="script<" />
<add sequence="script>" />
</denyQueryStringSequences>
<verbs />
</requestFiltering>
</security>
<!-- other blocks -->
</system.webServer>
More on denyquerystring. This way your security is for the entire website, and you don't have to roll code for everything and you can keep code validation to match business rules.
I am having small application in which I used SHIMS.
So as you know it gives warning like "Warning 20 Some fakes could not be generated. For complete details, set Diagnostic attribute of the Fakes element in this file to 'true' and rebuild the project."
So as said in the warning I tried to set the Diagnostic flag to true.
So as specified I got all the list of warning.
The number of warnings are 1933 from "mscorlib.fakes" file.
So to solve it I just took a look of all the following links check it out.
http://msdn.microsoft.com/en-us/library/hh708916.aspx#bkmk_type_filtering
vs 2012: Shims compile
Suppressing Microsoft Fakes warnings
http://connect.microsoft.com/VisualStudio/feedback/details/848682/microsoft-fakes-not-creating-properties-in-a-shim-of-a-class-with-auto-generated-properties
and other stuff.
But still I am unable to figure out how to solve all this warnings.
I also want to know is there any way to Suppress this warnings.
So how can I remove all this warnings in right way? And is there any other way to suppress all this warnings?
Whenever I am adding
<ShimGeneration>
<Clear/>
// other tags like add and etc..
<ShimGeneration/>
I am getting lots of errors in project like you are missing assembly reference and others.
So what is the way to clear out all this warnings and the way to suppress all this warnings?
There are two ways of solving when it produces some extra warnings e.g.
Cannot generate shim for System.Diagnostics.ProcessPriorityClass: type is an enum.
Which you might not like, you can get rid of these warnings by not generating Shims for those types in the fakes file. Something like:
<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/" Diagnostic="true">
<Assembly Name="System" Version="4.0.0.0"/>
<StubGeneration>
<Clear/>
</StubGeneration>
<ShimGeneration>
<Clear/>
<Add FullName="System.Diagnostics.Process"/>
<Remove FullName="System.Diagnostics.ProcessPriorityClass"/>
<Remove FullName="System.Diagnostics.ProcessWindowStyle"/>
</ShimGeneration>
</Fakes>
However going through and removing every single class that has a warning can be time consuming especially for larger BCLs.
The second approach, and better in my opinion, is to use type filtering with '!' and only specify the class you are interested in generating. The examples given on MSDN seem to indicate that type filtering can only be used to restrict the namespace attribute but can also be used with the fullname attribute like this example:
<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/" Diagnostic="true">
<Assembly Name="System" Version="4.0.0.0"/>
<StubGeneration>
<Clear/>
</StubGeneration>
<ShimGeneration>
<Clear/>
<Add FullName="System.Diagnostics.Process!"/>
</ShimGeneration>
</Fakes>
This example will only Shim the System.Diagnostics.Process class and not match System.Diagnostics.ProcessPriorityClass.
<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/" Diagnostic="true">
<Assembly Name="mscorlib" Version="4.0.0.0"/>
<StubGeneration>
<Clear />
</StubGeneration>
<ShimGeneration>
<Clear />
<!-- Add or remove library or class -->
</ShimGeneration>
</Fakes>
try the Following code
<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/">
<Assembly Name="mscorlib" />
<!-- user code -->
<StubGeneration>
<Types>
<Clear />
<Add AbstractClasses="true"/>
</Types>
</StubGeneration>
<!-- /user code -->
</Fakes>
Finally Worked with all the .fakes files.
And used following link again.
http://msdn.microsoft.com/en-us/library/hh708916.aspx#bkmk_type_filtering
And In above specified link there just specified how to deal with stub generation not with the shim generation.
I think complete example should be given over there.
So to remove all the warnings as specified in above links i added only needed stub generation and removed unnecessary generation.
example is as follow
<StubGeneration>
</Clear>
<Add Namespace="System!">
// Other code
</StubGeneration>
<ShimGeneration>
<Remove Namespace="System" TypeName="example"/>
</ShimGeneration>
There are different ways to remove all the unwanted stub and shim you can remove whole class directly or remove partial part of the class.
So to get around all warnings you must go through that.