.Net web application behind a WebSeal reverse proxy - asp.net

We are currently designing a solution that will run as a .Net Web application behind a WebSeal reverse proxy.
I have seen some comments on the net where people have had various problems with this, for example rewriting of viewstate.
Question is: Has anyone implemented this combination of techologies and got it to work?

I made an ASP.NET application workin behind WEBSEAL. After lot of study and development and test it works.
I suggest some issues to help you:
IIS and ASP.NET are case insensitive
("...Login.aspx" and "...login.aspx" both lead to the same page); by default webseal is case sensitive. So you should set WEBSEAL junction to be case insensitive or check any single link (page, javascript, image)
Internal links, written as server relative URLs won't be served
WEBSEAL changes any link referring your application but doesn't change links to other applications.
Internal links, written as server relative URLs instead of application relative URLs won't be changed (WEBSEAL doesn't recognize it's the same application) and won't be served (WEBSEAL rejects links that are not modified).
First rule is to check any single link and make it an application relative URL .
Look at rendered HTML if you find <.. href=/ anything> : this i a server relative URL and it is bad.
Look in the Code Behind if you use "= ~/ anything" it is good. If you use "= / anything" OR ResolveUrl(..) it is bad.
But this is not enough: AJAX puts loads of javascript and code inside ScriptResource.axd and WebResource.axd and creates server relative URL to link it. This links are not controlled by programmers and there is no easy way to change them.
Easy solution (if possible): solve the problem setting WEBSEAL junction to be transparent.
Hard solution: write the following code (thanks to this answer)
protected void Page_Load(object sender, EventArgs e)
{
//Initialises my dirty hack to remove the leading slash from all web reference files.
Response.Filter = new WebResourceResponseFilter(Response.Filter);
}
public class WebResourceResponseFilter : Stream
{
private Stream baseStream;
public WebResourceResponseFilter(Stream responseStream)
{
if (responseStream == null)
throw new ArgumentNullException("ResponseStream");
baseStream = responseStream;
}
public override bool CanRead
{ get { return baseStream.CanRead; } }
public override bool CanSeek
{ get { return baseStream.CanSeek; } }
public override bool CanWrite
{ get { return baseStream.CanWrite; } }
public override void Flush()
{ baseStream.Flush(); }
public override long Length
{ get { return baseStream.Length; } }
public override long Position
{
get { return baseStream.Position; }
set { baseStream.Position = value; }
}
public override int Read(byte[] buffer, int offset, int count)
{ return baseStream.Read(buffer, offset, count); }
public override long Seek(long offset, System.IO.SeekOrigin origin)
{ return baseStream.Seek(offset, origin); }
public override void SetLength(long value)
{ baseStream.SetLength(value); }
public override void Write(byte[] buffer, int offset, int count)
{
//Get text from response stream.
string originalText = System.Text.Encoding.UTF8.GetString(buffer, offset, count);
//Alter the text.
originalText = originalText.Replace(HttpContext.Current.Request.ApplicationPath + "/WebResource.axd",
VirtualPathUtility.MakeRelative(HttpContext.Current.Request.Url.AbsolutePath, "~/WebResource.axd"));
originalText = originalText.Replace(HttpContext.Current.Request.ApplicationPath + "/ScriptResource.axd",
VirtualPathUtility.MakeRelative(HttpContext.Current.Request.Url.AbsolutePath, "~/ScriptResource.axd"));
//Write the altered text to the response stream.
buffer = System.Text.Encoding.UTF8.GetBytes(originalText);
this.baseStream.Write(buffer, 0, buffer.Length);
}
This intercepts the stream to the page and replaces all occurrences of "/WebResource.axd" or "ScriptResource.axd" with "../../WebResource.axd" and "../../ScriptResource.axd"
Develop code to get actual WEBSEAL user
WEBSEAL has been configured to put username inside HTTP_IV_USER. I created Webseal\Login.aspx form to read it programmatically.
Now, in order to make this user the CurrentUser I put an hidden asp.Login
<span style="visibility:hidden">
<asp:Login ID="Login1" runat="server" DestinationPageUrl="~/Default.aspx">..
and clicked the button programmatically
protected void Page_Load(object sender, EventArgs e)
{
string username = Request.ServerVariables["HTTP_IV_USER"];
(Login1.FindControl("Password") as TextBox).Text = MyCustomProvider.PswJump;
if (!string.IsNullOrEmpty(username))
{
(Login1.FindControl("UserName") as TextBox).Text = username;
Button btn = Login1.FindControl("LoginButton") as Button;
((IPostBackEventHandler)btn).RaisePostBackEvent(null);
}
else
{
lblError.Text = "Login error.";
}
}
When LoginButton fires, application reads UserName (set from WEBSEAL variable) and password (hard coded). So i implemented a custom membership provider that validates users and sets current Principal.
Changes in web.config
loginUrl is the URL for the login page that the FormsAuthentication class will redirect to. It has been set to WEBSEAL portal: not authenticated user and logout button will redirect to portal.
<authentication mode="Forms">
<forms loginUrl="https://my.webseal.portal/" defaultUrl="default.aspx"...."/>
</authentication>
Since Webseal/login.aspx is NOT default login page, authorization tag grants access to not authenticated users:
<location path="Webseal/login.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
Application is set to use custom membership providers:
<membership defaultProvider="MyCustomMembershipProvider">
<providers>
<add name="MyCustomMembershipProvider" type="MyNamespace.MyCustomMembershipProvider" connectionStringName="LocalSqlServer"/>
</providers>
</membership>
<roleManager enabled="true" defaultProvider="MyCustomRoleProvider">
<providers>
<add name="MyCustomRoleProvider" type="MyNamespace.MyCustomRoleProvider" connectionStringName="LocalSqlServer"/>
</providers>
</roleManager>
Debug is set to off:
<compilation debug="false" targetFramework="4.0">
that's all folks!

I initially has some issues with the ASP.Net app when accessed through WebSeal. I was running the site on a development server. What worked for me was to deploy the application with debugging turned off in the config file.
<compilation debug="false" ...>
With debugging turned on, there were some AJAX calls that would work fine when I accessed the site directly but would fail when access through WebSeal. Once I turned the debugging off, everything work fine.
Also, because WebSeal requires anonymous authentication, we couldn't have used Windows Authentication.

Related

HttpModule isn't processing request authentication

I have an HttpHandler that I'm trying to use to put a little security layer over a certain directory in my site, but it's behaving strangely.
I've got it registered like this in my Web.Config: no longer valid since I'm in IIS 7.5
<httpHandlers>
<add verb="*" path="/courses/*" type="CoursesAuthenticationHandler" />
I can't tell if it's actually being called or not, because regardless of the code, it always seems to do nothing. On the flip side, if there are any errors in the code, it does show me an error page until I've corrected the error.
Here's the handler itself:
using System;
using System.Web;
public class CoursesAuthenticationHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
if (!context.Request.IsAuthenticated)
context.Response.Redirect("/");
}
}
So... that's pretty much it. The handler is being registered and analyzed at compile time, but doesn't actually do what it's expected to.
Edit: I realized that I'm using IIS 7.5 and that does indeed have an impact on this implementation.
For IIS 7, here's the Web.Config registration I used:
<handlers accessPolicy="Read, Execute, Script">
<add name="CoursesAuthenticationHandler"
verb="*"
path="/courses/*"
type="CoursesAuthenticationHandler"
resourceType="Unspecified" />
Edit 2: Progress! When not logged in, requests made to the /courses/ directory are redirected to the login page. However, authenticated requests to the /courses/ directory return empty pages...
Edit 3: Per #PatrickHofman's suggestion, I've switched to using an HttpModule.
The Web.Config registration:
<modules>
<add name="CourseAuthenticationModule" type="CourseAuthenticationModule" />
The code:
using System;
using System.Web;
public class CourseAuthenticationModule : IHttpModule
{
public void Dispose() { }
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(BeginRequest);
}
public void BeginRequest(Object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;
HttpRequest request = context.Request;
HttpResponse response = context.Response;
if (request.Path.ToLower().StartsWith("/courses/") && !request.IsAuthenticated)
{
response.Redirect("/");
}
}
}
Now the problem is that !request.IsAuthenticated is always false. If I'm logged in, and navigate to the /courses/ directory, I'm redirected to the homepage.
What's the deal?
I think the last problem lies in the fact that a HttpHander handles stuff. It is the end point of a request.
Since you didn't add anything to the request, the response will end up empty.
Are you looking for HttpModules? They can be stacked.
As a possible solution when only files are necessary: read the files yourself in the request by either reading and writing to response or use TransmitFile. For ASP.NET pages you need modules.

