HTTPModule - an interceptor indeed, but without communication skills!

G

Girish

Ok, Ive been thinking about this problem for a while.

I have 30 odd aspx pages (already built) on my website that I need to have
some validation occur before the page should load. The validation is - TEST
if javascript is enabled on the browser + some other plugin checks via
javascript.

Id rather implement this check without touching any of the aspx files.
Reason is the usual - I dont want "same code" clutter in all pages
(javascript is a mess) and implementing page templates id rather not do
cause all my aspx pages have the <head> tag defined and I need to imbed the
common <script> tags inbetween the <head> tags. If i were to use page
templates- id have to remove the head tag in all my aspx files and render it
from my page template along with my <script> tags.. Also I dont want to use
includes or user controls cause that still involves touching all files.

Whats left? HttpModules.

Heres the javascript code declared in default.aspx:

<script language="Javascript">
window.location="main.aspx"
</script>
<body>
This is for js-disabled browsers
</body>

What this does is simple - if javascript is enabled, it will replace the
browsers URL to the new url. The problem is that I can only implement this
in default.aspx. If somebody were to bookmark main.aspx - there would be no
check. Id be back to square one. Heres where HttpModules came in. Atleast I
though!

Ive gradually realized that the HttpModule is a interceptor and acts similar
to a human being having the job of bouncer at some fancy club. What the
bouncer lacks here is communication skills. Heres what I mean:

In order to detect if the client supports javascript - you have to ask the
client that question! So the request goes back to the client and it needs to
respond with a yes or a no for accessing the real page. How do we do this?
By request parameters being passed via the url. eg
window.location="main.aspx?ok=ok".

Heres my sample code:

using System;
using System.Text;
using System.Web;

namespace com.tietronix.vaweb.module
{
/// <summary>
/// Summary description for BrowserValidator.
/// </summary>
public class BrowserValidator : System.Web.IHttpModule
{
public void Init(HttpApplication application)
{
application.PreRequestHandlerExecute += (new
EventHandler(this.Application_PreRequestHandlerExecute));
}

public void Dispose()
{
}

private void Application_PreRequestHandlerExecute(Object source, EventArgs
e)
{
HttpApplication application = (HttpApplication)source;
HttpRequest request = application.Request;
HttpResponse response = application.Response;
//check the request
//if request variable is set to ok, allow request to continue.
//else return requested url with checker code.
if (request["ok"] != "ok")
{
String url = application.Request.RawUrl;
response.Write(checkerCode(url));
response.End();
}
else
{
//pass through with removing "ok" from the request
//response.Redirect
}
}

private string checkerCode(string url)
{
StringBuilder s1 = new StringBuilder();
s1.Append("<script language=\"Javascript\">");
s1.Append("location=\"" + url + "?ok=ok\";");
s1.Append("</script>");
s1.Append("<html><body>");
s1.Append("This is for js-disabled browsers");
s1.Append("</body></html>");

return s1.ToString();
}
}
}


So now you see my little commented out response.Redirect? Im dead in the
water. Im thinking this is not even possible. I would like to remove the
ok=ok from the url cause i dont want it displayed. People could easily
bypass my validation otherwise. Yes, I know - you can get the url by looking
at it through a browser with disabled javascript cause it would render the
complete url - but thats ok. I want to make this a hindrance rather than
bullet proof. So anyways - i want to remove the ok=ok from the url and
redirect to the same page, but then my module would again test the page for
javascript and id be in an infinite loop! See where im stuck?

Am I making a mess of the whole thing? Is this not possible at all? Well,
there is another way - intercepting and parsing the output string to the
browser and embedding the code in there. Id rather not do that.

Any help would be greatly appreciated.

Thanks,
Girish
 
S

Steven Cheng[MSFT]

Hi Girish,

Thanks for posting in the community!
From your description, you'd like to implement a pre-validating on the
clientside's script abitlity before the request are processed by the
certain page handler. And you're currrently making efforts on using the
httpModule to check in the certain event before request has been processed
but encountered some problems, yes?
If there is anything I misunderstood, please feel free to let me know.

