ASP MVC Url Encode double escape sequence - c#

I want to encrypt the Id part of a given url and I used SHA-1 for that. This algorithm convert the id to the following string:
NxVhIhrfbZNzyxqtudUZdiv4DdQA9nF1Zn7CueGUiT8=|h1bCRiN5zxexiIhHp+qNEQ0jVh/8fMGiIkeTf30LVdU=
Therefore, my final url would be something like this:
http://localhost:9432/Product/Edit/NxVhIhrfbZNzyxqtudUZdiv4DdQA9nF1Zn7CueGUiT8=|h1bCRiN5zxexiIhHp+qNEQ0jVh/8fMGiIkeTf30LVdU=
This url has some character which cause the request fail. For example ‘+’ is not allowed in url. So I used HttpUtility.UrlEncode() on the encrypted Id and got this string as a result:
NxVhIhrfbZNzyxqtudUZdiv4DdQA9nF1Zn7CueGUiT8%3d%7ch1bCRiN5zxexiIhHp%2bqNEQ0jVh%2f8fMGiIkeTf30LVdU%3d
Now my url is:
http://localhost:9432/Product/Edit/NxVhIhrfbZNzyxqtudUZdiv4DdQA9nF1Zn7CueGUiT8%3d%7ch1bCRiN5zxexiIhHp%2bqNEQ0jVh%2f8fMGiIkeTf30LVdU%3d
However using the above url cause the following error:
The request contained a double escape sequence and request filtering is configured on the Web server to deny double escape sequences.
I can ignore that by inserting the below code in web.config:
<system.webServer>
<security>
<requestFiltering allowDoubleEscaping="true" />
</security>
</system.webServer>
Now I have two questions:
Why the result of HttpUtility.UrlEncode() causes any kind of error. As I noticed, the result of that doesn’t contain any illegal character for a url?
As I understood putting <requestFiltering allowDoubleEscaping="true" /> is not a good solution, since it will create a security hole in the application, so what would be the best solution in this case?

the result of HttpUtility.UrlEncode() doesn't contain errors, it is just encoding the + sign with will be detected on IIS level. IIS rejects "+" in URLs by default. Your work around will work:
<requestFiltering allowDoubleEscaping="true" />
but as you said, it will create some security problems because this makes your site more vulnerable to malicious URLs.
What i suggest, either you use another encryption algorithm that doesn't generate these "IIS" sensetive characters, or if you wanna use the above workaround, you need to implement proper URL/User-Input validations in order to make sure that you catch and prevent all suspecious entries.

Related

How to add a json string as a app setting value in config file

I have a requirement whereby I need to fetch a set of jsons before making a API call.
I am planning to add these json strings in app.config as shown below
<add key="Jsons" value="{""Id"":""25"",""Name"":""Value-1""}"/>
However adding this results in a compilation error "Missing whitespace" at the start of the value.
Please let me know if i am missing something.
I dont want to create a separate text file to read jsons from. Thats why i decided to use app.config itself
Your quotes are not correctly formatted.
Can you try this:
<add key="Jsons" value='{"Id":"25","Name":"Value-1"}'/>
An app.config is still XML! You need to use the XML escape sequence for quotes.
<add key="Jsons" value="{"Id":"25","Name":"Value-1"}"/>
I see two choices here:
Use "\" to escape:
<add key="Jsons" value="{\"Id\":\"25\",\"Name\":\"Value-1\"}"/>
Use single quote:
<add key="Jsons" value="{'Id':'25','Name':'Value-1'}"/>

Reading cookie value : Using URL Rewrite Provider module - Unable to validate at System.Web.Configuration.MachineKeySection.EncryptOrDecryptData

