Esempio n. 1
0
        private SendQueue GeneratePackets(bool onClose)
        {
            var iface        = PacketDispatcher.Instance.GetCurrentInterface();
            var routingTable = IPv4Router.Instance.GetRoutingTable();

            lock (routingTable)
            {
                if (routingTable.Count == 0)
                {
                    return(null);
                }

                var gatewayMAC = routingTable[iface.IPv4Gateway];
                var sendQueue  = new SendQueue(64 * 4 * routingTable.Count);

                foreach (var entry in routingTable)
                {
                    // skip generating ARP replies for local gateway and local IP address entries
                    if (entry.Key.Equals(iface.IPv4Gateway) || entry.Key.Equals(iface.IPv4Address))
                    {
                        continue;
                    }

                    if (onClose)
                    {
                        // "friendly" ARP reply to gateway
                        sendQueue.Add(GenerateARPReply(entry.Key, entry.Value, iface.IPv4Gateway, gatewayMAC, iface.HardwareAddress).Bytes);

                        // "friendly" ARP reply to clients
                        sendQueue.Add(GenerateARPReply(iface.IPv4Gateway, gatewayMAC, entry.Key, entry.Value, iface.HardwareAddress).Bytes);
                    }
                    else
                    {
                        // fake ARP reply to gateway
                        sendQueue.Add(GenerateARPReply(entry.Key, iface.HardwareAddress, iface.IPv4Gateway, gatewayMAC).Bytes);

                        // fake ARP reply to clients
                        sendQueue.Add(GenerateARPReply(iface.IPv4Gateway, iface.HardwareAddress, entry.Key, entry.Value).Bytes);
                    }
                }

                return(sendQueue);
            }
        }
Esempio n. 2
0
        private async Task AckHandlerMethod(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    // Send every three minutes
                    await Task.Delay(3 * 60 * 1000, cancellationToken);

                    // Don't run this time if there aren't any messages to acknowledge
                    if (!PendingAcks.Any())
                    {
                        continue;
                    }

                    // Take all the required acks out of the bag
                    var acks = new List <long>();
                    while (PendingAcks.TryTake(out var ack))
                    {
                        acks.Add(ack);
                    }

                    Logger.Log(Logger.Level.Debug, $"Found {acks.Count} messages that need acknowledgement.  Adding them to the payload.");

                    // Create a request that contains the list of acks
                    var Acks_Request = new RequestState(Schema.msgs_ack(new { msg_ids = acks }));

                    // Add the request to both the send queue (to be sent to the server) and
                    // the sent acks queue (in case we need to resend.  We don't want to place
                    // in pending since there shouldn't be a response.
                    SendQueue.Add(Acks_Request);
                    SentAcks.Put(Acks_Request);

                    // Send the acks to the server
                    // ToDo: If the user will be polling for updates, can we skip this line
                    // and let the acks be sent for us?
                    Task unawaited = Task.Run(() => ProcessSendQueue());
                }
                catch (TaskCanceledException)
                {
                    // We don't really care if the task was cancelled.
                    break;
                }
                catch (ObjectDisposedException)
                {
                    // We don't really care if the task was cancelled.
                    break;
                }
                catch (Exception ex)
                {
                    // ToDo: Do we really want to skip all acks when this happens?  Likely we
                    // will encounter the same error again if we reprocess...
                    Logger.Log(Logger.Level.Error, $"An error occurred process acks.  Skipping.\n\n{ex.Message}");
                }
            }
        }
        private void InformSenderAboutFinish()
        {
            var msg = new Message
            {
                MsgType       = MessageType.EndingProgram,
                SendingServer = this.NodeAddress
            };
            var messageWrapper = new RemoteDispatch(msg, null);

            SendQueue.Add(messageWrapper);
        }
        private static async Task <string> SendData(string Request)
        {
            var RequestObject = new RequestObject()
            {
                Request  = Request,
                Response = new TaskCompletionSource <string>()
            };

            SendQueue.Add(RequestObject);

            return(await RequestObject.Response.Task);
        }