I've viewed the code logic you provided. Well, I think your idea is correct
and the only problems is that you used the url querystring to perform the
flag which represent whether the client side has passed the validation,
yes? As you've found that this is not quite good because some user can
easily manually append such querystring to bypass the validation.
My suggestion is what about the cookie? In the httpMOdule's certain event,
you can check the Request.Cookies collection for a certain cookie value, if
the value is set, then do nothing. If not set, then redirct the request to
the certain page which contains some certain code to validate whether the
client support javascript. In the validation code, you can use javascript
to set the cookie flag value and then use "window.location" to redirect it
to the orginal requested page. In fact, the ASP.NET's FormsAuthentication
's validation mechanism is just implemented via this means. Use the cookie
to store the authentication token and then checking this token in the
certain FormsAuthentication httpmodule. How do you think of this solution?

In addition, here are some tech articles on how to set cookie using
clientside javascript:
#JavaScript Cookies
http://www.comptechdoc.org/independent/web/cgi/javamanual/javacookie.html

#Netscape 6 compatible Cut and Paste Code Snippets - JavaScript and DHTML
http://www.the-cool-place.co.uk/javascript/cutandpaste/cutandpaste15.html

#The JavaScript Source: Cookie: User Name
http://javascript.internet.com/cookies/favorite-bg.html



Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Get Preview at ASP.NET whidbey
http://msdn.microsoft.com/asp.net/whidbey/default.aspx
 
G

Girish

The idea seems great. I was thinking about how Forms Authentication works -
cause it does a similar thing.
We have another requirement that states cookies NEED to be enabled. I guess
I could do that in the validation page itself too.

Thanks for your help. I'll try the solution out.
Girish
 
G

Girish

One thing that skips me... if I were to redirect the page in my module to
another one (validator page), how would I stop the HtppModule from trying to
process the validator page itself? Is there a easy way wherein it can ignore
a particular aspx file?

Thanks,
Girish
 
G

Girish

How can I stop a person from writing a simple javascript enabled HTML file
and setting a cookie and making himself bypass the validation?

girish
 
E

Eric Lawrence [MSFT]

Honestly, I think you're way better off just writing a function that you put
in your base page class that Response.Write()s

<noscript>
<meta refresh content="0;/youneedscript.htm">
</noscript>

If need be, this function could also insert JS to check cookies are enabled
(by setting and testing a cookie and changing document.location if failure).

Thanks,

Eric Lawrence
Program Manager
Assistance and Worldwide Services

This posting is provided "AS IS" with no warranties, and confers no rights.


Girish said:
Ok, Ive been thinking about this problem for a while.

I have 30 odd aspx pages (already built) on my website that I need to have
some validation occur before the page should load. The validation is - TEST
if javascript is enabled on the browser + some other plugin checks via
javascript.

Id rather implement this check without touching any of the aspx files.
Reason is the usual - I dont want "same code" clutter in all pages
(javascript is a mess) and implementing page templates id rather not do
cause all my aspx pages have the <head> tag defined and I need to imbed the
common <script> tags inbetween the <head> tags. If i were to use page
templates- id have to remove the head tag in all my aspx files and render it
from my page template along with my <script> tags.. Also I dont want to use
includes or user controls cause that still involves touching all files.

Whats left? HttpModules.

Heres the javascript code declared in default.aspx:

<script language="Javascript">
window.location="main.aspx"
</script>
<body>
This is for js-disabled browsers
</body>

What this does is simple - if javascript is enabled, it will replace the
browsers URL to the new url. The problem is that I can only implement this
in default.aspx. If somebody were to bookmark main.aspx - there would be no
check. Id be back to square one. Heres where HttpModules came in. Atleast I
though!

Ive gradually realized that the HttpModule is a interceptor and acts similar
to a human being having the job of bouncer at some fancy club. What the
bouncer lacks here is communication skills. Heres what I mean:

In order to detect if the client supports javascript - you have to ask the
client that question! So the request goes back to the client and it needs to
respond with a yes or a no for accessing the real page. How do we do this?
By request parameters being passed via the url. eg
window.location="main.aspx?ok=ok".

Heres my sample code:

using System;
using System.Text;
using System.Web;

