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

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

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

  1. DOSProtection用于放置Dos攻击,可以封IP,默认没有启用
  1. namespace NetworkCommsDotNet.Tools
  2. {
  3. /// <summary>
  4. /// NetworkComms.Net class used for providing Denial Of Service (DOS) protection features.
  5. /// If enabled, malformed data events and connection initialises are tracked. If above
  6. /// set thresholds IPAddresses are banned.
  7. /// 用于DOS攻击防御的类
  8. /// 如果启用 则格式不正确的数据和连接请求将会被跟踪 并对相应的IP进行查封
  9. /// </summary>
  10. public class DOSProtection
  11. {
  12. /// <summary>
  13. /// A local thread safety locker
  14. /// 同步锁
  15. /// </summary>
  16. object _syncRoot = new object();
  17.  
  18. /// <summary>
  19. /// Addresses that are currently banned. Key is remote IPAddress, value is time banned.
  20. /// 被查封的IP
  21. /// </summary>
  22. Dictionary<IPAddress, DateTime> _bannedAddresses = new Dictionary<IPAddress, DateTime>();
  23.  
  24. /// <summary>
  25. /// First key is remote IPAddress, second key is DateTime.Ticks, value is the malformed count for that DateTime.ticks
  26. /// 格式不正确的数据的相关信息 IP 发生的时间 次数
  27. /// </summary>
  28. Dictionary<IPAddress, Dictionary<long, int>> _malformedCountDict = new Dictionary<IPAddress, Dictionary<long, int>>();
  29.  
  30. /// <summary>
  31. /// First key is remote IPAddress, second key is DateTime.Ticks, value is the connection initialisation count for that DateTime.ticks
  32. /// 格式不正确的连接请求 IP 发生的时间 次数
  33. /// </summary>
  34. Dictionary<IPAddress, Dictionary<long, int>> _connectionInitialiseCountDict = new Dictionary<IPAddress, Dictionary<long, int>>();
  35.  
  36. /// <summary>
  37. /// The current state of DOS protection
  38. /// 是否启用DOS攻击防御
  39. /// </summary>
  40. public bool Enabled { get; set; }
  41.  
  42. /// <summary>
  43. /// The timeout after which time a banned IPAddress may have access again. Default is 10 minutes.
  44. /// 相关IP查封的时间
  45. /// </summary>
  46. public TimeSpan BanTimeout { get; set; }
  47.  
  48. /// <summary>
  49. /// The time within which if MalformedCountInIntervalBeforeBan or ConnectionInitialiseCountInIntervalBeforeBan
  50. /// is reached a peer will be banned. Default is 5 minutes.
  51. /// 查封相关的一个时间段
  52. /// 默认5分钟
  53. /// 比如说5分钟内收到2个不规则数据,启用查封
  54. /// </summary>
  55. public TimeSpan LogInterval { get; set; }
  56.  
  57. /// <summary>
  58. /// The number of malformed data counts to log within LogInterval before an IPAddress is banned. Default is 2.
  59. /// LogInterval时间内收到不规则数据将会被查封 默认为2个
  60. /// </summary>
  61. public int MalformedCountInIntervalBeforeBan { get; set; }
  62.  
  63. /// <summary>
  64. /// The number of connection initialises to log within LogInterval before an IPAddress is banned. Default is 100
  65. /// LogInterval时间内收到不规则连接请求 默认为100个 启用查封
  66. /// </summary>
  67. public int ConnectionInitialiseCountInIntervalBeforeBan { get; set; }
  68.  
  69. /// <summary>
  70. /// Initialise a new instance of DOS protection.
  71. /// 初始化
  72. /// </summary>
  73. public DOSProtection()
  74. {
  75. Enabled = false;
  76. BanTimeout = , , );
  77. LogInterval = , , );
  78. MalformedCountInIntervalBeforeBan = ;
  79. ConnectionInitialiseCountInIntervalBeforeBan = ;
  80. }
  81.  
  82. /// <summary>
  83. /// Log a malformed data event for the provided remote IPAddress.
  84. /// 记录不规则数据时间 根据指定的IP
  85. /// </summary>
  86. /// <param name="remoteIPAddress"></param>
  87. /// <returns>如果指定IP已经查封 返回True *** True if the remote IPAddress is now banned, otherwise false.</returns>
  88. public bool LogMalformedData(IPAddress remoteIPAddress)
  89. {
  90. bool ipAddressNowBanned = false;
  91.  
  92. lock (_syncRoot)
  93. {
  94. //Record the malformed data count
  95. //记录不规则数据数量
  96. long tick = DateTime.Now.Ticks;
  97. if (_malformedCountDict.ContainsKey(remoteIPAddress))
  98. {
  99. if (_malformedCountDict[remoteIPAddress].ContainsKey(tick))
  100. _malformedCountDict[remoteIPAddress][tick]++;
  101. else
  102. _malformedCountDict[remoteIPAddress].Add(tick, );
  103. }
  104. else
  105. _malformedCountDict.Add(remoteIPAddress, } });
  106.  
  107. //Delete any tick keys which are greater than LogInterval
  108. //删除超过LogInterval时间段的数据
  109. List<long> existingIPAddressTickKeys = new List<long>(_malformedCountDict[remoteIPAddress].Keys);
  110.  
  111. //Sort from oldest to newest
  112. //排序
  113. existingIPAddressTickKeys.Sort();
  114.  
  115. //Keep removing tick keys until we are within LogInterval
  116. //删除超过指定时间段的数据
  117. ; i < existingIPAddressTickKeys.Count; i++)
  118. {
  119. if (DateTime.Now - new DateTime(existingIPAddressTickKeys[i]) > LogInterval)
  120. _malformedCountDict[remoteIPAddress].Remove(existingIPAddressTickKeys[i]);
  121. else
  122. break;
  123. }
  124.  
  125. //Add up the remaining counts and see if we need to ban this peer
  126. //查看是否需要查封此IP
  127. ;
  128. foreach(int count in _malformedCountDict[remoteIPAddress].Values)
  129. currentMalformedCount += count;
  130.  
  131. if (currentMalformedCount >= MalformedCountInIntervalBeforeBan)
  132. {
  133. ipAddressNowBanned = true;
  134. _bannedAddresses[remoteIPAddress] = new DateTime(tick);
  135. }
  136. else
  137. {
  138. ipAddressNowBanned = false;
  139. _bannedAddresses.Remove(remoteIPAddress);
  140. }
  141.  
  142. //Remove the remote IPAddress key if no events are left
  143. //如果没有响应的时间 删除相应的IP
  144. )
  145. _malformedCountDict.Remove(remoteIPAddress);
  146. }
  147.  
  148. return ipAddressNowBanned;
  149. }
  150.  
  151. /// <summary>
  152. /// Log a connection initialisation for the provided remote IPAddress.
  153. /// 记录一个格式错误的连接初始化 根据指定IP
  154. /// </summary>
  155. /// <param name="remoteIPAddress"></param>
  156. /// <returns>True if the remote IPAddress is now banned, otherwise false.</returns>
  157. public bool LogConnectionInitialise(IPAddress remoteIPAddress)
  158. {
  159. bool ipAddressNowBanned = false;
  160.  
  161. lock (_syncRoot)
  162. {
  163. //Record the malformed data count
  164. //记录格式错误的数据的次数
  165. long tick = DateTime.Now.Ticks;
  166. if (_connectionInitialiseCountDict.ContainsKey(remoteIPAddress))
  167. {
  168. if (_connectionInitialiseCountDict[remoteIPAddress].ContainsKey(tick))
  169. _connectionInitialiseCountDict[remoteIPAddress][tick]++;
  170. else
  171. _connectionInitialiseCountDict[remoteIPAddress].Add(tick, );
  172. }
  173. else
  174. _connectionInitialiseCountDict.Add(remoteIPAddress, } });
  175.  
  176. //Delete any tick keys which are greater than LogInterval
  177. //删除超过LogInterval时间段的数据
  178. List<long> existingIPAddressTickKeys = new List<long>(_connectionInitialiseCountDict[remoteIPAddress].Keys);
  179.  
  180. //Sort from oldest to newest
  181. //排序
  182. existingIPAddressTickKeys.Sort();
  183.  
  184. //Keep removing tick keys until we are within LogInterval
  185. //删除超过LogInterval时间段的数据
  186. ; i < existingIPAddressTickKeys.Count; i++)
  187. {
  188. if (DateTime.Now - new DateTime(existingIPAddressTickKeys[i]) > LogInterval)
  189. _connectionInitialiseCountDict[remoteIPAddress].Remove(existingIPAddressTickKeys[i]);
  190. else
  191. break;
  192. }
  193.  
  194. //Add up the remaining counts and see if we need to ban this peer
  195. //查看是否需要查封相关的数据
  196. ;
  197. foreach (int count in _connectionInitialiseCountDict[remoteIPAddress].Values)
  198. currentConnectionInitialisationCount += count;
  199.  
  200. //Make a decision based on currentConnectionInitialisationCount
  201. //是否查封
  202. if (currentConnectionInitialisationCount >= ConnectionInitialiseCountInIntervalBeforeBan)
  203. {
  204. ipAddressNowBanned = true;
  205. _bannedAddresses[remoteIPAddress] = new DateTime(tick);
  206. }
  207. else
  208. {
  209. ipAddressNowBanned = false;
  210. _bannedAddresses.Remove(remoteIPAddress);
  211. }
  212.  
  213. //Remove the remote IPAddress key if no events are left
  214. //如果事件不存在 删除相关IP
  215. )
  216. _connectionInitialiseCountDict.Remove(remoteIPAddress);
  217. }
  218.  
  219. return ipAddressNowBanned;
  220. }
  221.  
  222. /// <summary>
  223. /// Returns true if the provided IPAddress has been banned due to DOSProtection.
  224. /// 如果参数中IP已经被查封 返回True
  225. /// </summary>
  226. /// <param name="remoteIPAddress">The IPAddress to check</param>
  227. /// <returns></returns>
  228. public bool RemoteIPAddressBanned(IPAddress remoteIPAddress)
  229. {
  230. lock(_syncRoot)
  231. {
  232. if (_bannedAddresses.ContainsKey(remoteIPAddress))
  233. {
  234. //If the ban time is longer than the timeout we can allow it again
  235. //如果过了封杀的时间 从查封列表中删除
  236. if (DateTime.Now - _bannedAddresses[remoteIPAddress] > BanTimeout)
  237. {
  238. _bannedAddresses.Remove(remoteIPAddress);
  239. return false;
  240. }
  241. else
  242. return true;
  243. }
  244. else
  245. return false;
  246. }
  247. }
  248. }
  249. }

