PacketMonitor.cs 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. /*
  2. * Mentalis.org Packet Monitor
  3. *
  4. * Copyright ?2003, The KPD-Team
  5. * All rights reserved.
  6. * http://www.mentalis.org/
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. *
  12. * - Redistributions of source code must retain the above copyright
  13. * notice, this list of conditions and the following disclaimer.
  14. *
  15. * - Neither the name of the KPD-Team, nor the names of its contributors
  16. * may be used to endorse or promote products derived from this
  17. * software without specific prior written permission.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  22. * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
  23. * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  24. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  25. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  26. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  27. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  28. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  29. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  30. * OF THE POSSIBILITY OF SUCH DAMAGE.
  31. */
  32. using System;
  33. using System.Text;
  34. using System.Net;
  35. using System.Net.Sockets;
  36. using System.Runtime.InteropServices;
  37. namespace Org.Mentalis.Network.PacketMonitor {
  38. /// <summary>
  39. /// A class that intercepts IP packets on a specific interface.
  40. /// </summary>
  41. /// <remarks>
  42. /// This class only works on Windows 2000 and higher.
  43. /// </remarks>
  44. public class PacketMonitor {
  45. /// <summary>
  46. /// Initializes a new instance of the PacketMonitor class.
  47. /// </summary>
  48. /// <param name="ip">The interface on which to listen for IP packets.</param>
  49. /// <exception cref="NotSupportedException">The operating system does not support intercepting packets.</exception>
  50. public PacketMonitor(IPAddress ip) {
  51. // make sure the user runs this program on Windows NT 5.0 or higher
  52. if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 5)
  53. throw new NotSupportedException("This program requires Windows 2000, Windows XP or Windows .NET Server!");
  54. // make sure the user is an Administrator
  55. if (!IsUserAnAdmin())
  56. throw new NotSupportedException("This program can only be run by administrators!");
  57. m_IP = ip;
  58. m_Buffer = new byte[65535];
  59. }
  60. /// <summary>
  61. /// Cleans up the unmanaged resources.
  62. /// </summary>
  63. ~PacketMonitor() {
  64. Stop();
  65. }
  66. /// <summary>
  67. /// Starts listening on the specified interface.
  68. /// </summary>
  69. /// <exception cref="SocketException">An error occurs when trying to intercept IP packets.</exception>
  70. public void Start() {
  71. if (m_Monitor == null) {
  72. try {
  73. m_Monitor = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
  74. m_Monitor.Bind(new IPEndPoint(IP, 0));
  75. byte[] outValue = BitConverter.GetBytes(0);
  76. byte[] inValue = BitConverter.GetBytes(1);
  77. m_Monitor.IOControl(IOControlCode.ReceiveAll, inValue, outValue);
  78. m_Monitor.BeginReceive(m_Buffer, 0, m_Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnReceive), null);
  79. } catch {
  80. m_Monitor = null;
  81. throw new SocketException();
  82. }
  83. }
  84. }
  85. /// <summary>
  86. /// Stops listening on the specified interface.
  87. /// </summary>
  88. public void Stop() {
  89. if (m_Monitor != null) {
  90. m_Monitor.Close();
  91. m_Monitor = null;
  92. }
  93. }
  94. /// <summary>
  95. /// Called when the socket intercepts an IP packet.
  96. /// </summary>
  97. /// <param name="ar">The asynchronous result.</param>
  98. private void OnReceive(IAsyncResult ar) {
  99. try {
  100. int received = m_Monitor.EndReceive(ar);
  101. try {
  102. if (m_Monitor != null) {
  103. byte[] packet = new byte[received];
  104. Array.Copy(Buffer, 0, packet, 0, received);
  105. OnNewPacket(new Packet(packet));
  106. }
  107. } catch {} // invalid packet; ignore
  108. m_Monitor.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnReceive), null);
  109. } catch {
  110. Stop();
  111. }
  112. }
  113. /// <summary>
  114. /// The interface used to intercept IP packets.
  115. /// </summary>
  116. /// <value>An <see cref="IPAddress"/> instance.</value>
  117. public IPAddress IP {
  118. get {
  119. return m_IP;
  120. }
  121. }
  122. /// <summary>
  123. /// The buffer used to store incoming IP packets.
  124. /// </summary>
  125. /// <value>An array of bytes.</value>
  126. protected byte[] Buffer {
  127. get {
  128. return m_Buffer;
  129. }
  130. }
  131. /// <summary>
  132. /// Raises an event that indicates a new packet has arrived.
  133. /// </summary>
  134. /// <param name="p">The arrived <see cref="Packet"/>.</param>
  135. protected void OnNewPacket(Packet p) {
  136. if (NewPacket != null)
  137. NewPacket(this, p);
  138. }
  139. /// <summary>
  140. /// Holds all the listeners for the NewPacket event.
  141. /// </summary>
  142. public event NewPacketEventHandler NewPacket;
  143. // private variables
  144. private Socket m_Monitor;
  145. private IPAddress m_IP;
  146. private byte[] m_Buffer;
  147. private const int IOC_VENDOR = 0x18000000;
  148. private const int IOC_IN = -2147483648; //0x80000000; /* copy in parameters */
  149. private const int SIO_RCVALL = IOC_IN | IOC_VENDOR | 1;
  150. private const int SECURITY_BUILTIN_DOMAIN_RID = 0x20;
  151. private const int DOMAIN_ALIAS_RID_ADMINS = 0x220;
  152. /// <summary>
  153. /// Tests whether the current user is a member of the Administrator's group.
  154. /// </summary>
  155. /// <returns>Returns <b>true</b> if the user is a member of the Administrator's group, <b>false</b> if not.</returns>
  156. private bool IsUserAnAdmin() {
  157. byte[] NtAuthority = new byte[6];
  158. NtAuthority[5] = 5; // SECURITY_NT_AUTHORITY
  159. IntPtr AdministratorsGroup;
  160. int ret = AllocateAndInitializeSid(NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, out AdministratorsGroup);
  161. if (ret != 0) {
  162. if (CheckTokenMembership(IntPtr.Zero, AdministratorsGroup, ref ret) == 0) {
  163. ret = 0;
  164. }
  165. FreeSid(AdministratorsGroup);
  166. }
  167. return (ret != 0);
  168. }
  169. /// <summary>
  170. /// The AllocateAndInitializeSid function allocates and initializes a security identifier (SID) with up to eight subauthorities.
  171. /// </summary>
  172. /// <param name="pIdentifierAuthority">Pointer to a SID_IDENTIFIER_AUTHORITY structure, giving the top-level identifier authority value to set in the SID.</param>
  173. /// <param name="nSubAuthorityCount">Specifies the number of subauthorities to place in the SID. This parameter also identifies how many of the subauthority parameters have meaningful values. This parameter must contain a value from 1 to 8.</param>
  174. /// <param name="dwSubAuthority0">Subauthority value to place in the SID.</param>
  175. /// <param name="dwSubAuthority1">Subauthority value to place in the SID.</param>
  176. /// <param name="dwSubAuthority2">Subauthority value to place in the SID.</param>
  177. /// <param name="dwSubAuthority3">Subauthority value to place in the SID.</param>
  178. /// <param name="dwSubAuthority4">Subauthority value to place in the SID.</param>
  179. /// <param name="dwSubAuthority5">Subauthority value to place in the SID.</param>
  180. /// <param name="dwSubAuthority6">Subauthority value to place in the SID.</param>
  181. /// <param name="dwSubAuthority7">Subauthority value to place in the SID.</param>
  182. /// <param name="pSid">Pointer to a variable that receives the pointer to the allocated and initialized SID structure.</param>
  183. /// <returns>If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.</returns>
  184. [DllImport("advapi32.dll")]
  185. private extern static int AllocateAndInitializeSid(byte[] pIdentifierAuthority, byte nSubAuthorityCount, int dwSubAuthority0, int dwSubAuthority1, int dwSubAuthority2, int dwSubAuthority3, int dwSubAuthority4, int dwSubAuthority5, int dwSubAuthority6, int dwSubAuthority7, out IntPtr pSid);
  186. /// <summary>
  187. /// The CheckTokenMembership function determines whether a specified SID is enabled in an access token.
  188. /// </summary>
  189. /// <param name="TokenHandle">Handle to an access token. The handle must have TOKEN_QUERY access to the token. The token must be an impersonation token.</param>
  190. /// <param name="SidToCheck">Pointer to a SID structure. The CheckTokenMembership function checks for the presence of this SID in the user and group SIDs of the access token.</param>
  191. /// <param name="IsMember">Pointer to a variable that receives the results of the check. If the SID is present and has the SE_GROUP_ENABLED attribute, IsMember returns TRUE; otherwise, it returns FALSE.</param>
  192. /// <returns>If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.</returns>
  193. [DllImport("advapi32.dll")]
  194. private extern static int CheckTokenMembership(IntPtr TokenHandle, IntPtr SidToCheck, ref int IsMember);
  195. /// <summary>
  196. /// The FreeSid function frees a security identifier (SID) previously allocated by using the AllocateAndInitializeSid function.
  197. /// </summary>
  198. /// <param name="pSid">Pointer to the SID structure to free.</param>
  199. /// <returns>This function does not return a value.</returns>
  200. [DllImport("advapi32.dll")]
  201. private extern static IntPtr FreeSid(IntPtr pSid);
  202. // <summary>
  203. // Tests whether the current user is a member of the Administrator's group.
  204. // </summary>
  205. // <returns>Returns TRUE if the user is a member of the Administrator's group, FALSE if not.</returns>
  206. //[DllImport("shell32.dll")]
  207. //private extern static int IsUserAnAdmin();
  208. }
  209. /// <summary>
  210. /// Represents the method that will handle the NewPacket event.
  211. /// </summary>
  212. /// <param name="pm">The <see cref="PacketMonitor"/> that intercepted the <see cref="Packet"/>.</param>
  213. /// <param name="p">The newly arrived <see cref="Packet"/>.</param>
  214. public delegate void NewPacketEventHandler(PacketMonitor pm, Packet p);
  215. }