Esempio n. 5
0
        // worker function for sending ARP requests
        private void WorkerSender()
        {
            // get start/end IP
            if (deviceInfo.Mask == "0.0.0.0")
            {
                deviceInfo.Mask = "255.255.255.0";
                ShowInputDialog(ref deviceInfo.Mask);
            }
            long[] range = Network.MaskToStartEnd(deviceInfo.IP, deviceInfo.Mask);

            long startIP   = range[0];
            long tot_endIP = range[1];
            long currentIP = startIP;
            int  chunkSize = 16;

            while (currentIP <= tot_endIP)
            {
                var possibilities = Math.Min((int)tot_endIP - (int)currentIP, chunkSize);
                var endIP         = currentIP + possibilities;
                var sendQueue     = new SendQueue(possibilities * 80);

                // There are still losses in arp, try to send packet in chunks

                var deviceIP = IPAddress.Parse(deviceInfo.IP);

                // create ARP requests for all the hosts in our subnet);
                while (currentIP <= endIP)
                {
                    sendQueue.Add(GenerateARPRequest(Network.LongToIP(currentIP), deviceIP).Bytes);

                    currentIP++;
                }

                // send our queue
                //sendQueue.Transmit(device, SendQueueTransmitModes.Normal);
                // There are losses in ARP part, not sure why, try different timing for better accuracy
                sendQueue.Transmit(device, SendQueueTransmitModes.Synchronized);

                Thread.Sleep(1000);
            }
            Thread.Sleep(3000);
            // stop other threads and stop scanning
            Started = false;

            workerARP.Join();
            workerNDP.Join();

            ScanCompleted();

            return;
        }
 internal override void AddToSendQueue(Packet packet)
 {
     if (IsSendingQueue)
     {
         lock (SendTempQueueLock)
         {
             SendTempQueue?.Add(packet);
         }
     }
     else
     {
         SendQueue?.Add(packet);
     }
 }
Esempio n. 7
0
        // worker for sending ARP reply packets
        public void WorkerSender()
        {
            var sendQueue = new SendQueue((SpoofingTargets1.Count * 2 * 60) + 60);

            foreach (Target target1 in SpoofingTargets1)
            {
                // send fake replies to the gateway
                sendQueue.Add(GenerateARPReply(target1.IP, SpoofingTarget2.IP, SpoofingTarget2.PMAC).Bytes);

                // senda fake replies to targets
                sendQueue.Add(GenerateARPReply(SpoofingTarget2.IP, target1.IP, target1.PMAC).Bytes);
            }

            while (SpoofingStarted)
            {
                sendQueue.Transmit(device, SendQueueTransmitModes.Normal);

                Thread.Sleep(2500);
            }

            sendQueue.Dispose();

            return;
        }
        private void BarrierWithTimeout()
        {
            var msg = new Message
            {
                MsgType       = MessageType.BarrierResponse,
                SendingServer = NodeAddress,
            };

            foreach (var remoteAddress in RemoteAddressesList)
            {
                var respond = new RemoteDispatch(msg, remoteAddress);
                SendQueue.Add(respond);
            }

            Console.WriteLine("Waiting on barrier");
            if (!SyncBarrier.Wait(TimeSpan.FromSeconds(Timeout)))
            {
                throw new Exception("Barrier timeout");
            }
        }
Esempio n. 9
0
        // worker function for sending ARP requests
        private void WorkerSender()
        {
            for (int i = 0; i < 3; i++)
            {
                // get start/end IP
                long[] range = Network.MaskToStartEnd(deviceInfo.IP, deviceInfo.Mask);

                long startIP   = range[0];
                long endIP     = range[1];
                long currentIP = startIP;

                var possibilities = (int)endIP - (int)startIP;

                var sendQueue = new SendQueue(possibilities * 80);
                var deviceIP  = IPAddress.Parse(deviceInfo.IP);

                // create ARP requests for all the hosts in our subnet);
                while (currentIP <= endIP)
                {
                    sendQueue.Add(GenerateARPRequest(Network.LongToIP(currentIP), deviceIP).Bytes);

                    currentIP++;
                }

                // send our queue
                sendQueue.Transmit(device, SendQueueTransmitModes.Normal);
                Thread.Sleep(3000);
            }


            // stop other threads and stop scanning
            Started = false;

            workerARP.Join();
            workerNDP.Join();

            ScanCompleted();

            return;
        }
