超碰人人人人人,亚洲AV午夜福利精品一区二区,亚洲欧美综合区丁香五月1区,日韩欧美亚洲系列

LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發(fā)文檔 其他文檔  
 
網(wǎng)站管理員

通過C#控制IIS網(wǎng)站只允許指定的動態(tài)IP白名單地址訪問,訪問者不在白名單的一律跳轉(zhuǎn)到其他指定的外部網(wǎng)站網(wǎng)頁

admin
2025年3月15日 17:39 本文熱度 847

以下是完整的C代碼實(shí)現(xiàn)方案,結(jié)合IIS動態(tài)配置與全自動跳轉(zhuǎn)功能:

一、核心功能實(shí)現(xiàn)代碼

using Microsoft.Web.Administration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

public class IPFilterAttribute : ActionFilterAttribute
{
    private static List<string> _allowedIPs = new List<string>
    {
        "192.168.1.1",
        "10.0.0.0-10.0.0.255" // 支持IP段格式
    };

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        string clientIP = GetClientIP();
        if (!IsAllowedIP(clientIP))
        {
            filterContext.Result = new RedirectResult("https://external-block-page.com");
            LogBlockedIP(clientIP);
        }
    }

    private string GetClientIP()
    {
        string ip = HttpContext.Current.Request.Headers["X-Forwarded-For"]?.Split(',')[0];
        return string.IsNullOrEmpty(ip) ? HttpContext.Current.Request.UserHostAddress : ip;
    }

    private bool IsAllowedIP(string ip)
    {
        return _allowedIPs.Contains(ip) || IPRangeContains(ip, _allowedIPs);
    }

    private bool IPRangeContains(string ip, List<string> ipRanges)
    {
        foreach (var range in ipRanges.Where(r => r.Contains('-')))
        {
            var start = IPAddress.Parse(range.Split('-')[0]);
            var end = IPAddress.Parse(range.Split('-')[1]);
            var client = IPAddress.Parse(ip);
            if (client.AddressFamily == AddressFamily.InterNetworkV6)
                throw new NotSupportedException("IPv6 range check not implemented");
            var bytes = client.GetAddressBytes();
            var startBytes = start.GetAddressBytes();
            var endBytes = end.GetAddressBytes();
            if (bytes.CompareTo(startBytes) >= 0 && bytes.CompareTo(endBytes) <= 0)
                return true;
        }
        return false;
    }

    private void LogBlockedIP(string ip)
    {
        File.AppendAllText("blocked_ips.log", $"{DateTime.Now}: Blocked IP - {ip}\n");
    }

    public static void SyncIISWhitelist()
    {
        try
        {
            using (ServerManager serverManager = new ServerManager())
            {
                var siteName = "OA_SITE"; // 替換為實(shí)際網(wǎng)站名稱
                var site = serverManager.Sites.FirstOrDefault(s => s.Name == siteName);
                if (site == null) throw new Exception($"網(wǎng)站 '{siteName}' 未找到");

                var config = serverManager.GetApplicationHostConfiguration();
                var ipSecuritySection = config.GetSection("system.webServer/security/ipSecurity", siteName);
                
                if (ipSecuritySection == null)
                {
                    ipSecuritySection = config.CreateSection("system.webServer/security/ipSecurity", siteName);
                    ipSecuritySection["allowUnlisted"] = false; // 關(guān)鍵配置:未列出的IP自動拒絕
                }

                var ipCollection = ipSecuritySection.GetCollection();
                ipCollection.Clear(); // 清空現(xiàn)有規(guī)則

                foreach (var ip in _allowedIPs)
                {
                    var addElement = ipCollection.CreateElement("add");
                    addElement["ipAddress"] = ip;
                    addElement["action"] = "Allow";
                    addElement["allowed"] = true;
                    ipCollection.Add(addElement);
                }

                serverManager.CommitChanges();
            }
        }
        catch (Exception ex)
        {
            File.AppendAllText("sync_error.log", $"{DateTime.Now}: {ex.Message}\n");
        }
    }
}

二、關(guān)鍵配置說明

IIS配置文件修改

在 web.config 中添加以下配置,啟用IP安全規(guī)則:

<system.webServer>
  <security>
    <ipSecurity allowUnlisted="false" />
  </security>
</system.webServer>

引用說明:此配置確保未在白名單中的IP自動被拒絕。

管理員權(quán)限要求

程序需以管理員身份運(yùn)行,否則無法修改IIS配置。

在Windows中可通過:

 右鍵exe -> 屬性 -> 兼容性 -> 以管理員身份運(yùn)行此程序 

IP范圍支持

代碼支持IP段格式(如 10.0.0.0-10.0.0.255 ),通過 IPRangeContains 方法實(shí)現(xiàn)范圍檢查。

三、部署與調(diào)用步驟

初始化白名單同步

在網(wǎng)站啟動時(shí)調(diào)用 SyncIISWhitelist() 方法,確保IIS規(guī)則與代碼一致:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    SyncIISWhitelist(); // 同步白名單到IIS
}

應(yīng)用層攔截配置

在 Global.asax 中注冊全局過濾器:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new IPFilterAttribute());
    }
}

日志與監(jiān)控

封禁日志記錄到 blocked_ips.log ,便于審計(jì)。

建議集成ELK或Prometheus監(jiān)控日志文件,異常IP封禁時(shí)觸發(fā)告警。

 

四、功能驗(yàn)證

白名單生效驗(yàn)證

通過IIS管理器檢查網(wǎng)站配置,確認(rèn) ipSecurity 節(jié)點(diǎn)已正確添加白名單IP。

使用非白名單IP訪問網(wǎng)站,應(yīng)自動跳轉(zhuǎn)至外部頁面。

IP范圍測試

添加IP段 192.168.2.0-192.168.2.100 到白名單,驗(yàn)證該網(wǎng)段內(nèi)所有IP均可訪問。

 

五、安全增強(qiáng)建議

雙重驗(yàn)證機(jī)制

在跳轉(zhuǎn)前增加驗(yàn)證碼驗(yàn)證,防止自動化工具繞過IP限制。

動態(tài)白名單更新

通過管理后臺提供界面,支持手動添加/刪除白名單IP。

定期從AD域控同步內(nèi)部員工IP。

備份與回滾

定期備份IIS配置文件( %windir%\System32\inetsrv\config\applicationHost.config )。

實(shí)現(xiàn)配置變更回滾功能,防止誤操作導(dǎo)致服務(wù)中斷。


通過以上方案,可實(shí)現(xiàn)全自動化的IP白名單控制與訪問跳轉(zhuǎn),有效抵御外部攻擊。建議配合WAF(Web應(yīng)用防火墻)和DDoS防護(hù)服務(wù),構(gòu)建縱深防御體系。


該文章在 2025/3/15 17:40:26 編輯過
關(guān)鍵字查詢
相關(guān)文章
正在查詢...
點(diǎn)晴ERP是一款針對中小制造業(yè)的專業(yè)生產(chǎn)管理軟件系統(tǒng),系統(tǒng)成熟度和易用性得到了國內(nèi)大量中小企業(yè)的青睞。
點(diǎn)晴PMS碼頭管理系統(tǒng)主要針對港口碼頭集裝箱與散貨日常運(yùn)作、調(diào)度、堆場、車隊(duì)、財(cái)務(wù)費(fèi)用、相關(guān)報(bào)表等業(yè)務(wù)管理,結(jié)合碼頭的業(yè)務(wù)特點(diǎn),圍繞調(diào)度、堆場作業(yè)而開發(fā)的。集技術(shù)的先進(jìn)性、管理的有效性于一體,是物流碼頭及其他港口類企業(yè)的高效ERP管理信息系統(tǒng)。
點(diǎn)晴WMS倉儲管理系統(tǒng)提供了貨物產(chǎn)品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質(zhì)期管理,貨位管理,庫位管理,生產(chǎn)管理,WMS管理系統(tǒng),標(biāo)簽打印,條形碼,二維碼管理,批號管理軟件。
點(diǎn)晴免費(fèi)OA是一款軟件和通用服務(wù)都免費(fèi),不限功能、不限時(shí)間、不限用戶的免費(fèi)OA協(xié)同辦公管理系統(tǒng)。
Copyright 2010-2025 ClickSun All Rights Reserved