Esempio n. 1
0
        public SocketSniffer(NetworkInterfaceInfo nic, Filters <IPPacket> filters, IOutput output)
        {
            this.outputQueue = new BlockingCollection <TimestampedData>();
            this.filters     = filters;
            this.output      = output;

            this.bufferManager = new BufferManager(BUFFER_SIZE, MAX_RECEIVE);
            this.receivePool   = new ConcurrentStack <SocketAsyncEventArgs>();
            var endPoint = new IPEndPoint(nic.IPAddress, 0);

            // Capturing at the IP level is not supported on Linux
            // https://github.com/dotnet/corefx/issues/25115
            // https://github.com/dotnet/corefx/issues/30197
            var protocolType = SystemInformation.IsWindows
                ? ProtocolType.IP
                : ProtocolType.Tcp;

            // IPv4
            this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, protocolType);
            this.socket.Bind(endPoint);
            this.socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);

            // Enter promiscuous mode on Windows only
            if (SystemInformation.IsWindows)
            {
                EnterPromiscuousMode();
            }
        }
Esempio n. 2
0
        public static IList <NetworkInterfaceInfo> GetInterfaces()
        {
            var nicInfos = new List <NetworkInterfaceInfo>();
            var nics     = NetworkInterface.GetAllNetworkInterfaces();

            foreach (var nic in nics)
            {
                var ipAddresses = nic.GetIPProperties().UnicastAddresses.Where(x =>
                                                                               x.Address != null && x.Address.AddressFamily == AddressFamily.InterNetwork);

                foreach (var ipAddress in ipAddresses)
                {
                    var nicInfo = new NetworkInterfaceInfo
                    {
                        Index     = nicInfos.Count,
                        Id        = nic.Id,
                        Name      = nic.Name,
                        IPAddress = ipAddress.Address
                    };

                    nicInfos.Add(nicInfo);
                }
            }

            return(nicInfos);
        }
Esempio n. 3
0
        public SocketSniffer(NetworkInterfaceInfo nic, Filters<IPPacket> filters, IOutput output)
        {
            this.outputQueue = new BlockingCollection<TimestampedData>();
            this.filters = filters;
            this.output = output;

            this.bufferManager = new BufferManager(BUFFER_SIZE, MAX_RECEIVE);
            this.receivePool = new ConcurrentStack<SocketAsyncEventArgs>();
            var endPoint = new IPEndPoint(nic.IPAddress, 0);

            // IPv4
            this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
            this.socket.Bind(endPoint);
            this.socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);

            // Enter promiscuous mode
            try
            {
                this.socket.IOControl(IOControlCode.ReceiveAll, BitConverter.GetBytes(1), new byte[4]);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to enter promiscuous mode: {0}", ex);
                throw;
            }
        }
Esempio n. 4
0
        private static void ShowHelp(AppOptions appOptions)
        {
            Console.WriteLine(@"      __.---,__                ");
            Console.WriteLine(@"   .-`         '-,__           ");
            Console.WriteLine(@" &/           ',_\ _\          ");
            Console.WriteLine(@" /               '',_          ");
            Console.WriteLine(@" |    .            ("")         ");
            Console.WriteLine(@" |__.`'-..--|__|--``   Snifter ");
            Console.WriteLine();

            Console.WriteLine("Usage:");
            Console.WriteLine("snifter -i x -f filename");
            Console.WriteLine();
            Console.WriteLine(appOptions.OptionsHelpText);
            Console.WriteLine();

            var nicInfos = NetworkInterfaceInfo.GetInterfaces();

            Console.WriteLine("ID\tIP Address\tName");
            Console.WriteLine("===========================================================");

            foreach (var nicInfo in nicInfos)
            {
                Console.WriteLine("{0}\t{1}\t{2}", nicInfo.Index, nicInfo.IPAddress, nicInfo.Name);
            }
        }
Esempio n. 5
0
        public static IList<NetworkInterfaceInfo> GetInterfaces()
        {
            var nicInfos = new List<NetworkInterfaceInfo>();
            var nics = NetworkInterface.GetAllNetworkInterfaces();

            foreach (var nic in nics)
            {
                var ipAddresses = nic.GetIPProperties().UnicastAddresses.Where(x =>
                    x.Address != null && x.Address.AddressFamily == AddressFamily.InterNetwork);

                foreach (var ipAddress in ipAddresses)
                {
                    var nicInfo = new NetworkInterfaceInfo
                    {
                        Index = nicInfos.Count,
                        Id = nic.Id,
                        Name = nic.Name,
                        IPAddress = ipAddress.Address
                    };

                    nicInfos.Add(nicInfo);
                }
            }

            return nicInfos;
        }