Esempio n. 10
0
        /// <summary>
        /// Cleanly disconnects the server.  Pending requests are placed back in a sending queue to be resent upon reconnection
        /// </summary>
        public void Disconnect()
        {
            // Close the connection superficially
            CommunicationEstablished = false;

            try
            {
                // Stop the ack processing loop.
                Logger.Log <MTProtoSender>(Logger.Level.Debug, $"Trying to stop Ack Handler");
                if (AckCancellation != null)
                {
                    AckCancellation.Cancel();
                }
                if (AckHandler != null)
                {
                    AckHandler.Wait();
                }

                // Close the connection to the server
                // ToDo: Should we also dispose?
                Connection.Disconnect();

                // Remove any event handlers
                Logger.Log <MTProtoSender>(Logger.Level.Debug, $"Removing event handlers");
                Connection.DataReceivedEvent -= Connection_DataReceivedEvent;

                // Place all the pending messages back in the queue to resend
                // Note: Leave pending acks alone.  We will pick up where we left off later
                PendingQueue.Values.ToList().ForEach(x => SendQueue.Add(x));
                PendingQueue.Clear();
            }
            catch (Exception ex)
            {
                Logger.Log(Logger.Level.Error, $"An error occurred while disconnecting.\n\n{ex.Message}");
            }
        }
Esempio n. 11
0
        private void PacketProcessor()
        {
            DebugInformation.WriteLine("[PD] Packet processor started.");

            var localPacketBuffer = new List <EthernetPacket>();
            var packetBytes       = 0;

            while (started)
            {
                EthernetPacket rawPacket;

                // wait if there haven't been any new packets put into queue
                packetsAvailable.WaitOne();

                // get packets from queue and add them to the local buffer
                while (packetBuffer.TryDequeue(out rawPacket) && rawPacket != null)
                {
                    localPacketBuffer.Add(rawPacket);

                    packetBytes += rawPacket.BytesHighPerformance.BytesLength;

                    // add 16 bytes | TODO: find out why there are always 16 more bytes needed for each packet
                    packetBytes += 16;
                }

                packetsAvailable.Reset();

                var packetQueue = new SendQueue(packetBytes * packetRouters.Count);

                // loop through local packet buffer
                foreach (var packet in localPacketBuffer)
                {
                    // skip local packets
                    if (iface.IsLocalIPv4Packet(packet))
                    {
                        continue;
                    }

                    // send to packet readers
                    foreach (IPacketReader reader in packetReaders)
                    {
                        reader.ReadPacket(packet);
                    }

                    // send to packet filters, skip routing step for filtered packets
                    lock (packetFilters)
                    {
                        foreach (IPacketFilter filter in packetFilters)
                        {
                            if (filter.Enabled && filter.FilterPacket(packet))
                            {
                                continue;
                            }
                        }
                    }

                    // send to packet routers
                    foreach (IPacketRouter router in packetRouters)
                    {
                        var routedPacket = router.RoutePacket(packet);

                        if (routedPacket != null)
                        {
                            packetQueue.Add(routedPacket.Bytes);
                        }
                    }
                }

                // send out all the routed packets
                packetQueue.TransmitAll(iface.PcapDevice);

                localPacketBuffer.Clear();
                packetBytes = 0;
            }

            DebugInformation.WriteLine("[PD] Packet processor stopped.");
        }
