Add IP filtering to your Web site in the. NET Environment

Source: Internet
Author: User
Tags add format expression final net string to number access visual studio
Huaneng Group under the Enterprise website of a power plant (based on asp.net2.0 implementation, not allowed to modify the source program) requirements to achieve "factory users can directly access the entire site of all pages, outside the factory users can only access the specified page" function, this article will be in accordance with the requirements analysis, program design, coding, The sequence of deployment applications is a step-by-step elaboration of the overall solution formation process.

absrtact: Huaneng Group under the Enterprise website of a power plant (based on asp.net2.0 implementation, not allowed to modify the source program) requirements to achieve "factory users can directly access the entire site of all pages, outside the factory users can only access the specified page" function, In this paper, according to requirements analysis, Scheme design , coding implementation, deployment application sequence step-by-step to explain the formation of the whole solution process.

1. Demand Analysis

Through in-depth communication and communication, confirmed the power plant in the Enterprise website user Access control improvement requirements, the general situation is as follows:
A The website is based on asp.net2.0 implementation and does not allow modification of the source program
B Factory users can directly access all pages of the entire site, employees do not need authentication
c) Outside the factory users can only access the specified page

Clearly, they are adding an IP filtering function to the corporate web site, shutting them out when users outside the factory visit certain sensitive pages. First we need to set up an IP list and a URL list, the former contains all the IP in the factory, which contains all the URLs accessible to the outside of the factory, and the two lists are maintainable; Another core problem is that we need to choose a reasonable way to integrate the developed functional modules into the corporate web site, Http Modules incumbent.

In the ASP.net era, after IIS received the request and dispatched it to Aspnet_isapi.dll, the ASP.net engine began initializing the configured HTTP module (httpmodules) one by one. The correct HTTP handler is then invoked and the requested resource is rendered, and finally the generated token is returned to IIS and the requesting client (as shown in the following figure).


IIS and ASP.net are processing requests

If you want to know more about httpmodules, please check it yourself.

2. Programme design

2.1. Development environment

Programming Language: c#2.0
Development tools: Visual studio.net2008
Operating system: Windows2003 R2

2.2. Overview Design

The core idea of using httpmodules to implement IP filtering is to customize a HttpModule to capture each user request, then obtain the relevant user IP and the requested URL for logical judgment, and redirect the unauthorized request to an error prompt page. The decision logic for HTTP request authorization is:
1 to determine whether the request is from the local computer, it is automatically ignored, otherwise continue;
2 to determine whether the user IP belongs to the intranet (IP list), it is ignored, otherwise continue;
3 to determine whether the requested URL is authorized to access all users, is ignored, or continue;
4 redirects the request to the error prompt page.

Attaching a custom handler to the HttpApplication beginrequest event completes the capture of the HTTP request. In addition, to facilitate the maintenance of the parameters (IP list, url list, error prompt, and so on) that we should store in a particular XML configuration file in order to be more efficient, we also need to perform a memory-level cache processing of the configuration file and the IP, URL matching algorithm for appropriate optimization.

2.3. Configure caching algorithms

The cache of configuration files is based on the implementation logic of the Microsoft CommonServer Project, Persisting configuration information into entity classes are stored in HttpContext.Current.Cache, the cached information is automatically emptied after the configuration file occurs, and the next time you perform a persistent operation, you do not need to restart the site. In this paper, the caching logic of CommonServer is not discussed in depth, and the interested persons can search the relevant data by themselves.

2.4. IP List algorithm

Through the above, the current project used in the IP list contains a very limited amount of data, is the Power Plant Web server can be effectively identified in the intranet IP of the poor.

So we'll cache the entire IP list, using it to retrieve whether the current user IP exists in the list. For the storage of specific IP, we can view it as 256, and convert the IP string to number format (for example: 192.168.10.3 visual 192*256*256*256+168*256*256+10*256+3= 3232238083, regardless of the IPV6), in the format of parameter configuration, we should support a single IP or IP segment in addition to the IP list.

2.5. URL list algorithm

