原文网址: http://www.cnblogs.com/csdev

Networkcomms 是一款C# 语言编写的TCP/UDP通信框架  作者是英国人  以前是收费的 目前作者已经开源  许可是:Apache License v2

开源地址是:https://github.com/MarcFletcher/NetworkComms.Net

DOSProtection用于放置Dos攻击,可以封IP,默认没有启用
namespace NetworkCommsDotNet.Tools
{
    /// <summary>
    /// NetworkComms.Net class used for providing Denial Of Service (DOS) protection features.
    /// If enabled, malformed data events and connection initialises are tracked. If above
    /// set thresholds IPAddresses are banned.
    /// 用于DOS攻击防御的类
    /// 如果启用  则格式不正确的数据和连接请求将会被跟踪  并对相应的IP进行查封
    /// </summary>
    public class DOSProtection
    {
        /// <summary>
        /// A local thread safety locker
        /// 同步锁
        /// </summary>
        object _syncRoot = new object();

        /// <summary>
        /// Addresses that are currently banned. Key is remote IPAddress, value is time banned.
        /// 被查封的IP
        /// </summary>
        Dictionary<IPAddress, DateTime> _bannedAddresses = new Dictionary<IPAddress, DateTime>();

        /// <summary>
        /// First key is remote IPAddress, second key is DateTime.Ticks, value is the malformed count for that DateTime.ticks
        /// 格式不正确的数据的相关信息    IP  发生的时间  次数
        /// </summary>
        Dictionary<IPAddress, Dictionary<long, int>> _malformedCountDict = new Dictionary<IPAddress, Dictionary<long, int>>();

        /// <summary>
        /// First key is remote IPAddress, second key is DateTime.Ticks, value is the connection initialisation count for that DateTime.ticks
        /// 格式不正确的连接请求    IP  发生的时间  次数
        /// </summary>
        Dictionary<IPAddress, Dictionary<long, int>> _connectionInitialiseCountDict = new Dictionary<IPAddress, Dictionary<long, int>>();

        /// <summary>
        /// The current state of DOS protection
        /// 是否启用DOS攻击防御
        /// </summary>
        public bool Enabled { get; set; }

        /// <summary>
        /// The timeout after which time a banned IPAddress may have access again. Default is 10 minutes.
        /// 相关IP查封的时间
        /// </summary>
        public TimeSpan BanTimeout { get; set; }

        /// <summary>
        /// The time within which if MalformedCountInIntervalBeforeBan or ConnectionInitialiseCountInIntervalBeforeBan
        /// is reached a peer will be banned. Default is 5 minutes.
        /// 查封相关的一个时间段
        /// 默认5分钟
        /// 比如说5分钟内收到2个不规则数据,启用查封
        /// </summary>
        public TimeSpan LogInterval { get; set; }

        /// <summary>
        /// The number of malformed data counts to log within LogInterval before an IPAddress is banned. Default is 2.
        /// LogInterval时间内收到不规则数据将会被查封  默认为2个
        /// </summary>
        public int MalformedCountInIntervalBeforeBan { get; set; }

        /// <summary>
        /// The number of connection initialises to log within LogInterval before an IPAddress is banned. Default is 100
        /// LogInterval时间内收到不规则连接请求  默认为100个  启用查封
        /// </summary>
        public int ConnectionInitialiseCountInIntervalBeforeBan { get; set; }