Esempio n. 12
0
        // worker function for routing IPv6 packets
        public void WorkerRouter()
        {
            while (SpoofingStarted)
            {
                // size of packets - needed for send queue (set some starting value - it seems the length is not set correctly during threadQueue packet copying)
                int bufferSize = 2048;

                // copy packets to threadRoutingQueue
                lock (PacketQueueRouting)
                {
                    foreach (Packet packet in PacketQueueRouting)
                    {
                        threadQueueRouting.Add(packet);
                        bufferSize += packet.Bytes.Length;
                    }

                    PacketQueueRouting.Clear();
                }

                if (threadQueueRouting.Count > 0)
                {
                    var sendQueue = new SendQueue(bufferSize);

                    // loop through packets and change MAC addresses
                    foreach (Packet packet in threadQueueRouting)
                    {
                        if (packet == null)
                        {
                            continue;
                        }

                        var ethernetPacket = (packet as EthernetPacket);
                        if (ethernetPacket == null)
                        {
                            continue;
                        }

                        var ip = (packet is IpPacket ? (IpPacket)packet : IpPacket.GetEncapsulated(packet));

                        var sourceIP      = ip.SourceAddress.ToString();
                        var destinationIP = ip.DestinationAddress.ToString();

                        var destinationMAC = ethernetPacket.DestinationHwAddress.ToString();

                        if (sourceIP == deviceInfo.IPv6 || destinationIP == deviceInfo.IPv6)
                        {
                            continue;
                        }

                        // skip local network traffic
                        if ((sourceIP.Contains(prefix.Replace("::", ":")) && destinationIP.Contains(prefix.Replace("::", ":"))) || (sourceIP.Contains("fe80::") || destinationIP.Contains("fe80::")))
                        {
                            continue;
                        }

                        // check for IPv6 - MAC entry existance (check only addresses from this network) and add it if necessary (we need this because scanner cannot pick up IPv6 addresses of all the targets)
                        if (sourceIP.Contains(prefix.Replace("::", ":")) && !IPv6toMACTargets.ContainsKey(sourceIP) && !sourceIP.Contains("fe80::"))
                        {
                            lock (IPv6toMACTargets)
                            {
                                IPv6toMACTargets.Add(sourceIP, ethernetPacket.SourceHwAddress);
                            }
                        }

                        // incoming packets (internet -> nighthawk) - change destination MAC back to target's MAC
                        if (IPv6toMACTargets.ContainsKey(destinationIP) && (destinationMAC != IPv6toMACTargets[destinationIP].ToString()))
                        {
                            ethernetPacket.SourceHwAddress      = physicalAddress;
                            ethernetPacket.DestinationHwAddress = IPv6toMACTargets[destinationIP];

                            if (ethernetPacket.Bytes != null)
                            {
                                sendQueue.Add(packet.Bytes);
                            }
                        }

                        // outgoing packets (targets -> nighthawk) - change destination MAC to gateway's MAC
                        if (IPv6toMACTargets.ContainsKey(sourceIP) && (destinationMAC != IPv6toMACTargets[gatewayIPv6].ToString()))
                        {
                            ethernetPacket.SourceHwAddress      = physicalAddress;
                            ethernetPacket.DestinationHwAddress = IPv6toMACTargets[gatewayIPv6];

                            if (ethernetPacket.Bytes != null)
                            {
                                sendQueue.Add(packet.Bytes);
                            }
                        }
                    }

                    sendQueue.Transmit(device, SendQueueTransmitModes.Normal);
                    sendQueue.Dispose();

                    threadQueueRouting.Clear();
                }
                else
                {
                    Thread.Sleep(1);
                }
            }

            return;
        }
Esempio n. 13
0
        public void Send(string content, UInt16 port, string address)
        {
            SuzukiMessage msg = new SuzukiMessage(content, port, address);

            SendQueue.Add(msg);
        }