In terms of specific requirements, the URL list is a whitelist that authorizes the extranet user to access the in other words, "external users in addition to the list of other people are not accessible", once the data security level is reduced, will not appear "external users in addition to the list of other can access" situation? In order to be compatible with this follow-up scenario, we need to define a "blacklist" (isblacklist) additional parameter for the URL list, and it is obviously unrealistic for the dynamic Web site to raise the URL, whether it's a blacklist or a whitelist, so we can change our thinking, Change the final URL to a regular expression, that is, maintain a regular expression list that matches the target URL, perform a matching action on a regular expression for the specific URL that the user requests, and, if a match succeeds, the current URL exists in the URL list.

3. Code implementation

Since this article provides all of the C # source downloads, this section only gives a brief description of the main files in the source code compression package:

-->Dotcommon.websitefilter
│dotcommonwebsitefilter.cfg.xml
│websitefilterconfiguration.cs
│websitefilterhttpmodule.cs
├─util
│globescache.cs
│xmlattributereader.cs
└─websitefilter
IPMatchEngine.cs
UrlMatchCondition.cs
UrlMatchEngine.cs


    • dotcommonwebsitefilter.cfg.xml
      Run the parameter configuration file
    • websitefilterconfiguration.cs
      Configuration file entity classes
    • websitefilterhttpmodule.cs
      A custom HTTP module that implements the System.Web.IHttpModule interface
    • globescache.cs
      Global Cache Manipulation Class
    • xmlattributereader.cs
      XML Node Property Reader
    • ipmatchengine.cs
      IP matching engine
    • urlmatchcondition.cs
      URL matching Criteria (matching regular expressions)
    • urlmatchengine.cs
      URL matching engine

The core code for the BeginRequest custom handler in WebsiteFilterHttpModule.cs is as follows:

-->
void Context_beginrequest (object sender, EventArgs e)
{
if (HttpContext.Current.Request.IsLocal)//ignores local computer requests
Return
string ip = HttpContext.Current.Request.UserHostAddress;
if (! Websitefilterconfiguration.getconfig (). Pickedips.ismatch (IP))
{//If no guest IP is found in the IP list
string rawurl = HttpContext.Current.Request.RawUrl;
Urlmatchengine pu = websitefilterconfiguration.getconfig (). Pickedurls;
The list contains the current URL and the list is blacklisted, the list does not contain the current URL, and the list is not blacklisted when it needs to be turned
In other words, the "equipped with results" and "whether blacklist" values are consistent with the need to turn
if (PU. IsMatch (rawurl) = = pu. Isblacklist)
{//private URL automatic redirection
HttpContext.Current.Response.Redirect (PU. ErrorPage);
}
}
}


4. Deployment Applications

4.1. DotCommonWebsiteFilter.cfg.xml configuration file

The root node of the configuration file is Dotcommon, and all configuration information is a child of the Websitefilter node. The Pickedurl node corresponds to the URL list, isblacklist (1 is 0 NO) indicates whether it is a blacklist, errorpage specifies the path to the error prompt page, and its child nodes add can be repeated, and the regular expression text is specified through the pattern attribute. The configuration shown above shows that only the home page (Default.aspx) of the Web site allows extranet users to access it.

The PICKEDIP node corresponds to the IP list, and the valid child nodes include Add, remove, clear three. For example, the first add indicates that the intranet IP is 192.168.10.1, 192.168.10.2, 192.168.10.3, 192.168.10.4, 192.168.10.5 Five, and the second row deletes 192.168.10.2, 192.168.10.3, 192.168.10.4 still have 192.168.10.1, 192.168.10.5 Two, and add 192.168.10.3 to the third line, the final intranet IP list is 192.168.10.1, 192.168.10.3, 192.168.10.5 three.

4.2. Integration in the corporate web site

    1. Configure the parameters in DotCommonWebsiteFilter.cfg.xml and copy them to the site root directory.
    2. Copy the DotCommon.WebsiteFilter.dll file to the Web site Bin directory.
    3. Create an Error prompt page (for example, sorry.htm) that corresponds to the configuration file in the site root directory.
    4. Modify Web.config to register the Websitefilter module under the <add name= "Websitefilter"
      Type= "Dotcommon.websitefilterhttpmodule, Dotcommon.websitefilter"/>
    5. From intranet, external network access to the corporate Web site to view the effect of the operation.

Conclusion

This article only elaborates the solution idea process for the specific demand, hoped that can be helpful to the reader, welcome proposes the improvement opinion.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.