ASP.NET HttpModule Request handling

I would like to handle static file web requests through an HttpModule to show the documents in my CMS according to some policies. I can filter out a request, but I don't know how to directly process such a request as asp.net should do.
Is this what you're looking for? Assuming you're running in integrated pipeline mode, all requests should make it through here, so you can kill the request if unauthorized, or let it through like normal otherwise.
public class MyModule1 : IHttpModule
{
public void Dispose() {}
public void Init(HttpApplication context)
{
context.AuthorizeRequest += context_AuthorizeRequest;
}
void context_AuthorizeRequest(object sender, EventArgs e)
{
var app = (HttpApplication)sender;
// Whatever you want to test to see if they are allowed
// to access this file. I believe the `User` property is
// populated by this point.
if (app.Context.Request.QueryString["allow"] == "1")
{
return;
}
app.Context.Response.StatusCode = 401;
app.Context.Response.End();
}
}
<configuration>
<system.web>
<httpModules>
<add name="CustomSecurityModule" type="MyModule1"/>
</httpModules>
</system.web>
</configuration>

Execute some code for each request for ASP.NET (aspx and cshtml )

Is there a way to write some code that would be executed for each request to a .aspx or a .cshtml page in asp.net 4.5 apart from using a base page class. it is a very huge project and making changes to all pages to use a base page is a nightmare. Also i am not sure how would this be done for a cshtml page since they don't have a class.
Can we use the Application_BeginRequest and target only the aspx and cshtml files since the website is running in integrated mode.?
basically, i have to check if a user who is accessing the website has a specific ip address against a database and if yes then allow access otherwise redirect.
we are using IIS8 and ASP.Net 4.5 and ASP.Net Razor Web Pages
Also i am not sure how would this be done for a cshtml page since they don't have a class.
You could place a _ViewStart.cshtml file whose contents will get executed on each request.
Alternatively you could write a custom Http Module:
public class MyModule: IHttpModule
{
public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(OnBeginRequest);
}
public void Dispose()
{
}
public void OnBeginRequest(object s, EventArgs e)
{
// this code here's gonna get executed on each request
}
}
and then simply register this module in your web.config:
<system.webServer>
<modules>
<add name="MyModule" type="SomeNamespace.MyModule, SomeAssembly" />
</modules>
...
</system.webServer>
or if you are running in Classic Mode:
<system.web>
<httpModules>
<add name="MyModule" type="SomeNamespace.MyModule, SomeAssembly" />
</httpModules>
</system.web>
basically, i have to check if a user who is accessing the website has
a specific ip address against a database and if yes then allow access
otherwise redirect.
Inside the OnBeginRequest method you could get the current user IP:
public void OnBeginRequest(object sender, EventArgs e)
{
var app = sender as HttpApplication;
var request = app.Context.Request;
string ip = request.UserHostAddress;
// do your checks against the database
}
Asp.net MVC filters are especially designed for that purpose.
You would implement ActionFilterAttribute like this (maybe put this new class in a Filters folder in your webapp solution):
public class IpFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string ip = filterContext.HttpContext.Request.UserHostAddress;
if(!testIp(ip))
{
if (true /* You want to use a route name*/)
filterContext.Result = new RedirectToRouteResult("badIpRouteName");
else /* you want an url */
filterContext.Result = new RedirectResult("~/badIpController/badIpAction");
}
base.OnActionExecuting(filterContext);
}
private bool testIp(string inputIp)
{
return true /* do you ip test here */;
}
}
Then you have to decorate any action that would perform the ipcheck with IpFilter like so :
[IpFilter]
public ActionResult AnyActionWhichNeedsGoodIp()
{
/* do stuff */
}

