BasicDOSProtector.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Reflection;
  30. using log4net;
  31. namespace OpenSim.Framework
  32. {
  33. public class BasicDOSProtector
  34. {
  35. public enum ThrottleAction
  36. {
  37. DoThrottledMethod,
  38. DoThrow
  39. }
  40. private readonly CircularBuffer<int> _generalRequestTimes; // General request checker
  41. private readonly BasicDosProtectorOptions _options;
  42. private readonly Dictionary<string, CircularBuffer<int>> _deeperInspection; // per client request checker
  43. private readonly Dictionary<string, int> _tempBlocked; // blocked list
  44. private readonly Dictionary<string, int> _sessions;
  45. private readonly System.Timers.Timer _forgetTimer; // Cleanup timer
  46. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  47. private readonly System.Threading.ReaderWriterLockSlim _blockLockSlim = new System.Threading.ReaderWriterLockSlim();
  48. private readonly System.Threading.ReaderWriterLockSlim _sessionLockSlim = new System.Threading.ReaderWriterLockSlim();
  49. public BasicDOSProtector(BasicDosProtectorOptions options)
  50. {
  51. _generalRequestTimes = new CircularBuffer<int>(options.MaxRequestsInTimeframe + 1, true);
  52. _generalRequestTimes.Put(0);
  53. _options = options;
  54. _deeperInspection = new Dictionary<string, CircularBuffer<int>>();
  55. _tempBlocked = new Dictionary<string, int>();
  56. _sessions = new Dictionary<string, int>();
  57. _forgetTimer = new System.Timers.Timer();
  58. _forgetTimer.Elapsed += delegate
  59. {
  60. _forgetTimer.Enabled = false;
  61. List<string> removes = new List<string>();
  62. _blockLockSlim.EnterReadLock();
  63. foreach (string str in _tempBlocked.Keys)
  64. {
  65. if (
  66. Util.EnvironmentTickCountSubtract(Util.EnvironmentTickCount(),
  67. _tempBlocked[str]) > 0)
  68. removes.Add(str);
  69. }
  70. _blockLockSlim.ExitReadLock();
  71. lock (_deeperInspection)
  72. {
  73. _blockLockSlim.EnterWriteLock();
  74. for (int i = 0; i < removes.Count; i++)
  75. {
  76. _tempBlocked.Remove(removes[i]);
  77. _deeperInspection.Remove(removes[i]);
  78. _sessions.Remove(removes[i]);
  79. }
  80. _blockLockSlim.ExitWriteLock();
  81. }
  82. foreach (string str in removes)
  83. {
  84. m_log.InfoFormat("[{0}] client: {1} is no longer blocked.",
  85. _options.ReportingName, str);
  86. }
  87. _blockLockSlim.EnterReadLock();
  88. if (_tempBlocked.Count > 0)
  89. _forgetTimer.Enabled = true;
  90. _blockLockSlim.ExitReadLock();
  91. };
  92. _forgetTimer.Interval = _options.ForgetTimeSpan.TotalMilliseconds;
  93. }
  94. /// <summary>
  95. /// Given a string Key, Returns if that context is blocked
  96. /// </summary>
  97. /// <param name="key">A Key identifying the context</param>
  98. /// <returns>bool Yes or No, True or False for blocked</returns>
  99. public bool IsBlocked(string key)
  100. {
  101. bool ret = false;
  102. _blockLockSlim.EnterReadLock();
  103. ret = _tempBlocked.ContainsKey(key);
  104. _blockLockSlim.ExitReadLock();
  105. return ret;
  106. }
  107. /// <summary>
  108. /// Process the velocity of this context
  109. /// </summary>
  110. /// <param name="key"></param>
  111. /// <param name="endpoint"></param>
  112. /// <returns></returns>
  113. public bool Process(string key, string endpoint)
  114. {
  115. if (_options.MaxRequestsInTimeframe < 1 || _options.RequestTimeSpan.TotalMilliseconds < 1)
  116. return true;
  117. string clientstring = key;
  118. _blockLockSlim.EnterReadLock();
  119. if (_tempBlocked.ContainsKey(clientstring))
  120. {
  121. _blockLockSlim.ExitReadLock();
  122. if (_options.ThrottledAction == ThrottleAction.DoThrottledMethod)
  123. return false;
  124. else
  125. throw new System.Security.SecurityException("Throttled");
  126. }
  127. _blockLockSlim.ExitReadLock();
  128. lock (_generalRequestTimes)
  129. _generalRequestTimes.Put(Util.EnvironmentTickCount());
  130. if (_options.MaxConcurrentSessions > 0)
  131. {
  132. int sessionscount = 0;
  133. _sessionLockSlim.EnterReadLock();
  134. if (_sessions.ContainsKey(key))
  135. sessionscount = _sessions[key];
  136. _sessionLockSlim.ExitReadLock();
  137. if (sessionscount > _options.MaxConcurrentSessions)
  138. {
  139. // Add to blocking and cleanup methods
  140. lock (_deeperInspection)
  141. {
  142. _blockLockSlim.EnterWriteLock();
  143. if (!_tempBlocked.ContainsKey(clientstring))
  144. {
  145. _tempBlocked.Add(clientstring,
  146. Util.EnvironmentTickCount() +
  147. (int) _options.ForgetTimeSpan.TotalMilliseconds);
  148. _forgetTimer.Enabled = true;
  149. m_log.WarnFormat("[{0}]: client: {1} is blocked for {2} milliseconds based on concurrency, X-ForwardedForAllowed status is {3}, endpoint:{4}", _options.ReportingName, clientstring, _options.ForgetTimeSpan.TotalMilliseconds, _options.AllowXForwardedFor, endpoint);
  150. }
  151. else
  152. _tempBlocked[clientstring] = Util.EnvironmentTickCount() +
  153. (int) _options.ForgetTimeSpan.TotalMilliseconds;
  154. _blockLockSlim.ExitWriteLock();
  155. }
  156. }
  157. else
  158. ProcessConcurrency(key, endpoint);
  159. }
  160. if (_generalRequestTimes.Size == _generalRequestTimes.Capacity &&
  161. (Util.EnvironmentTickCountSubtract(Util.EnvironmentTickCount(), _generalRequestTimes.Get()) <
  162. _options.RequestTimeSpan.TotalMilliseconds))
  163. {
  164. //Trigger deeper inspection
  165. if (DeeperInspection(key, endpoint))
  166. return true;
  167. if (_options.ThrottledAction == ThrottleAction.DoThrottledMethod)
  168. return false;
  169. else
  170. throw new System.Security.SecurityException("Throttled");
  171. }
  172. return true;
  173. }
  174. private void ProcessConcurrency(string key, string endpoint)
  175. {
  176. _sessionLockSlim.EnterWriteLock();
  177. if (_sessions.ContainsKey(key))
  178. _sessions[key] = _sessions[key] + 1;
  179. else
  180. _sessions.Add(key,1);
  181. _sessionLockSlim.ExitWriteLock();
  182. }
  183. public void ProcessEnd(string key, string endpoint)
  184. {
  185. _sessionLockSlim.EnterWriteLock();
  186. if (_sessions.ContainsKey(key))
  187. {
  188. _sessions[key]--;
  189. if (_sessions[key] <= 0)
  190. _sessions.Remove(key);
  191. }
  192. else
  193. _sessions.Add(key, 1);
  194. _sessionLockSlim.ExitWriteLock();
  195. }
  196. /// <summary>
  197. /// At this point, the rate limiting code needs to track 'per user' velocity.
  198. /// </summary>
  199. /// <param name="key">Context Key, string representing a rate limiting context</param>
  200. /// <param name="endpoint"></param>
  201. /// <returns></returns>
  202. private bool DeeperInspection(string key, string endpoint)
  203. {
  204. lock (_deeperInspection)
  205. {
  206. string clientstring = key;
  207. if (_deeperInspection.ContainsKey(clientstring))
  208. {
  209. _deeperInspection[clientstring].Put(Util.EnvironmentTickCount());
  210. if (_deeperInspection[clientstring].Size == _deeperInspection[clientstring].Capacity &&
  211. (Util.EnvironmentTickCountSubtract(Util.EnvironmentTickCount(), _deeperInspection[clientstring].Get()) <
  212. _options.RequestTimeSpan.TotalMilliseconds))
  213. {
  214. //Looks like we're over the limit
  215. _blockLockSlim.EnterWriteLock();
  216. if (!_tempBlocked.ContainsKey(clientstring))
  217. _tempBlocked.Add(clientstring, Util.EnvironmentTickCount() + (int)_options.ForgetTimeSpan.TotalMilliseconds);
  218. else
  219. _tempBlocked[clientstring] = Util.EnvironmentTickCount() + (int)_options.ForgetTimeSpan.TotalMilliseconds;
  220. _blockLockSlim.ExitWriteLock();
  221. m_log.WarnFormat("[{0}]: client: {1} is blocked for {2} milliseconds, X-ForwardedForAllowed status is {3}, endpoint:{4}", _options.ReportingName, clientstring, _options.ForgetTimeSpan.TotalMilliseconds, _options.AllowXForwardedFor, endpoint);
  222. return false;
  223. }
  224. //else
  225. // return true;
  226. }
  227. else
  228. {
  229. _deeperInspection.Add(clientstring, new CircularBuffer<int>(_options.MaxRequestsInTimeframe + 1, true));
  230. _deeperInspection[clientstring].Put(Util.EnvironmentTickCount());
  231. _forgetTimer.Enabled = true;
  232. }
  233. }
  234. return true;
  235. }
  236. }
  237. public class BasicDosProtectorOptions
  238. {
  239. public int MaxRequestsInTimeframe;
  240. public TimeSpan RequestTimeSpan;
  241. public TimeSpan ForgetTimeSpan;
  242. public bool AllowXForwardedFor;
  243. public string ReportingName = "BASICDOSPROTECTOR";
  244. public BasicDOSProtector.ThrottleAction ThrottledAction = BasicDOSProtector.ThrottleAction.DoThrottledMethod;
  245. public int MaxConcurrentSessions;
  246. }
  247. }