        /// <summary>
        /// Initialise a new instance of DOS protection.
        /// 初始化
        /// </summary>
        public DOSProtection()
        {
            Enabled = false;
            BanTimeout = , , );
            LogInterval = , , );
            MalformedCountInIntervalBeforeBan = ;
            ConnectionInitialiseCountInIntervalBeforeBan = ;
        }

        /// <summary>
        /// Log a malformed data event for the provided remote IPAddress.
        /// 记录不规则数据时间 根据指定的IP
        /// </summary>
        /// <param name="remoteIPAddress"></param>
        /// <returns>如果指定IP已经查封 返回True *** True if the remote IPAddress is now banned, otherwise false.</returns>
        public bool LogMalformedData(IPAddress remoteIPAddress)
        {
            bool ipAddressNowBanned = false;

            lock (_syncRoot)
            {
                //Record the malformed data count
                //记录不规则数据数量
                long tick = DateTime.Now.Ticks;
                if (_malformedCountDict.ContainsKey(remoteIPAddress))
                {
                    if (_malformedCountDict[remoteIPAddress].ContainsKey(tick))
                        _malformedCountDict[remoteIPAddress][tick]++;
                    else
                        _malformedCountDict[remoteIPAddress].Add(tick, );
                }
                else
                    _malformedCountDict.Add(remoteIPAddress,  } });

                //Delete any tick keys which are greater than LogInterval
                //删除超过LogInterval时间段的数据
                List<long> existingIPAddressTickKeys = new List<long>(_malformedCountDict[remoteIPAddress].Keys);

                //Sort from oldest to newest
                //排序
                existingIPAddressTickKeys.Sort();

                //Keep removing tick keys until we are within LogInterval
                //删除超过指定时间段的数据
                ; i < existingIPAddressTickKeys.Count; i++)
                {
                    if (DateTime.Now - new DateTime(existingIPAddressTickKeys[i]) > LogInterval)
                        _malformedCountDict[remoteIPAddress].Remove(existingIPAddressTickKeys[i]);
                    else
                        break;
                }

                //Add up the remaining counts and see if we need to ban this peer
                //查看是否需要查封此IP
                ;
                foreach(int count in _malformedCountDict[remoteIPAddress].Values)
                    currentMalformedCount += count;

                if (currentMalformedCount >= MalformedCountInIntervalBeforeBan)
                {
                    ipAddressNowBanned = true;
                    _bannedAddresses[remoteIPAddress] = new DateTime(tick);
                }
                else
                {
                    ipAddressNowBanned = false;
                    _bannedAddresses.Remove(remoteIPAddress);
                }

                //Remove the remote IPAddress key if no events are left
                //如果没有响应的时间 删除相应的IP
                )
                    _malformedCountDict.Remove(remoteIPAddress);
            }

            return ipAddressNowBanned;
        }

        /// <summary>
        /// Log a connection initialisation for the provided remote IPAddress.
        /// 记录一个格式错误的连接初始化 根据指定IP
        /// </summary>
        /// <param name="remoteIPAddress"></param>
        /// <returns>True if the remote IPAddress is now banned, otherwise false.</returns>
        public bool LogConnectionInitialise(IPAddress remoteIPAddress)
        {
            bool ipAddressNowBanned = false;

            lock (_syncRoot)
            {
                //Record the malformed data count
                //记录格式错误的数据的次数
                long tick = DateTime.Now.Ticks;
                if (_connectionInitialiseCountDict.ContainsKey(remoteIPAddress))
                {
                    if (_connectionInitialiseCountDict[remoteIPAddress].ContainsKey(tick))
                        _connectionInitialiseCountDict[remoteIPAddress][tick]++;
                    else
                        _connectionInitialiseCountDict[remoteIPAddress].Add(tick, );
                }
                else
                    _connectionInitialiseCountDict.Add(remoteIPAddress,  } });

                //Delete any tick keys which are greater than LogInterval
                //删除超过LogInterval时间段的数据
                List<long> existingIPAddressTickKeys = new List<long>(_connectionInitialiseCountDict[remoteIPAddress].Keys);

                //Sort from oldest to newest
                //排序
                existingIPAddressTickKeys.Sort();

                //Keep removing tick keys until we are within LogInterval
                //删除超过LogInterval时间段的数据
                ; i < existingIPAddressTickKeys.Count; i++)
                {
                    if (DateTime.Now - new DateTime(existingIPAddressTickKeys[i]) > LogInterval)
                        _connectionInitialiseCountDict[remoteIPAddress].Remove(existingIPAddressTickKeys[i]);
                    else
                        break;
                }

                //Add up the remaining counts and see if we need to ban this peer
                //查看是否需要查封相关的数据
                ;
                foreach (int count in _connectionInitialiseCountDict[remoteIPAddress].Values)
                    currentConnectionInitialisationCount += count;

                //Make a decision based on currentConnectionInitialisationCount
                //是否查封
                if (currentConnectionInitialisationCount >= ConnectionInitialiseCountInIntervalBeforeBan)
                {
                    ipAddressNowBanned = true;
                    _bannedAddresses[remoteIPAddress] = new DateTime(tick);
                }
                else
                {
                    ipAddressNowBanned = false;
                    _bannedAddresses.Remove(remoteIPAddress);
                }

                //Remove the remote IPAddress key if no events are left
                //如果事件不存在 删除相关IP
                )
                    _connectionInitialiseCountDict.Remove(remoteIPAddress);
            }

            return ipAddressNowBanned;
        }

        /// <summary>
        /// Returns true if the provided IPAddress has been banned due to DOSProtection.
        /// 如果参数中IP已经被查封  返回True
        /// </summary>
        /// <param name="remoteIPAddress">The IPAddress to check</param>
        /// <returns></returns>
        public bool RemoteIPAddressBanned(IPAddress remoteIPAddress)
        {
            lock(_syncRoot)
            {
                if (_bannedAddresses.ContainsKey(remoteIPAddress))
                {
                    //If the ban time is longer than the timeout we can allow it again
                    //如果过了封杀的时间  从查封列表中删除
                    if (DateTime.Now - _bannedAddresses[remoteIPAddress] > BanTimeout)
                    {
                        _bannedAddresses.Remove(remoteIPAddress);
                        return false;
                    }
                    else
                        return true;
                }
                else
                    return false;
            }
        }
    }
}

