BasicDOSProtector.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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.Info($"[{_options.ReportingName}] client: {str} is no longer blocked.");
  85. }
  86. _blockLockSlim.EnterReadLock();
  87. if (_tempBlocked.Count > 0)
  88. _forgetTimer.Enabled = true;
  89. _blockLockSlim.ExitReadLock();
  90. };
  91. _forgetTimer.Interval = _options.ForgetTimeSpan.TotalMilliseconds;
  92. }
  93. /// <summary>
  94. /// Given a string Key, Returns if that context is blocked
  95. /// </summary>
  96. /// <param name="key">A Key identifying the context</param>
  97. /// <returns>bool Yes or No, True or False for blocked</returns>
  98. public bool IsBlocked(string key)
  99. {
  100. bool ret = false;
  101. _blockLockSlim.EnterReadLock();
  102. ret = _tempBlocked.ContainsKey(key);
  103. _blockLockSlim.ExitReadLock();
  104. return ret;
  105. }
  106. /// <summary>
  107. /// Process the velocity of this context
  108. /// </summary>
  109. /// <param name="key"></param>
  110. /// <param name="endpoint"></param>
  111. /// <returns></returns>
  112. public bool Process(string key, string endpoint)
  113. {
  114. if (_options.MaxRequestsInTimeframe < 1 || _options.RequestTimeSpan.TotalMilliseconds < 1)
  115. return true;
  116. string clientstring = key;
  117. _blockLockSlim.EnterReadLock();
  118. if (_tempBlocked.ContainsKey(clientstring))
  119. {
  120. _blockLockSlim.ExitReadLock();
  121. if (_options.ThrottledAction == ThrottleAction.DoThrottledMethod)
  122. return false;
  123. else
  124. throw new System.Security.SecurityException("Throttled");
  125. }
  126. _blockLockSlim.ExitReadLock();
  127. lock (_generalRequestTimes)
  128. _generalRequestTimes.Put(Util.EnvironmentTickCount());
  129. if (_options.MaxConcurrentSessions > 0)
  130. {
  131. _sessionLockSlim.EnterReadLock();
  132. _sessions.TryGetValue(key, out int sessionscount);
  133. _sessionLockSlim.ExitReadLock();
  134. if (sessionscount > _options.MaxConcurrentSessions)
  135. {
  136. // Add to blocking and cleanup methods
  137. lock (_deeperInspection)
  138. {
  139. _blockLockSlim.EnterWriteLock();
  140. if (!_tempBlocked.ContainsKey(clientstring))
  141. {
  142. _tempBlocked.Add(clientstring,
  143. Util.EnvironmentTickCount() +
  144. (int) _options.ForgetTimeSpan.TotalMilliseconds);
  145. _forgetTimer.Enabled = true;
  146. m_log.Warn($"[{_options.ReportingName}]: client: {clientstring} is blocked for {_options.ForgetTimeSpan.TotalMilliseconds}ms based on concurrency, X-ForwardedForAllowed status is {_options.AllowXForwardedFor}, endpoint:{_options.AllowXForwardedFor}");
  147. }
  148. else
  149. _tempBlocked[clientstring] = Util.EnvironmentTickCount() +
  150. (int) _options.ForgetTimeSpan.TotalMilliseconds;
  151. _blockLockSlim.ExitWriteLock();
  152. }
  153. }
  154. else
  155. ProcessConcurrency(key, endpoint);
  156. }
  157. if (_generalRequestTimes.Size == _generalRequestTimes.Capacity &&
  158. (Util.EnvironmentTickCountSubtract(Util.EnvironmentTickCount(), _generalRequestTimes.Get()) <
  159. _options.RequestTimeSpan.TotalMilliseconds))
  160. {
  161. //Trigger deeper inspection
  162. if (DeeperInspection(key, endpoint))
  163. return true;
  164. if (_options.ThrottledAction == ThrottleAction.DoThrottledMethod)
  165. return false;
  166. else
  167. throw new System.Security.SecurityException("Throttled");
  168. }
  169. return true;
  170. }
  171. private void ProcessConcurrency(string key, string endpoint)
  172. {
  173. _sessionLockSlim.EnterWriteLock();
  174. if (_sessions.ContainsKey(key))
  175. _sessions[key] = _sessions[key] + 1;
  176. else
  177. _sessions.Add(key,1);
  178. _sessionLockSlim.ExitWriteLock();
  179. }
  180. public void ProcessEnd(string key, string endpoint)
  181. {
  182. _sessionLockSlim.EnterWriteLock();
  183. if (_sessions.ContainsKey(key))
  184. {
  185. _sessions[key]--;
  186. if (_sessions[key] <= 0)
  187. _sessions.Remove(key);
  188. }
  189. else
  190. _sessions.Add(key, 1);
  191. _sessionLockSlim.ExitWriteLock();
  192. }
  193. /// <summary>
  194. /// At this point, the rate limiting code needs to track 'per user' velocity.
  195. /// </summary>
  196. /// <param name="key">Context Key, string representing a rate limiting context</param>
  197. /// <param name="endpoint"></param>
  198. /// <returns></returns>
  199. private bool DeeperInspection(string key, string endpoint)
  200. {
  201. lock (_deeperInspection)
  202. {
  203. string clientstring = key;
  204. if (_deeperInspection.ContainsKey(clientstring))
  205. {
  206. _deeperInspection[clientstring].Put(Util.EnvironmentTickCount());
  207. if (_deeperInspection[clientstring].Size == _deeperInspection[clientstring].Capacity &&
  208. (Util.EnvironmentTickCountSubtract(Util.EnvironmentTickCount(), _deeperInspection[clientstring].Get()) <
  209. _options.RequestTimeSpan.TotalMilliseconds))
  210. {
  211. //Looks like we're over the limit
  212. _blockLockSlim.EnterWriteLock();
  213. if (!_tempBlocked.ContainsKey(clientstring))
  214. _tempBlocked.Add(clientstring, Util.EnvironmentTickCount() + (int)_options.ForgetTimeSpan.TotalMilliseconds);
  215. else
  216. _tempBlocked[clientstring] = Util.EnvironmentTickCount() + (int)_options.ForgetTimeSpan.TotalMilliseconds;
  217. _blockLockSlim.ExitWriteLock();
  218. m_log.Warn($"[{_options.ReportingName}]: client: {clientstring} is blocked for {_options.ForgetTimeSpan.TotalMilliseconds}ms, X-ForwardedForAllowed status is {_options.AllowXForwardedFor}, endpoint:{endpoint}");
  219. return false;
  220. }
  221. //else
  222. // return true;
  223. }
  224. else
  225. {
  226. _deeperInspection.Add(clientstring, new CircularBuffer<int>(_options.MaxRequestsInTimeframe + 1, true));
  227. _deeperInspection[clientstring].Put(Util.EnvironmentTickCount());
  228. _forgetTimer.Enabled = true;
  229. }
  230. }
  231. return true;
  232. }
  233. }
  234. public class BasicDosProtectorOptions
  235. {
  236. public int MaxRequestsInTimeframe;
  237. public TimeSpan RequestTimeSpan;
  238. public TimeSpan ForgetTimeSpan;
  239. public bool AllowXForwardedFor;
  240. public string ReportingName = "BASICDOSPROTECTOR";
  241. public BasicDOSProtector.ThrottleAction ThrottledAction = BasicDOSProtector.ThrottleAction.DoThrottledMethod;
  242. public int MaxConcurrentSessions;
  243. }
  244. }