Restrict IP Address to access Web Application - c#

I have publish my Web Application in IIS and I getting Error while running
Server Error in '/' Application.
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: Could not load type 'SecurityHttpModule'.
My Web Config Like
<httpModules>
<add name="SecurityHttpModule type="SecurityHttpModule"/>
</httpModules>
My SecurityHttpModule Like
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public interface IHttpModule
{ }
namespace BankSuite
{
public class SecurityHttpModule : IHttpModule
{
public SecurityHttpModule() { }
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(Application_BeginRequest);
}
private void Application_BeginRequest(object source, EventArgs e)
{
HttpContext context = ((HttpApplication)source).Context;
string ipAddress = context.Request.UserHostAddress;
if (!IsValidIpAddress(ipAddress))
{
context.Response.StatusCode = 403; // (Forbidden)
}
}
private bool IsValidIpAddress(string ipAddress)
{
return (ipAddress == "127.0.0.1");
}
public void Dispose() { /* clean up */ }
}
}

It seems like you are missing a closing quote on the name
make sure it is not like that in reall config
Try specify using Fully qualified name such as NamespaceQualifiedTypeName, AssemblyName
so something like BankSuite.SecurityHttpModule, AssemblyName - where AssemblyName correspond to your dll name
also if you are using iis 7+ with integrated mode, use
<configuration>
<system.webServer>
<modules>
<add name="SecurityHttpModule" type="BankSuite.SecurityHttpModule, AssemblyName"/>
</modules>
</system.webServer>
</configuration>
instead.

Related

How to create a rule in a web.config file for a C# application, to block based on parameters in the URL

I want to create filter rule in the web.config file for a C# application, to block http://website.com/folder/Default.aspx,
but allow http://website.com/folder/Default.aspx?db=Database. Basically they don't have "Default.aspx?db=Database" in the URL, then it will either redirect them to a website another website (or Deny access).
You could implement an HttpModule that performs your desired logic. You can register it in the web.config without any code changes to the project. Just compile it into its own dll and drop that into the bin folder of your website.
The module
class RequestInterceptor : IHttpModule
{
public void Dispose()
{
}
// In the Init function, register for HttpApplication
// events by adding your handlers.
public void Init(HttpApplication application)
{
application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
}
private void Application_BeginRequest(Object source,
EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
//Inspect the URL and decide if this is a request you are interested in
//context.Request.Url
//context.Request.QueryString
//Redirect, or whatever...
//context.Response.Redirect(...)
}
}
The web.config:
<system.webServer>
<modules>
<add name="MyInterceptor" type="YourNamespace.RequestInterceptor, RequestInterceptor"/>
</modules>
...

asp.net HTTPHandler prevents page from loading

I have an ASP:NET web project with a simple HTTPHandler which filters out requests from outside IPs.
The code itself works, but the HTTPHandler prevents my page from loading. No error. No infinite load. There's just a blank page.
If I remove the reference in the config, it loads perfectly fine. It's definitely caused by the HTTPHandler. I've also stepped through the handler and the code is definitely reached, it's just that when the handler is done, the page doesn't load like it should.
Here is the code.
public class SecurityHttpHandler : IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
string ipAddress = context.Request.UserHostAddress;
if (!IsValidIpAddress(ipAddress))
{
context.Response.StatusCode = 403;
}
}
private bool IsValidIpAddress(string ipAddress)
{
return true; //for the time being, this will always return true
}
public void Dispose() { } //clean
}
The handler exists in another project (i have a reference to the assembly) and the httphandler is registered in my webprojects web.config as such:
<handlers>
<add name="SecurityHttpHandler" verb="*"
path="*Default.aspx"
type="MyProjects.CommonResources.Web.SecurityHttpHandler"
resourceType="Unspecified" />
</handlers>
I'm running IIS 7.5 in integrated mode. .net framework 4.0.
Let me know if I should add more code. I excluded the code from my web-project as the handler itself seems to be the cause early in the asp.net pipeline.

BLToolkit using a MySQL connection

I am making an attempt to establish a connection to a MySQL server using BLToolkit, and have installed MySql.Data (6.5.4), BLToolkit (4.1.12) and BLToolkit.MySql (4.1.12) via NuGet. I can make a connection to a MSSQL server in a single line, but have had trouble with MySQL and ended up with the following configuration file ...
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<BLToolkit>
<dataProviders>
<add type="BLToolkit.Data.DataProvider.MySqlDataProvider" />
</dataProviders>
</BLToolkit>
<configSections>
<section name="BLToolkit" type="BLToolkit.Configuration.BLToolkitSection, BLToolkit.4" />
</configSections>
<connectionStrings>
<add name="Test"
connectionString="Data Source=localhost;Port=3306;Database=bltest;User ID=root;Password=root;"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</configuration>
I have extended the DbManager class to implement a reference to the tables, and passed the name of the connection string into the base class. This is how I implemented this behaviour, which should be telling BLToolkit to load the connectionString from the configuration file ...
class BlDb : DbManager {
public BlDb()
: base("Test") {
return;
}
public Table<Car> Car { get { return GetTable<Car>(); } }
public Table<Make> Make { get { return GetTable<Make>(); } }
}
An exception, however, is thrown. The exception is "The type initializer for 'BLToolkit.Data.DbManager' threw an exception." with the inner exception being "Configuration system failed to initialize". How should I proceed? Please note that a similar question does exist on SO, Getting BLToolkit to work with MySQL, which might be a helpful reference for you but doesn't make any sense whatsoever to me. Is installing both NuGet packages not enough?
Firts you need to add the reference to the BLToolkit.Data.DataProvider.MySql.4.dll to your project. Then modify your extended DbManager class to look as the following
class BlDb : DbManager
{
public BlDb()
: base( new BLToolkit.Data.DataProvider.MySqlDataProvider(), "Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword" )
{
}
public Table<Car> Car { get { return GetTable<Car>(); } }
public Table<Make> Make { get { return GetTable<Make>(); } }
}
you can replace the hard-coded connection string and return it from your app.config file like ConfigurationManager.ConnectionStrings["Test"].ConnectionString

