BaseStreamHandlerBasicDOSProtector.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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 OpenSim.Framework;
  28. using System.Collections.Generic;
  29. using System.IO;
  30. using System.Reflection;
  31. using log4net;
  32. namespace OpenSim.Framework.Servers.HttpServer
  33. {
  34. /// <summary>
  35. /// BaseStreamHandlerBasicDOSProtector Base streamed request handler.
  36. /// </summary>
  37. /// <remarks>
  38. /// Inheriting classes should override ProcessRequest() rather than Handle()
  39. /// </remarks>
  40. public abstract class BaseStreamHandlerBasicDOSProtector : BaseRequestHandler, IStreamedRequestHandler
  41. {
  42. private readonly CircularBuffer<int> _generalRequestTimes;
  43. private readonly BasicDosProtectorOptions _options;
  44. private readonly Dictionary<string, CircularBuffer<int>> _deeperInspection;
  45. private readonly Dictionary<string, int> _tempBlocked;
  46. private readonly System.Timers.Timer _forgetTimer;
  47. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  48. private readonly System.Threading.ReaderWriterLockSlim _lockSlim = new System.Threading.ReaderWriterLockSlim();
  49. protected BaseStreamHandlerBasicDOSProtector(string httpMethod, string path, BasicDosProtectorOptions options) : this(httpMethod, path, null, null, options) {}
  50. protected BaseStreamHandlerBasicDOSProtector(string httpMethod, string path, string name, string description, BasicDosProtectorOptions options)
  51. : base(httpMethod, path, name, description)
  52. {
  53. _generalRequestTimes = new CircularBuffer<int>(options.MaxRequestsInTimeframe + 1, true);
  54. _generalRequestTimes.Put(0);
  55. _options = options;
  56. _deeperInspection = new Dictionary<string, CircularBuffer<int>>();
  57. _tempBlocked = new Dictionary<string, int>();
  58. _forgetTimer = new System.Timers.Timer();
  59. _forgetTimer.Elapsed += delegate
  60. {
  61. _forgetTimer.Enabled = false;
  62. List<string> removes = new List<string>();
  63. _lockSlim.EnterReadLock();
  64. foreach (string str in _tempBlocked.Keys)
  65. {
  66. if (
  67. Util.EnvironmentTickCountSubtract(Util.EnvironmentTickCount(),
  68. _tempBlocked[str]) > 0)
  69. removes.Add(str);
  70. }
  71. _lockSlim.ExitReadLock();
  72. lock (_deeperInspection)
  73. {
  74. _lockSlim.EnterWriteLock();
  75. for (int i = 0; i < removes.Count; i++)
  76. {
  77. _tempBlocked.Remove(removes[i]);
  78. _deeperInspection.Remove(removes[i]);
  79. }
  80. _lockSlim.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. _lockSlim.EnterReadLock();
  88. if (_tempBlocked.Count > 0)
  89. _forgetTimer.Enabled = true;
  90. _lockSlim.ExitReadLock();
  91. };
  92. _forgetTimer.Interval = _options.ForgetTimeSpan.TotalMilliseconds;
  93. }
  94. public virtual byte[] Handle(
  95. string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  96. {
  97. byte[] result;
  98. RequestsReceived++;
  99. //httpRequest.Headers
  100. if (_options.MaxRequestsInTimeframe < 1 || _options.RequestTimeSpan.TotalMilliseconds < 1)
  101. {
  102. result = ProcessRequest(path, request, httpRequest, httpResponse);
  103. RequestsHandled++;
  104. return result;
  105. }
  106. string clientstring = GetClientString(httpRequest);
  107. _lockSlim.EnterReadLock();
  108. if (_tempBlocked.ContainsKey(clientstring))
  109. {
  110. _lockSlim.ExitReadLock();
  111. if (_options.ThrottledAction == ThrottleAction.DoThrottledMethod)
  112. {
  113. result = ThrottledRequest(path, request, httpRequest, httpResponse);
  114. RequestsHandled++;
  115. return result;
  116. }
  117. else
  118. throw new System.Security.SecurityException("Throttled");
  119. }
  120. _lockSlim.ExitReadLock();
  121. _generalRequestTimes.Put(Util.EnvironmentTickCount());
  122. if (_generalRequestTimes.Size == _generalRequestTimes.Capacity &&
  123. (Util.EnvironmentTickCountSubtract(Util.EnvironmentTickCount(), _generalRequestTimes.Get()) <
  124. _options.RequestTimeSpan.TotalMilliseconds))
  125. {
  126. //Trigger deeper inspection
  127. if (DeeperInspection(httpRequest))
  128. {
  129. result = ProcessRequest(path, request, httpRequest, httpResponse);
  130. RequestsHandled++;
  131. return result;
  132. }
  133. if (_options.ThrottledAction == ThrottleAction.DoThrottledMethod)
  134. {
  135. result = ThrottledRequest(path, request, httpRequest, httpResponse);
  136. RequestsHandled++;
  137. return result;
  138. }
  139. else
  140. throw new System.Security.SecurityException("Throttled");
  141. }
  142. result =ProcessRequest(path, request, httpRequest, httpResponse);
  143. RequestsHandled++;
  144. return result;
  145. }
  146. protected virtual byte[] ProcessRequest(
  147. string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  148. {
  149. return null;
  150. }
  151. protected virtual byte[] ThrottledRequest(
  152. string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  153. {
  154. return new byte[0];
  155. }
  156. private bool DeeperInspection(IOSHttpRequest httpRequest)
  157. {
  158. lock (_deeperInspection)
  159. {
  160. string clientstring = GetClientString(httpRequest);
  161. if (_deeperInspection.ContainsKey(clientstring))
  162. {
  163. _deeperInspection[clientstring].Put(Util.EnvironmentTickCount());
  164. if (_deeperInspection[clientstring].Size == _deeperInspection[clientstring].Capacity &&
  165. (Util.EnvironmentTickCountSubtract(Util.EnvironmentTickCount(), _deeperInspection[clientstring].Get()) <
  166. _options.RequestTimeSpan.TotalMilliseconds))
  167. {
  168. _lockSlim.EnterWriteLock();
  169. if (!_tempBlocked.ContainsKey(clientstring))
  170. _tempBlocked.Add(clientstring, Util.EnvironmentTickCount() + (int)_options.ForgetTimeSpan.TotalMilliseconds);
  171. else
  172. _tempBlocked[clientstring] = Util.EnvironmentTickCount() + (int)_options.ForgetTimeSpan.TotalMilliseconds;
  173. _lockSlim.ExitWriteLock();
  174. 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, GetRemoteAddr(httpRequest));
  175. return false;
  176. }
  177. //else
  178. // return true;
  179. }
  180. else
  181. {
  182. _deeperInspection.Add(clientstring, new CircularBuffer<int>(_options.MaxRequestsInTimeframe + 1, true));
  183. _deeperInspection[clientstring].Put(Util.EnvironmentTickCount());
  184. _forgetTimer.Enabled = true;
  185. }
  186. }
  187. return true;
  188. }
  189. private string GetRemoteAddr(IOSHttpRequest httpRequest)
  190. {
  191. string remoteaddr = string.Empty;
  192. if (httpRequest.Headers["remote_addr"] != null)
  193. remoteaddr = httpRequest.Headers["remote_addr"];
  194. return remoteaddr;
  195. }
  196. private string GetClientString(IOSHttpRequest httpRequest)
  197. {
  198. string clientstring = string.Empty;
  199. if (_options.AllowXForwardedFor && httpRequest.Headers["x-forwarded-for"] != null)
  200. clientstring = httpRequest.Headers["x-forwarded-for"];
  201. else
  202. clientstring = GetRemoteAddr(httpRequest);
  203. return clientstring;
  204. }
  205. }
  206. }