Add IP filtering for websites in. NET Environment

Source: Internet
Author: User

Abstract:The enterprise website of a power plant in Huaneng Group (Based on Asp. net2.0 implementation, does not allow modification of the source program) requires the implementation of the "factory users can directly access all the pages of the entire site, factory users can only access the specified page" function, this article will gradually explain the entire solution formation process based on the demand analysis, solution design, coding implementation, and application deployment sequence.

1. Requirement Analysis

Through in-depth communication, the improvement requirements of the power plant for Enterprise Website user access control are confirmed. The general situation is as follows:
A) websites are implemented based on Asp. Net2.0 and cannot modify source programs.
B) in-plant users can directly access all pages of the entire site, and employees do not need authentication.
C. users outside the factory can only access the specified page

Obviously, they add an IP address filtering function for enterprise websites to deny access to some sensitive pages by users outside the factory. First, we need to set an IP address list and a Url list. The former includes all the IP addresses in the factory, and the latter includes all the URLs accessible to users outside the factory. The two lists are maintained; another core issue is that we need to choose a reasonable way to integrate the developed functional modules into the enterprise website. It is incumbent on HttpModules.

In Asp. net Era, after IIS receives the request and schedules it to aspnet_isapi.dll, ASP. the NET engine starts to initialize the configured HTTP module (HttpModules) one by one, and then calls the correct HTTP processing program and presents the requested resources, finally, return the generated tag to IIS and the request client, as shown in ).

 

IIS and ASP. NET are processing requests

For more information about HttpModules, see.

2. solution design

2.1. Development Environment

Programming Language: C #2.0.
Development Tool: Visual Studio. NET2008
Operating System: windows2003 R2

2.2. Outline Design

The core idea of using HttpModules to implement the IP filtering function is to customize an HttpModule to capture each user request, and then obtain the relevant user IP address and the requested Url for logical judgment, redirect unauthorized requests to an error prompt page. The logic for determining whether an Http request is authorized is:
1) checks whether the request is from a local computer. If yes, the request is automatically ignored; otherwise, the request continues;
2) check whether the user's IP address belongs to the Intranet (IP address list). If yes, ignore it; otherwise, continue;
3) if the requested Url authorizes all users to access it, ignore it; otherwise, continue;
4) redirect requests to the error prompt page.

 

 

You can add a Custom Handler to the BeginRequest event of HttpApplication to complete Http request capturing. In addition, to facilitate maintenance, we should store the parameters (IP address list, Url list, error prompt page path, and so on) required for running the program in a specific XML configuration file. To improve efficiency, we also need to perform memory-level cache processing on the configuration file and optimize the IP and Url matching algorithms.

2.3. Configure cache Algorithms

For configuration file caching, refer to the implementation logic in the Microsoft CommonServer project to persistently save configuration information as an object class stored in HttpContext. current. cache, the Cache information is automatically cleared after the configuration file is created. The persistence operation is performed again during the next visit without restarting the site. This article does not discuss the caching logic of CommonServer in depth. Interested parties can search for relevant information on their own.

2.4. IP list Algorithm

As we can see from the above, the IP list used in the current project contains a very limited amount of data, that is, the power plant web server can effectively identify the Intranet IP address.

Therefore, we can cache the entire IP address list and directly retrieve whether the current user's IP address exists in the list. In terms of storage of specific IP addresses, we can regard it as a 256 hexadecimal system, and convert the IP string to a digital format (for example: 192.168.10.3 can be viewed as 192*256*256*256*168*256*256 + 10*256 + 3 = 3232238083, regardless of IPV6). In terms of parameter configuration format, we should also support adding or deleting IP addresses in a single IP address or IP segment.

2.5. Url list Algorithm

For specific requirements, the Url list is a whitelist that authorizes Internet users to access. To put it another way, "Internet users cannot access anything except the list ", if the security level of data is reduced, will there be a situation where "access is allowed for Internet users except for all the items in the list? In order to be compatible with this subsequent scenario, we need to define an additional parameter for the Url list "whether to blacklist" (IsBlacklist). In addition, it is obviously unrealistic for dynamic websites to make URLs obsolete, whether it is to maintain the blacklist or whitelist, we can change the idea and change the final Url to a regular expression, that is, to maintain a list of regular expressions that can match the target Url, the matching operation is performed on the specific URLs in the regular expression one by one. If one matching succeeds, the current Url is considered to exist in the Url list.