I have requirement to append USERNAME to the URL in server side using URL Rewrite module.
Why?:
I have website site1, when USER logs in to site1, he will see a link to site2., This link is URL or reports. (Tableau).
Authenticated ticket has been created using FormAuthentication in site1.
When USER clicks the link, authenticated username should be passed to site2.
I could append username from client side, but due to security issues I have to append username to URL in server side before it gets executed.
So I have decided to use URL rewrite provider, which grabs the username by decrypting the cookie value as shown below
namespace PlatformAnalysisUrlProvider.PlatformAnalysisProvider
{
class AnalysisRewriteProvider: IRewriteProvider, IProviderDescriptor
{
public void Initialize(IDictionary<string, string> settings,
IRewriteContext rewriteContext)
{
}
public string Rewrite(string value)
{
string[] cookievalues = value.Spli('=');
FormAuthentication ticket = FormAuthentication.Decrypt(cookievalues[1]);
//Decrypt throws error as shown below
}
}
}
Cookie Values
cookievalues [0] = has the key
cookievalues [1] = has the value
Example:
233AWJDKSHFHFDSHFJKDFDKJFHDKJFKDJFHDHFDHFKJHDFKJHDFJHDKJFHDSKJFHDF
It's a cookie value. But decrypt is not happening
I am getting following error
Unable to validate data.
at System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(
Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start,
Int32 length, IVType ivType, Boolean useValidationSymAlgo,
Boolean signData)
Here is my settings in IIS for URL Rewrite
Requested URL: Matches the Patterns
Using: Regular Expression
Ignore Case - Checked
Conditions -
Input : {HTTP_COOKIE}
Type : Matches the Pattern
Pattern : .*
Action Type - Rewrite
Rewrite URL - http://11.155.011.123{HTTP_URL}&USERNAME={PlatformAnalysisUrlProvider:{C:0}}
I have also set up MACHINE KEY as suggested by this forum
I have referred this post for development
One of the stack overflow post suggested that it might be firewall or antivirus issue. But I do not have antivirus installed or firwall enabled.
It really helps if someone direct me to code sample where web site hosted in IIS and URL Rewrite provider is used.
Updating Error Log
MODULE_SET_RESPONSE_ERROR_STATUS
Notification - "PRE_BEGIN_REQUEST"
HttpReason - "URL Rewrite Module Error"
Updating post with Machine Key Info
<MachineKey Description="AES" validation="SHA1"
descriptionKey="******"
validationKey="******" CompatibilityMode="Framework20SP2">
Reason May be - The website where cookie getting created is developed using .NET Framework 4.5. The provider where we reading the cookie is Framework 3.5. Is this may be the cause? OR Do we need config file for Provider project?
Updates - I have added machine key to Machine.config , but it still did not work :(
Alternative Solution
Add App.config to class Library
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<!-- ... -->
<add key="SecurityKey" value="somevalue"/>
<!-- ... -->
</appSettings>
</configuration>
Copy config to GAC
Follow this blog - http://techphile.blogspot.in/2007/02/2.html
Encrypt the value (refer here) and create custom cookie during Login
Use the Decrption logic inside custom rewrite provider
The good thing about this is that the error is a general decryption error and not one with URL Rewrite itself, so that gives you a wider area to search for help. The mechanics of URL Rewrite seem to be right.
Decrypting means that it must be encrypted by the same method as you're decrypting it. So it has to be the right cookie and the right decryption method.
Since you're not checking which cookie that you're reading from, you could get unexpected results if the wrong cookie is first in the list of cookies.
Here are some steps that I recommend to troubleshoot this:
Create a simple URL Rewrite rule that will give you the value of your cookie. I created a rule to do that in my example below. You can test it by going to yoursite.com/getcookie. It should redirect to yoursite.com/?Cookie={cookievalue}
Then you can test your code outside of the URL Rewrite provider. You can create a simple console app or winforms app to test the rest of the code.
I recommend adding a check for the existence of the cookie and then a check again for the 2nd value. For example: if (cookievalues[1] != null).
When developing the decryption method, you don't have to worry about URL Rewrite. As long as it works in a test app in .NET then you should be set.
<rule name="Get cookie value" stopProcessing="true">
<match url="^getcookie" />
<action type="Redirect" url="/?Cookie={HTTP_COOKIE}" appendQueryString="false" redirectType="Found" />
</rule>

Url rewriting not properly applied

I have a web portal on which I have applied Url rewritting using rewriteModule.dll.
I have define a rule like
<rule source="Voices" destination="Others/MyVoices.aspx"/>
It runs successfully.
But In my admin login I have a page named DefineVoices.aspx [In admin login I have not applied rewritting], when i have called DefineVoices.aspx then Url is converted into
/Admin/DefineOthers/MyVoices.aspx.aspx
Please give me a solution without chage in my current url rule...
You have to change your url replace algorithm because you might be using direct string replace. Which causing the url
/Admin/DefineVoices.aspx
to
/Admin/DefineOthers/MyVoices.aspx.aspx
In your rule you have specified a rule that replaces the word Voices to Others/MyVoices.aspx.
I would recommend to update your replace alogirthm and use Regular expression properly and only replace part of url not words.
e.g. exact word /voices to /Others/MyVoices.aspx

Replacing special characters in web.config using Intelligencia UrlRewriter

I have an article based website where users can login, post articles etc.
The url I am using for a registered user looks as follows (only example):
http://example.com/Author/1234/Screenname
Like you can see, I am passing through the ID (1234) and using the users screen name.
The Problem
Passing the ID is 100% fine, but once a user has a special character or anything that is not A-Z, it will return a 404 or a Bad Request page.
Problematic URL
See /Screen.name - I want to replace special characters, coz it will cause a Http error.
http://example.com/Author/1234/Screenname.
I want to use the Intelligencia UrlRewriter in the web.config (or any other global solution, e.g. global.asa) to replace special invalid url characters.
My current web.config rewriter code:
<rewrite url="^~/Author/(.+)/(.+)" to="~/Contributor_Profile.aspx?auID=$1&auN=$2" processing="stop" permanent="true"/>
Try this in your web.config
<httpRuntime relaxedUrlToFileSystemMapping="true" />

How do I "smoothly" format HttpHandler URI?

I'm just meddling in the ways of the RESTful web service in C# using ASP.Net 2.0 and have managed (via a class library, a reference to dll produced by the former and some adjustment of my web.config) to coax out a URI format like so:
http: //localhost/DevelopmentProject/testhandler/?input=thisismyinput
Which unremarkably just returns the input as a piece of text with the enlightening prefix "Your Input Was: "
I was under the impression that I could get the URI to become further ensmoothened to something more along the lines of:
http: //localhost/DevelopmentProject/testhandler/thisismyinput
and have the same result but have no idea how to get rid of the pesky "?input="
The entry to the httphandlers section of my web.config is (spaces added so code displays):
< add verb="*" path="testhandler/*" type="HandlerLib.testhandler, HandlerLib"/ >
I am running IIS 5.1 on the local machine, will this introduce a problem?
Essentially where am I going wrong?
Thanks.
One solution is to use UrlRewriting to rewrite the Url to what you need.
I use http://urlrewriter.net/ to do all my rewriting, and you could setup something like this in your scenario
<rewriter>
<rewrite
url="DevelopmentProject/testhandler/([\w]+)"
to="DevelopmentProject/testhandler/?input=$1" />
</rewriter>
This would remain "http: //localhost/DevelopmentProject/testhandler/thisismyinput" in your browser address bar, yet process as "http: //localhost/DevelopmentProject/testhandler/?input=thisismyinput"
You could implement URL rewriting, using something like URLRewriter.net
That would let you use the syntax you've mentioned.
I kinda cheated.
Try:
My Article About How I Got Round It
Change your config from:
< add verb="" path="testhandler/" type="HandlerLib.testhandler, HandlerLib"/ >
to:
< add verb="" path="testhandler/*" type="HandlerLib.testhandler, HandlerLib"/ >
Check out the value of Request.PathInfo in your handler's ProcessRequest function
with a URL like http://localhost/DevelopmentProject/testhandler/thisismyinput.
If that doesn't do it, make sure that IIS 5.1 is routing ALL requests to the aspnet_isapi.dll. (Although, it seems like it already is) This is the "Configuration..." button > "App Mappings" tab in your virtual directory in IIS.

Categories