介绍开源的.net通信框架NetworkComms框架 源码分析(十)DOSProtection的更多相关文章

  1. DotNetty网络通信框架学习之源码分析

    DotNetty网络通信框架学习之源码分析 有关DotNetty框架,网上的详细资料不是很多,有不多的几个博友做了简单的介绍,也没有做深入的探究,我也根据源码中提供的demo做一下记录,方便后期查阅. ...

  2. 深入理解分布式调度框架TBSchedule及源码分析

    简介 由于最近工作比较忙,前前后后花了两个月的时间把TBSchedule的源码翻了个底朝天.关于TBSchedule的使用,网上也有很多参考资料,这里不做过多的阐述.本文着重介绍TBSchedule的 ...

  3. 设计模式(十五)——命令模式(Spring框架的JdbcTemplate源码分析)

    1 智能生活项目需求 看一个具体的需求 1) 我们买了一套智能家电,有照明灯.风扇.冰箱.洗衣机,我们只要在手机上安装 app 就可以控制对这些家电工作. 2) 这些智能家电来自不同的厂家,我们不想针 ...

  4. 设计模式(二十一)——解释器模式(Spring 框架中SpelExpressionParser源码分析)

    1 四则运算问题 通过解释器模式来实现四则运算,如计算 a+b-c 的值,具体要求 1) 先输入表达式的形式,比如 a+b+c-d+e,  要求表达式的字母不能重复 2) 在分别输入 a ,b, c, ...

  5. $Django cbv源码分析 djangorestframework框架之APIView源码分析

    1 CBV的源码分析 #视图 class login (View): pass #路由 url(r'^books/$', views.login.as_view()) #阅读源码: #左侧工程栏--- ...

  6. ④NuPlayer播放框架之Renderer源码分析

    [时间:2016-11] [状态:Open] [关键词:android,nuplayer,开源播放器,播放框架,渲染器,render] 0 导读 之前我们分析了NuPlayer的实现代码,本文将重点聚 ...

  7. ⑤NuPlayer播放框架之GenericSource源码分析

    [时间:2017-01] [状态:Open] [关键词:android,nuplayer,开源播放器,播放框架,GenericSource] 0 导读 GenericSource是NuPlayer:: ...

  8. ③NuPlayer播放框架之类NuPlayer源码分析

    [时间:2016-10] [状态:Open] [关键词:android,nuplayer,开源播放器,播放框架] 0 引言 差不多一个月了,继续分析AOSP的播放框架的源码.这次我们需要深入分析的是N ...

  9. Laravel开发:Laravel框架门面Facade源码分析

    前言 这篇文章我们开始讲 laravel 框架中的门面 Facade,什么是门面呢?官方文档: Facades(读音:/fəˈsäd/ )为应用程序的服务容器中可用的类提供了一个「静态」接口.Lara ...

  10. Android 应用框架层 SQLite 源码分析

    概述   Android 在应用框架层为开发者提供了 SQLite 相关操作接口,其归属于android.database.sqlite包底下,主要包含SQLiteProgram, SQLiteDat ...