Esempio n. 14
0
        // worker for routing IPv4 packets
        public void WorkerRouter()
        {
            while (SpoofingStarted)
            {
                // size of packets - needed for send queue (set some starting value - it seems the length is not set correctly during threadQueue packet copying)
                int bufferSize = 2048;

                // copy packets to thread's packet storage (threadRoutingQueue)
                lock (PacketQueueRouting)
                {
                    foreach (Packet packet in PacketQueueRouting)
                    {
                        threadQueueRouting.Add(packet);
                        bufferSize += packet.Bytes.Length;
                    }

                    PacketQueueRouting.Clear();
                }

                if (threadQueueRouting.Count > 0)
                {
                    var sendQueue = new SendQueue(bufferSize);

                    // loop through packets and change MAC addresses
                    foreach (Packet packet in threadQueueRouting)
                    {
                        if (packet == null)
                        {
                            continue;
                        }

                        var ethernetPacket = (packet as EthernetPacket);
                        if (ethernetPacket == null)
                        {
                            continue;
                        }

                        var ip = (packet is IpPacket ? (IpPacket)packet : IpPacket.GetEncapsulated(packet));

                        // discard invalid packets
                        if (ip is IPv4Packet && (((IPv4Packet)ip).Checksum == 0 || !((IPv4Packet)ip).ValidIPChecksum))
                        {
                            continue;
                        }

                        var sourceIP      = ip.SourceAddress.ToString();
                        var destinationIP = ip.DestinationAddress.ToString();

                        var sourceMAC      = ethernetPacket.SourceHwAddress.ToString();
                        var destinationMAC = ethernetPacket.DestinationHwAddress.ToString();

                        if (destinationMAC == sourceMAC)
                        {
                            continue;
                        }

                        // block PPTP if necessary (exclude local computer)
                        if (blockPPTP && sourceIP != deviceInfo.IP && destinationIP != deviceInfo.IP)
                        {
                            // block GRE
                            if (ip.Protocol == IPProtocolType.GRE)
                            {
                                continue;
                            }

                            // check for port 1723 and block it
                            if (ip.Protocol == IPProtocolType.TCP)
                            {
                                var tcp = TcpPacket.GetEncapsulated(packet);

                                if (tcp != null && (tcp.SourcePort == 1723 || tcp.DestinationPort == 1723))
                                {
                                    continue;
                                }
                            }
                        }

                        // incoming packets - change destination MAC back to target's MAC
                        if (IPtoMACTargets1.ContainsKey(destinationIP) && (destinationMAC != IPtoMACTargets1[destinationIP].ToString()))
                        {
                            ethernetPacket.SourceHwAddress      = physicalAddress;
                            ethernetPacket.DestinationHwAddress = IPtoMACTargets1[destinationIP];

                            if (ethernetPacket.Bytes != null)
                            {
                                sendQueue.Add(packet.Bytes);
                            }
                        }

                        // outgoing packets - change destination MAC to gateway's MAC
                        if (IPtoMACTargets1.ContainsKey(sourceIP) && (destinationMAC != SpoofingTarget2.PMAC.ToString()))
                        {
                            ethernetPacket.SourceHwAddress      = physicalAddress;
                            ethernetPacket.DestinationHwAddress = SpoofingTarget2.PMAC;

                            if (ethernetPacket.Bytes != null)
                            {
                                sendQueue.Add(packet.Bytes);
                            }
                        }
                    }

                    sendQueue.Transmit(device, SendQueueTransmitModes.Normal);
                    sendQueue.Dispose();

                    threadQueueRouting.Clear();
                }
                else
                {
                    Thread.Sleep(1);
                }
            }

            return;
        }
Esempio n. 15
0
 public void Send(byte[] packet, bool dontCompress = false)
 {
     SendQueue.Add(SendArgs, packet, dontCompress);
 }