namespace com.tietronix.vaweb.module
{
/// <summary>
/// Summary description for BrowserValidator.
/// </summary>
public class BrowserValidator : System.Web.IHttpModule
{
public void Init(HttpApplication application)
{
application.PreRequestHandlerExecute += (new
EventHandler(this.Application_PreRequestHandlerExecute));
}

public void Dispose()
{
}

private void Application_PreRequestHandlerExecute(Object source, EventArgs
e)
{
HttpApplication application = (HttpApplication)source;
HttpRequest request = application.Request;
HttpResponse response = application.Response;
//check the request
//if request variable is set to ok, allow request to continue.
//else return requested url with checker code.
if (request["ok"] != "ok")
{
String url = application.Request.RawUrl;
response.Write(checkerCode(url));
response.End();
}
else
{
//pass through with removing "ok" from the request
//response.Redirect
}
}

private string checkerCode(string url)
{
StringBuilder s1 = new StringBuilder();
s1.Append("<script language=\"Javascript\">");
s1.Append("location=\"" + url + "?ok=ok\";");
s1.Append("</script>");
s1.Append("<html><body>");
s1.Append("This is for js-disabled browsers");
s1.Append("</body></html>");

return s1.ToString();
}
}
}


So now you see my little commented out response.Redirect? Im dead in the
water. Im thinking this is not even possible. I would like to remove the
ok=ok from the url cause i dont want it displayed. People could easily
bypass my validation otherwise. Yes, I know - you can get the url by looking
at it through a browser with disabled javascript cause it would render the
complete url - but thats ok. I want to make this a hindrance rather than
bullet proof. So anyways - i want to remove the ok=ok from the url and
redirect to the same page, but then my module would again test the page for
javascript and id be in an infinite loop! See where im stuck?

Am I making a mess of the whole thing? Is this not possible at all? Well,
there is another way - intercepting and parsing the output string to the
browser and embedding the code in there. Id rather not do that.

Any help would be greatly appreciated.

Thanks,
Girish
 
J

John Saunders

Girish said:
How can I stop a person from writing a simple javascript enabled HTML file
and setting a cookie and making himself bypass the validation?

Encrypt the cookie.
 
G

Girish

Maybe Im missing something - but heres my thought process

Some person -> hits website
Module intercepts -> checks cookie -> no cookie -> server.transfers to
validator page and passes to page encrypted cookie
validator -> validates -> validation passes -> stores encrypted cookie which
it got from module -> redirects back to first page
Module -> checks cookie -> cookie exists -> decrypts cookie -> control
passes normaly
Some person -> reads encrypted cookie from file system -> writes own html ->
stores encrypted cookie -> redirects to any page without validation

Girish
 
E

Eric Lawrence [MSFT]

1> You can probably prevent cookie tampering using Encryption and a
challenge response system (e.g. encrypted cookie contains enough state
information that it can't be repurposed).
2> Doing so is very unlikely to make any sense for the purpose you've
described. As you described it, you wanted to test the user client to see
if cookies are enabled. This is a convenience for your customer and if they
decide to "hack" it and pretend like they have cookies, where's the harm?

If your code makes some sort of security assumptions requiring the existence
of cookies, you should be sure that you understand that any client can
refuse any cookie at any time.

--
Thanks,

Eric Lawrence
Program Manager
Assistance and Worldwide Services

This posting is provided "AS IS" with no warranties, and confers no rights.
 
G

Girish

yep i agree.. its not going to make sense for my purposes. I was just
curious to know it anyways just incase in the future I would need it for
another purpose.

Anyways, Ive already implemented this validator checker without the need for
encryption. Again, I was curious and my thougts keep going back to Forms
Authentication module. It implemted in the same way right? so it must need a
sophisticated cookie encryption scheme so as to prevent tampering all
together. right? just a tought process on the side :)

thanks,
Girish
 
S

Steven Cheng[MSFT]

Hi Girish,

Thanks for your response. Yes, as you've mentioned the FormsAuthentication
in ASP.NET has provide the
certain interfaces that allow use the encrypt the token that will be stored
in clientside cookie. For example:
the FormsAuthentication class has the below functions:

Encrypt, Decrypt, HashPasswordForStoringInConfigFile....

For detailed infos you may refer to the following reference in MSDN:
#Forms Authentication Credentials
http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemWebSecurityFor
msAuthenticationClassTopic.asp?frame=true

#Forms Authentication Provider
http://msdn.microsoft.com/library/en-us/cpguide/html/cpconthecookieauthentic
ationprovider.asp?frame=true


Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Get Preview at ASP.NET whidbey
http://msdn.microsoft.com/asp.net/whidbey/default.aspx
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top