1
0

GenericHTTPBasicDOSProtector.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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;
  29. using System.Collections.Generic;
  30. using System.Reflection;
  31. using System.Net;
  32. using OpenSim.Framework;
  33. using log4net;
  34. namespace OpenSim.Framework.Servers.HttpServer
  35. {
  36. public class GenericHTTPDOSProtector
  37. {
  38. private readonly GenericHTTPMethod _normalMethod;
  39. private readonly GenericHTTPMethod _throttledMethod;
  40. private readonly CircularBuffer<int> _generalRequestTimes;
  41. private readonly BasicDosProtectorOptions _options;
  42. private readonly Dictionary<string, CircularBuffer<int>> _deeperInspection;
  43. private readonly Dictionary<string, int> _tempBlocked;
  44. private readonly System.Timers.Timer _forgetTimer;
  45. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  46. private readonly System.Threading.ReaderWriterLockSlim _lockSlim = new System.Threading.ReaderWriterLockSlim();
  47. public GenericHTTPDOSProtector(GenericHTTPMethod normalMethod, GenericHTTPMethod throttledMethod, BasicDosProtectorOptions options)
  48. {
  49. _normalMethod = normalMethod;
  50. _throttledMethod = throttledMethod;
  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. _forgetTimer = new System.Timers.Timer();
  57. _forgetTimer.Elapsed += delegate
  58. {
  59. _forgetTimer.Enabled = false;
  60. List<string> removes = new List<string>();
  61. _lockSlim.EnterReadLock();
  62. foreach (string str in _tempBlocked.Keys)
  63. {
  64. if (
  65. Util.EnvironmentTickCountSubtract(Util.EnvironmentTickCount(),
  66. _tempBlocked[str]) > 0)
  67. removes.Add(str);
  68. }
  69. _lockSlim.ExitReadLock();
  70. lock (_deeperInspection)
  71. {
  72. _lockSlim.EnterWriteLock();
  73. for (int i = 0; i < removes.Count; i++)
  74. {
  75. _tempBlocked.Remove(removes[i]);
  76. _deeperInspection.Remove(removes[i]);
  77. }
  78. _lockSlim.ExitWriteLock();
  79. }
  80. foreach (string str in removes)
  81. {
  82. m_log.InfoFormat("[{0}] client: {1} is no longer blocked.",
  83. _options.ReportingName, str);
  84. }
  85. _lockSlim.EnterReadLock();
  86. if (_tempBlocked.Count > 0)
  87. _forgetTimer.Enabled = true;
  88. _lockSlim.ExitReadLock();
  89. };
  90. _forgetTimer.Interval = _options.ForgetTimeSpan.TotalMilliseconds;
  91. }
  92. public Hashtable Process(Hashtable request)
  93. {
  94. if (_options.MaxRequestsInTimeframe < 1)
  95. return _normalMethod(request);
  96. if (_options.RequestTimeSpan.TotalMilliseconds < 1)
  97. return _normalMethod(request);
  98. string clientstring = GetClientString(request);
  99. _lockSlim.EnterReadLock();
  100. if (_tempBlocked.ContainsKey(clientstring))
  101. {
  102. _lockSlim.ExitReadLock();
  103. if (_options.ThrottledAction == ThrottleAction.DoThrottledMethod)
  104. return _throttledMethod(request);
  105. else
  106. throw new System.Security.SecurityException("Throttled");
  107. }
  108. _lockSlim.ExitReadLock();
  109. _generalRequestTimes.Put(Util.EnvironmentTickCount());
  110. if (_generalRequestTimes.Size == _generalRequestTimes.Capacity &&
  111. (Util.EnvironmentTickCountSubtract(Util.EnvironmentTickCount(), _generalRequestTimes.Get()) <
  112. _options.RequestTimeSpan.TotalMilliseconds))
  113. {
  114. //Trigger deeper inspection
  115. if (DeeperInspection(request))
  116. return _normalMethod(request);
  117. if (_options.ThrottledAction == ThrottleAction.DoThrottledMethod)
  118. return _throttledMethod(request);
  119. else
  120. throw new System.Security.SecurityException("Throttled");
  121. }
  122. Hashtable resp = null;
  123. try
  124. {
  125. resp = _normalMethod(request);
  126. }
  127. catch (Exception)
  128. {
  129. throw;
  130. }
  131. return resp;
  132. }
  133. private bool DeeperInspection(Hashtable request)
  134. {
  135. lock (_deeperInspection)
  136. {
  137. string clientstring = GetClientString(request);
  138. if (_deeperInspection.ContainsKey(clientstring))
  139. {
  140. _deeperInspection[clientstring].Put(Util.EnvironmentTickCount());
  141. if (_deeperInspection[clientstring].Size == _deeperInspection[clientstring].Capacity &&
  142. (Util.EnvironmentTickCountSubtract(Util.EnvironmentTickCount(), _deeperInspection[clientstring].Get()) <
  143. _options.RequestTimeSpan.TotalMilliseconds))
  144. {
  145. _lockSlim.EnterWriteLock();
  146. if (!_tempBlocked.ContainsKey(clientstring))
  147. _tempBlocked.Add(clientstring, Util.EnvironmentTickCount() + (int)_options.ForgetTimeSpan.TotalMilliseconds);
  148. else
  149. _tempBlocked[clientstring] = Util.EnvironmentTickCount() + (int)_options.ForgetTimeSpan.TotalMilliseconds;
  150. _lockSlim.ExitWriteLock();
  151. 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(request));
  152. return false;
  153. }
  154. //else
  155. // return true;
  156. }
  157. else
  158. {
  159. _deeperInspection.Add(clientstring, new CircularBuffer<int>(_options.MaxRequestsInTimeframe + 1, true));
  160. _deeperInspection[clientstring].Put(Util.EnvironmentTickCount());
  161. _forgetTimer.Enabled = true;
  162. }
  163. }
  164. return true;
  165. }
  166. private string GetRemoteAddr(Hashtable request)
  167. {
  168. string remoteaddr = "";
  169. if (!request.ContainsKey("headers"))
  170. return remoteaddr;
  171. Hashtable requestinfo = (Hashtable)request["headers"];
  172. if (!requestinfo.ContainsKey("remote_addr"))
  173. return remoteaddr;
  174. object remote_addrobj = requestinfo["remote_addr"];
  175. if (remote_addrobj != null)
  176. {
  177. if (!string.IsNullOrEmpty(remote_addrobj.ToString()))
  178. {
  179. remoteaddr = remote_addrobj.ToString();
  180. }
  181. }
  182. return remoteaddr;
  183. }
  184. private string GetClientString(Hashtable request)
  185. {
  186. string clientstring = "";
  187. if (!request.ContainsKey("headers"))
  188. return clientstring;
  189. Hashtable requestinfo = (Hashtable)request["headers"];
  190. if (_options.AllowXForwardedFor && requestinfo.ContainsKey("x-forwarded-for"))
  191. {
  192. object str = requestinfo["x-forwarded-for"];
  193. if (str != null)
  194. {
  195. if (!string.IsNullOrEmpty(str.ToString()))
  196. {
  197. return str.ToString();
  198. }
  199. }
  200. }
  201. if (!requestinfo.ContainsKey("remote_addr"))
  202. return clientstring;
  203. object remote_addrobj = requestinfo["remote_addr"];
  204. if (remote_addrobj != null)
  205. {
  206. if (!string.IsNullOrEmpty(remote_addrobj.ToString()))
  207. {
  208. clientstring = remote_addrobj.ToString();
  209. }
  210. }
  211. return clientstring;
  212. }
  213. }
  214. }