介绍开源的.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. Visual Studio 2015速递(1)——C#6.0新特性怎么用

    系列文章 Visual Studio 2015速递(1)——C#6.0新特性怎么用 Visual Studio 2015速递(2)——提升效率和质量(VS2015核心竞争力) Visual Studi ...

  2. AngularJS快速入门指南12:模块

    AngularJS模块定义了一个application. 模块是一个application中不同部分的容器. application中的所有控制器都应该属于一个模块. 带有一个控制器的模块 下面这个a ...

  3. zk系列-zookeeper概述

    接触zk是2年前了,最近工作又比较依赖于zk,所以准备起个系列文章,系统的总结下. zookeeper是一个分布式的用于协调的服务,起源于Hadoop中的一个组件.分布式系统可以用zookeeper实 ...

  4. ASP.net状态服务器使用

    最近在开发一.NET4.0系统时经常发生session丢失问题,导致用户频繁登陆,给客户造成不良的用户体验.应项目经理号召尽快解决此问题. 一.问题描述. 服务器:windows server 200 ...

  5. tomcat 5.5 动态加载类

    转载于:http://www.itxuexiwang.com/a/javadianzishu/tomcat/2016/0225/161.html?1456480735 开发使用的是tomcat5.5. ...

  6. Atitit  五种IO模型attilax总结 blocking和non-blocking synchronous IO和asynchronous I

    Atitit  五种IO模型attilax总结 blocking和non-blocking synchronous IO和asynchronous I   1.1. .3 进程的阻塞1 1.2. 网络 ...

  7. MVC3中如何输出富文本

    MVC3中如何输出富文本 在网站的文本输出中,经常会将DB里的文本输出到页面上. 一般来说是直接利用MVC3中的ViewBag将文本带到前台并表示, 或是是直接以<%:model.data%&g ...

  8. javascript_core_03之数组

    1.数组:连续存储多个数据,一组连续变量的集合: ①创建空数组:var arr=[]:或者var arr=new Array(): ②创建初始化数组:var arr=[值1,值2,……]:或者var ...

  9. POJ3069 POJ2586 解题报告(异曲同工的贪心算法)

    [POJ 3069](2586见下) 原题在此:http://poj.org/problem?id=3069 题目大意: 一个直线上有N个点.点i的距离是Xi.从这些点中选取若干个加上标记.要求:对于 ...

  10. 利用CSS3 clip-path裁剪各种图形。

    'clip-path'是css3的一个强大属性,我们可以利用它来绘制各种各样的图形,当然不只是这些,接下来一起看看它的强大功能吧. 首先介绍的是clip-path里面的polygon功能,我们可以通过 ...