Developing a Module for IIS7

I've been working on a module for IIS7. I want to intercept requests from a specific browser. This is only in dev, but right now my code looks like this:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace MyNamespace
{
class MyModule : IHttpModule
{
#region IHttpModule Members
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(OnPreRequestHandlerExecute);
}
#endregion
public void OnPreRequestHandlerExecute(Object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
HttpRequest request = app.Context.Request;
string useragent = "AGENT: " + request.Headers["User-Agent"];
throw new HttpException(403, useragent);
// stuff here
}
}
}
I want to test this, but despite reading NUMEROUS articles on adding it to IIS7, I can't seem to get it working.
Examples:
http://learn.iis.net/page.aspx/366/developing-iis-70-modules-and-handlers-with-the-net-framework/
http://learn.iis.net/page.aspx/269/how-to-create-a-simple-iis-manager-module/
I've got the module strongly named, signed, you name it. I can't seem to get it to show up under Managed Modules for IIS.
If someone who has experience in this area could point me in the right direction I would greatly appreciate it! The code is very incomplete and I don't expect it to be perfect, but just to get it working under IIS7 right now would be a huge step forward.
Thanks!
You can simply drop the MyNameSpace.dll file in the bin folder, and then reference it like this in the section of the web.config:
<add name="MyModuleName" type="MyNamespace.MyModule, MyNamespace" preCondition="managedHandler" />

.NET 4.0 application on network share causes SecurityException

Today I experienced a weird problem while trying to remotely debug an application built for the .NET 4.0 runtime.
The application resides on a network share and executed by a remote machine. However the application crashes each time during load because of a SecurityException raised by a permission demand in the System.Configuration.ConfigurationManager.GetSection() method. I have not checked if other permission demands in the base class library also cause a security exception but in all cases this shouldn't be happening with the new CLR.
The application is running in full trust (checked it while debugging and as usual this must be always true for intranet applications in CLR 4.0) so I am clueless how a permission demand can cause an exception in this case. When built against the 3.5 SP1 runtime (which first introduced full trust for network shared apps by default) everythings runs as expected.
I pasted the sample code below. Any help is greatly appreciated.
using System;
using System.Configuration;
namespace ConsoleApplication1
{
public sealed class AssetsSection : ConfigurationSection
{
private static readonly ConfigurationProperty s_propPath;
private static readonly ConfigurationPropertyCollection s_properties;
static AssetsSection()
{
s_propPath = new ConfigurationProperty("path", typeof(String));
s_properties = new ConfigurationPropertyCollection()
{
s_propPath
};
}
public static AssetsSection Get()
{
return (AssetsSection) ConfigurationManager.GetSection("test/assets");
}
protected override ConfigurationPropertyCollection Properties
{
get
{
return s_properties;
}
}
public String Path
{
get
{
return (String) base[s_propPath];
}
set
{
base[s_propPath] = value;
}
}
}
class Program
{
static void Main(String[] args)
{
Console.WriteLine(AssetsSection.Get().Path);
Console.ReadLine();
}
}
}
And the App.config file;
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="test">
<section name="assets" type="ConsoleApplication1.AssetsSection, ConsoleApplication1"/>
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client"/>
</startup>
<test>
<assets path="..\Assets"/>
</test>
</configuration>
Try loading the configuration first and open your section on that:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AssetsSection configSection = (AssetsSection)config.GetSection("test/assets");
I ran into the same issue with .NET 4 and this works for me.
This is due to a known bug in .NET 4.0 when running the application from a network share.
The follow code fails with a SecurityException. Note that it only fails when you have defined a custom type for the section like in this example AssetsSection:
ConfigurationManager.GetSection("test/assets");
One fix is the solution suggestion by Timo to use a different API. Another solution is to apply the patch provided by Microsoft.
The bug and the related hotfix is filed under KB2580188.
If you add your own class to map the section like this:
[XmlRoot("Interface")]
public class MySectionClass
{
[XmlAttribute()]
public string MyAttr1
{
get;
set;
}
public string MyAttr2
{
get;
set;
}
}
You can use this code:
ConfigurationSection configSection =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).
GetSection("MySection");
XmlSerializer xs = new XmlSerializer(typeof(MySectionClass));
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(configSection.SectionInformation.GetRawXml());
XmlNodeReader xnr = new XmlNodeReader(xdoc.DocumentElement);
MySectionClass section = (MySectionClass)xs.Deserialize(xnr);
I'm speculating here, but I suspect it's your configuration file that's not trusted.
In your case, your configuration file is referencing a type ConsoleApplication1.AssetsSection that does not have a strong name that could be used as evidence.
Can you provide more details and the exact error message.

Categories