Logging server-wide request data (including POST data) in IIS 6 / ASP.NET webforms

Here's the big picture. We're running a server in IIS 6 that hosts several web sites and applications, and we're in the process of moving the whole thing to a different data center with a slightly different setup. We've notified our users and updated our DNS info so that theoretically everyone will be happily hitting the new server from day 1, but we know that someone will inevitably fall through the cracks.
The powers that be want a "Listener" page/handler that will receive all requests to the server and log the entire request to a text file, including (especially) POST data.
That's where I'm stuck. I don't know how to implement a single handler that will receive all requests to the server. I vaguely understand IIS 6 redirection options, but they all seem to lose the POST data on the redirect. I also know a little about IIS 6's built-in logging, but it ignores POST data as well.
Is there a simple(ish) way to route all requests to the server so that they all hit a single handler, while maintaining post data?
EDIT: This is in WebForms, if that matters, but other solutions (if small) are definitely worth considering.
If all the requests are POST's to ASP.NET forms then you could plugin a HttpModule to capture and log this data.
You wouldn't have to rebuild all your applications to deploy this either. All it would take is to drop the HttpModule into each application's /bin folder and add it to the <httpModules> section of your web.config files. For example:
using System;
using System.Diagnostics;
using System.Web;
public class SimpleLogger : IHttpModule
{
private HttpApplication _application;
public void Dispose() { }
public void Init(HttpApplication context)
{
_application = context;
context.BeginRequest += new EventHandler(Context_BeginRequest);
}
void Context_BeginRequest(object sender, EventArgs e)
{
foreach (string key in _application.Request.Form.AllKeys)
{
// You can get everything on the Request object at this point
// Output to debug but you'd write to a file or a database here.
Debug.WriteLine(key + "=" + _application.Request.Form[key]);
}
}
}
In your web.config file add the logger:
<httpModules>
<add name="MyLogger" type="SimpleLogger, SimpleLogger"/>
</httpModules>
Be careful though. If your site captures credit card details or other sensitive data. You may need to ensure this is filtered out or have it encrypted and away from personel who should have no need to see this information.
Also if you're logging to files, make sure the log files are outside any public facing web folders.
Here is code of custom HTTP module we use to log HTTP POST request data.
using System;
using System.Web;
namespace MySolution.HttpModules
{
public class HttpPOSTLogger : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
private void context_BeginRequest(object sender, EventArgs e)
{
if (sender != null && sender is HttpApplication)
{
var request = (sender as HttpApplication).Request;
var response = (sender as HttpApplication).Response;
if (request != null && response != null && request.HttpMethod.ToUpper() == "POST")
{
var body = HttpUtility.UrlDecode(request.Form.ToString());
if (!string.IsNullOrWhiteSpace(body))
response.AppendToLog(body);
}
}
}
}
}
Do not forget to register it in web.config of you application.
Use system.WebServer section for IIS Integrated Model
<system.webServer>
<modules>
<add name="HttpPOSTLogger" type="MySolution.HttpModules.HttpPOSTLogger, MySolution.HttpModules" />
</modules>
</system.webServer>
Use system.web section for IIS Classic Model
<system.web>
<httpModules>
<add name="HttpPOSTLogger" type="MySolution.HttpModules.HttpPOSTLogger, MySolution.HttpModules"/>
</httpModules>
</system.web>
IIS log Before applying module:
::1, -, 10/31/2017, 10:53:20, W3SVC1, machine-name, ::1, 5, 681, 662, 200, 0, POST, /MySolution/MyService.svc/MyMethod, -,
IIS log After applying module:
::1, -, 10/31/2017, 10:53:20, W3SVC1, machine-name, ::1, 5, 681, 662, 200, 0, POST, /MySolution/MyService.svc/MyMethod, {"model":{"Platform":"Mobile","EntityID":"420003"}},
Full article:
https://www.codeproject.com/Tips/1213108/HttpModule-for-logging-HTTP-POST-data-in-IIS-Log