Esempio n. 16
0
        static void Main(string[] args)
        {
            //显示SharpPcap版本
            string ver = SharpPcap.Version.VersionString;
            Console.WriteLine("SharpPcap {0}", ver);

            //获取网络设备
            var devices = LivePcapDeviceList.Instance;
            if (devices.Count < 1)
            {
                Console.WriteLine("找不到网络设备");
                return;
            }
            Console.WriteLine();
            Console.WriteLine("以下是目前本计算机上的活动网络设备:");
            Console.WriteLine("----------------------------------------------------");
            Console.WriteLine();
            int i = 0;
            foreach (LivePcapDevice dev in devices)
            {
                Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description);
                i++;
            }

            //选择要监听的网络设备
            Console.WriteLine();
            Console.Write("-- 请选择一个需要监听的网络设备: ");
            i = int.Parse(Console.ReadLine());
            LivePcapDevice device = devices[i];

            Console.Write("-- 请选择操作:监听通讯[C/c],多线程监听通讯[T/t],监听统计[F/f],发送随机数据包[S/s]? ");
            string resp = Console.ReadLine().ToUpper();

            while (!(resp.StartsWith("C") || resp.StartsWith("F") || resp.StartsWith("T") || resp.StartsWith("S")))
            {
                resp = Console.ReadLine().ToUpper();
            }

            try
            {
                if (resp.StartsWith("C") || resp.StartsWith("F") || resp.StartsWith("T"))
                {
                    //监听过滤条件
                    //string filter = "ip and tcp";
                    string filter = "";

                    //连接设备
                    System.Threading.Thread backgroundThread = null;
                    int readTimeoutMilliseconds = 1000;
                    if (resp.StartsWith("F"))
                    {
                        device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
                        device.SetFilter(filter);
                        device.Mode = CaptureMode.Statistics; //抓包统计
                        device.OnPcapStatistics += new StatisticsModeEventHandler(device_OnPcapStatistics); //抓包统计回调事件
                    }
                    else if (resp.StartsWith("C"))
                    {
                        device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
                        device.SetFilter(filter);
                        device.Mode = CaptureMode.Packets; //抓数据包
                        showDetails = resp.EndsWith("-A"); //当抓数据包时,检查是否要查看详情
                        device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); //抓数据包回调事件
                    }
                    else
                    {
                        backgroundThread = new System.Threading.Thread(BackgroundThread);
                        backgroundThread.Start();
                        device.Open();
                        device.SetFilter(filter);
                        device.Mode = CaptureMode.Packets; //抓数据包
                        showDetails = resp.EndsWith("-A"); //当抓数据包时,检查是否要查看详情
                        device.OnPacketArrival += new PacketArrivalEventHandler(device_OnThreadPacketArrival); //抓数据包回调事件
                    }

                    Console.WriteLine();
                    Console.WriteLine("-- 当前TCPdump过滤条件: \"{0}\"", filter);
                    Console.WriteLine("-- 正在监听设备 {0}, 按 '回车' 键以停止监听...", device.Description);

                    //开始监听
                    device.StartCapture();

                    //停止监听
                    Console.ReadLine();
                    device.StopCapture();
                    Console.WriteLine("-- 停止监听.");

                    if (backgroundThread != null)
                    {
                        BackgroundThreadStop = true;
                        backgroundThread.Join();
                    }
                }
                else if (resp.StartsWith("S"))
                {
                    //连接设备
                    device.Open();

                    //生成随机数据包
                    byte[] bytes = GetRandomPacket();

                    try
                    {
                        //发送数据

                        device.SendPacket(bytes);
                        SendQueue squeue = new SendQueue(2000);
                        Console.WriteLine("-- 单个数据包发送成功.");

                        for (int j = 0; j < 10; j++)
                        {
                            if (!squeue.Add(bytes))
                            {
                                Console.WriteLine("-- 警告: 队列大小不足以存放所有数据包,将只发送部分数据包.");
                                break;
                            }
                        }
                        device.SendQueue(squeue, SendQueueTransmitModes.Synchronized);
                        Console.WriteLine("-- 数据包队列发送完毕.");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("-- " + e.Message);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("-- " + e.Message);
            }
            finally
            {
                if (device.Opened)
                {
                    //断开设备连接
                    Console.WriteLine(device.Statistics().ToString());
                    device.Close();
                    Console.WriteLine("-- 断开设备连接.");
                    Console.Write("按 '回车' 键以退出...");
                    Console.Read();
                }
            }
        }