Esempio n. 6
0
        /// <summary>
        /// Create a new raw socket sniffer
        /// </summary>
        /// <param name="nic">Network interface from which to capture packets</param>
        /// <param name="filters">Filters to apply before outputting packets or raising events</param>
        /// <param name="output">An optional output to which matching packets should be written, such as a PCAPNG file</param>
        /// <param name="maxProcessQueue">Maximum size of the packet processing queue. Defaults to 10,000</param>
        /// <param name="logger">An optional logger, used only for logging errors</param>
        public SocketSniffer(NetworkInterfaceInfo nic, Filters <IIpPacket> filters, IOutput output = null,
                             int maxProcessQueue = MAX_PROCESS_QUEUE, ILogger logger = null)
        {
            this.logger       = logger ?? NullLogger.Instance;
            this.filters      = filters;
            this.output       = output;
            this.processQueue = new BlockingCollection <TimestampedData>(maxProcessQueue);

            // Capturing at the IP level is not supported on Linux
            // https://github.com/dotnet/corefx/issues/25115
            // https://github.com/dotnet/corefx/issues/30197
            var protocolType = SystemInformation.IsWindows
                ? ProtocolType.IP
                : ProtocolType.Tcp;

            // IPv4
            var endPoint = new IPEndPoint(nic.IPAddress, 0);

            this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, protocolType);
            this.socket.Bind(endPoint);
            this.socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);

            var buffer = new byte[BUFFER_SIZE];

            this.socketEventArgs.Completed += (e, args) => OnReceived(socketEventArgs);
            this.socketEventArgs.SetBuffer(buffer, 0, BUFFER_SIZE);

            // Enter promiscuous mode on Windows only
            if (SystemInformation.IsWindows)
            {
                EnterPromiscuousMode();
            }
        }
Esempio n. 7
0
        public SocketSniffer(NetworkInterfaceInfo nic, Filters <IPPacket> filters, IOutput output)
        {
            this.outputQueue = new BlockingCollection <TimestampedData>();
            this.filters     = filters;
            this.output      = output;

            this.bufferManager = new BufferManager(BUFFER_SIZE, MAX_RECEIVE);
            this.receivePool   = new ConcurrentStack <SocketAsyncEventArgs>();
            var endPoint = new IPEndPoint(nic.IPAddress, 0);

            // IPv4
            this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
            this.socket.Bind(endPoint);
            this.socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);

            // Enter promiscuous mode
            try
            {
                this.socket.IOControl(IOControlCode.ReceiveAll, BitConverter.GetBytes(1), new byte[4]);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to enter promiscuous mode: {0}", ex);
                throw;
            }
        }
Esempio n. 8
0
        static void Main(string[] args)
        {
            // You can only create raw sockets with elevated privileges
            if (!IsElevated())
            {
                Console.WriteLine("Please run with elevated prilileges");
                Environment.Exit(1);
            }

            var appOptions = ParseCommandLine(args);

            if (appOptions.ShowHelp)
            {
                ShowHelp(appOptions);
                Environment.Exit(0);
            }

            var nics = NetworkInterfaceInfo.GetInterfaces();

            if ((!appOptions.InterfaceId.HasValue) ||
                (appOptions.InterfaceId > nics.Count - 1) ||
                (appOptions.InterfaceId < 0))
            {
                Console.WriteLine("Invalid interface ID");
                ShowHelp(appOptions);
                Environment.Exit(3);
            }

            var filters = appOptions.BuildFilters();
            var nic     = nics[appOptions.InterfaceId.Value];

            // Start capturing packets
            var output  = new PcapNgFileOutput(nic, appOptions.Filename);
            var sniffer = new SocketSniffer(nic, filters, output);

            sniffer.Start();

            Console.WriteLine();
            Console.WriteLine("Capturing on interface {0} ({1})", nic.Name, nic.IPAddress);
            Console.WriteLine("Saving to file {0}", appOptions.Filename);
            Console.WriteLine("Press CTRL+C to stop");
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();

            // Shutdown gracefully on CTRL+C
            Console.CancelKeyPress += ConsoleOnCancelKeyPress;

            while (!isStopping)
            {
                Console.SetCursorPosition(0, Console.CursorTop - 2);
                Console.WriteLine("Packets Observed: {0}", sniffer.PacketsObserved);
                Console.WriteLine("Packets Captured: {0}", sniffer.PacketsCaptured);

                Thread.Sleep(200);
            }

            sniffer.Stop();
        }
Esempio n. 9
0
        private static void ShowHelp(AppOptions appOptions)
        {
            Console.WriteLine("Usage:");
            Console.WriteLine("snifter -i x -f filename");
            Console.WriteLine();
            Console.WriteLine(appOptions.OptionsHelpText);
            Console.WriteLine();

            var nicInfos = NetworkInterfaceInfo.GetInterfaces();

            Console.WriteLine("ID\tIP Address\tName");
            Console.WriteLine("===========================================================");

            foreach (var nicInfo in nicInfos)
            {
                Console.WriteLine("{0}\t{1}\t{2}", nicInfo.Index, nicInfo.IPAddress, nicInfo.Name);
            }
        }