Need url's to be non secure when moving away from a secured link (without hardcoded url's in html)?

I have an asp.net site. It has an order form which is accessible at https://secure.example.com/order.aspx. The links on the site do not include the domain name. So for example the home page is 'default.aspx'.
The issue is that if I click on a link like the home page from the secure page, the url becomes https://secure.example.com/default.aspx instead of http://www.example.com/default.aspx.
What's a good way to handle this? The scheme should automatically work using any domain name based on where it's launched from. So if the site is launched from 'localhost', moving away from the secured page, the url's should be http://localhost/...
The navigation links are in a master page.
I suppose the best solution for this would be a http module.
The simplest implementation of it is posted below. useUnsecureConnection variable contains the value indicating whether moving away is required (should be calculated by yourself).
public class SecurityModule : IHttpModule
{
#region IHttpModule Members
public void Dispose()
{
}
public void Init(HttpApplication application)
{
application.BeginRequest += new EventHandler(application_BeginRequest);
}
#endregion
#region Events Handling
protected void application_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = ((HttpApplication)(sender));
HttpRequest request = application.Request;
HttpResponse response = application.Response;
// here should be you condition to determine
// whether to move away from secure page or not
bool useUnsecureConnection = true;
if (useUnsecureConnection && request.IsSecureConnection)
{
string absoluteUri = request.Url.AbsoluteUri;
response.Redirect(absoluteUri.Replace("https://", "http://"), true);
}
}
#endregion
}
And and of course don't forget to register module in your web.config:
<httpModules>
<!--Used to redirect secure connections to the unsecure ones
if necessary-->
<add name="Security"
type="{YourNamespace}.Handlers.SecurityModule,
{YourAssembly}" />
...
</httpModules>
</system.web>
BTW, for localhost the condition may looks like:
useUnsecureConnection = request.IsLocal;
which will be true if the IP address of the request originator is 127.0.0.1 or if the IP address of the request is the same as the server's IP address.

Resources