3. coding implementation

As this article provides all the c # source code downloads, this section only briefly describes the main files in the source code 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 parameter configuration file
  • WebsiteFilterConfiguration. cs
    Configuration File entity class
  • WebsiteFilterHttpModule. cs
    Implement the custom Http module of the System. Web. IHttpModule Interface
  • GlobesCache. cs
    Global Cache Control
  • XmlAttributeReader. cs
    Xml node attribute Reader
  • IPMatchEngine. cs
    IP matching engine
  • UrlMatchCondition. cs
    Url matching conditions (matching with regular expressions)
  • UrlMatchEngine. cs
    Url matching engine

 

The core code of the inrequest Custom Handler in WebsiteFilterHttpModule. cs is as follows:


Void context_BeginRequest (object sender, EventArgs e)
{
If (HttpContext. Current. Request. IsLocal) // ignore local computer requests
Return;
String ip = HttpContext. Current. Request. UserHostAddress;
If (! WebsiteFilterConfiguration. GetConfig (). PickedIPs. IsMatch (ip ))
{// If no visitor IP address is found in the ip address list
String rawUrl = HttpContext. Current. Request. RawUrl;
UrlMatchEngine pu = WebsiteFilterConfiguration. GetConfig (). PickedUrls;
// When 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, you need to turn
// In other words, when the value of "configuration result" is the same as that of "blacklist or not", you need to switch
If (pu. IsMatch (rawUrl) = pu. IsBlacklist)
{// Automatic redirection of Non-public URLs
HttpContext. Current. Response. Redirect (pu. ErrorPage );
}
}
}

 

4. Deploy the application

4.1. DotCommonWebsiteFilter. cfg. xml configuration file

 

 

The root node of the configuration file is DotCommon, and all configuration information is a subitem of the WebsiteFilter node. The Url list corresponding to the PickedUrl node. IsBlacklist (1 is 0 No) indicates whether it is blacklisted. ErrorPage specifies the path of the error prompt page. Its subnode add can appear repeatedly and the regular expression text is specified through the pattern attribute, the configuration shown in the preceding figure indicates that only the homepage (default. aspx) allows access by Internet users.

 

The IP address list corresponding to the PickedIP node. Valid subnodes include add, remove, and clear. For example, the first add command indicates that the Intranet ip addresses are 192.168.10.1, 192.168.10.2, 192.168.10.3, 192.168.10.4, and 192.168.10.5. In the second row, 192.168.10.2, 192.168.10.3, 192.168.10.4, and 192.168.10.1 and 192.168.10.5 are deleted; add 192.168.10.3 to the third line. The final Intranet IP addresses are 192.168.10.1, 192.168.10.3, and 192.168.10.5.

4.2. Integration in enterprise websites

  1. Configure the parameters in DotCommonWebsiteFilter. cfg. xml and copy them to the website root directory.
  2. Copy the DotCommon. WebsiteFilter. dll file to the bin directory of the website.
  3. Create a page (such as sorry.htm) corresponding to the configuration file in the website root directory ).
  4. Modify Web. config and register the WebsiteFilter module under the

    Code highlighting produced by Actipro CodeHighlighter (freeware)
    http://www.CodeHighlighter.com/

    --><HttpModules>
    <Add name = "WebsiteFilter"
    Type = "DotCommon. WebsiteFilterHttpModule, DotCommon. WebsiteFilter"/>
    </HttpModules>

  5. Access the enterprise website from the Intranet and Internet respectively to view the running effect.

Conclusion

This article only describes the conception process of the solution based on specific requirements, and hopes to help readers. We welcome suggestions for improvement.

Source code (): http://files.cnblogs.com/cncxz/DotCommon_WebsiteFilter.rar

 

 

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.