随机推荐

  1. Unity3d使用经验总结 数据驱动篇

    我这里说的数据驱动,不是指某种框架,某种结构,或者某种编码方式. 我要说的,是一种开发方式. 大家都知道,U3D中,我们可以为某个对象编写一个脚本,然后将这个脚本挂在对象上,那这个对象就拥有了相应的能 ...

  2. lua跨平台文件夹遍历匹配查找

    require"lfs" --[[Desc:在B路径D文件中下 搜寻A路径下的没用到的C类文件: 并且将没用到的B类文件名称打印出来: 设置好路径拖到lua自带编辑器中即可运行之; ...

  3. Atitit 判断判断一张图片是否包含另一张小图片

    Atitit 判断判断一张图片是否包含另一张小图片 1. keyword1 2.  模板匹配是在图像中寻找目标的方法之一(切割+图像相似度计算)1 3. 匹配效果2 4. 图片相似度的算法(感知哈希算 ...

  4. PHP 基础

    var_dump(empty($a));    判断变量是否为空 var_dump(isset($a));      判断变量是否定义 $a=10;unset($a);      删除变量 var_d ...

  5. ftp下载目录下所有文件及文件夹内(递归)

    ftp下载目录下所有文件及文件夹内(递归)   /// <summary> /// ftp文件上传.下载操作类 /// </summary> public class FTPH ...

  6. 快速入门系列--WCF--07传输安全、授权与审核

    这部分主要涉及企业级应用的安全问题,一般来说安全框架主要提供3个典型的安全行为:认证.授权和审核.除了典型的安全问题,对于一个以消息作为通信手段的分布式应用,还需要考虑消息保护(Message Pro ...

  7. KendoUI系列:TreeView

    1.加载本地数据 <link href="@Url.Content("~/Content/kendo/2014.1.318/kendo.common.min.css" ...

  8. 模拟java.util.Collection一些简单的用法

    /* 需求:模拟java.util.Collection一些简单的用法! 注意:java虚拟机中并没有泛型类型的对象.泛型是通过编译器执行一个被称为类型擦除的前段转换来实现的. 1)用泛型的原生类型替 ...

  9. 微信开发 -- 搭建基于ngrok的微信本地调试环境

    第一步,安装ngrok客户端 (1)首先先到官网下载个客户端 http://natapp.cn/,选择适合的客户端类型,本人选择的是windows版 (2)下载后,解压,可以看到如下目录: 第二步,开 ...

  10. PHP内核的学习--创建PHP扩展

    开始看PHP内核也有一段时间了,现在开始边学边总结,今天就总结一下如何创建自己的PHP扩展. 我的环境如下: 系统:Ubuntu 14.04 php版本:5.5.19 参考摘录:用C/C++扩展你的P ...