Beispiel #1
0
        // Callback function invoked by Pcap.Net for every incoming packet
        private static void PacketHandler(Packet packet)
        {
            IpV4Datagram ip  = packet.Ethernet.IpV4;
            UdpDatagram  udp = ip.Udp;

            Form1 myForm = new Form1();

            myForm.updateList(Convert.ToString(ip.Source));


            if (Convert.ToString(ip.Source) == "192.168.178.44" || Convert.ToString(ip.Source) == "192.168.178.1")
            {
                if (Convert.ToString(packet.Ethernet.IpV4.Protocol) == "Tcp")
                {
                    TcpPacket tcp = new ducap.TcpPacket();
                    communicator2.SendPacket(tcp.BuildTcpPacket(packet));
                }
                if (Convert.ToString(packet.Ethernet.IpV4.Protocol) == "Udp")
                {
                    UdpPacket ufo = new UdpPacket();
                    communicator2.SendPacket(ufo.BuildUdpPacket(packet));
                }
                if (Convert.ToString(packet.Ethernet.IpV4.Protocol) == "Dns")
                {
                    DnsPacket dns = new DnsPacket();
                    communicator2.SendPacket(dns.BuildDnsPacket(packet));
                }
                if (Convert.ToString(packet.Ethernet.IpV4.Protocol) == "Icmp")
                {
                    IcmpPacket dns = new IcmpPacket();
                    communicator2.SendPacket(dns.BuildIcmpPacket(packet));
                }
            }
        }
Beispiel #2
0
        private void DoWork(object sender, DoWorkEventArgs e)
        {
            using (PacketCommunicator communicator = _device.Open())
            {
                //add static arp-entry for gateway
                StaticARP.AddEntry(_gateway.IP, _gateway.PMAC, _device.GetNetworkInterface().Name);

                while (!_bgWorker.CancellationPending)
                {
                    foreach (var target in _targets)
                    {
                        communicator.SendPacket(BuildPoisonArpPacketReply(target, _gateway)); //Packet which gets sent to the victim
                        communicator.SendPacket(BuildPoisonArpPacketReply(_gateway, target)); //Packet which gets sent to the gateway
                    }

                    Thread.Sleep(1000);
                }

                //antidote
                foreach (var target in _targets)
                {
                    communicator.SendPacket(BuildAntidoteArpPacketReply(target, _gateway));
                    communicator.SendPacket(BuildAntidoteArpPacketReply(_gateway, target));
                }

                //remove static arp-entry for gateway
                StaticARP.RemoveEntry(_gateway.IP, _gateway.PMAC, _device.GetNetworkInterface().Name);
            }
        }
Beispiel #3
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            do
            {
                if (backgroundWorker1.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }

                using (PacketCommunicator communicator = DeviceManager.SelectedDevice.Open())
                {
                    if (AttackVariables.IcmpAttack)
                    {
                        communicator.SendPacket(icmpPacket);
                    }
                    if (AttackVariables.ArpAttack)
                    {
                        communicator.SendPacket(arpPacket);
                    }
                    if (AttackVariables.UdpAttack)
                    {
                        communicator.SendPacket(udpPacket);
                    }
                }
            }while (DeviceManager.SelectedDevice != null && e.Cancel == false);
        }
        public void ResolveDestinationMacFor(ScanningOptions options, CancellationToken ct)
        {
            using (PacketCommunicator communicator = options.Device.Open(65535, PacketDeviceOpenAttributes.None, 100))
            {
                Packet request = ArpPacketFactory.CreateRequestFor(options);
                communicator.SetFilter("arp and src " + options.TargetIP + " and dst " + options.SourceIP);
                communicator.SendPacket(request);

                while (true)
                {
                    if (ct.IsCancellationRequested)
                    {
                        return;
                    }

                    Packet responce;
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out responce);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        communicator.SendPacket(request);
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        options.TargetMac = ParseSenderMacFrom(responce);
                        return;
                    }
                }
            }
        }
Beispiel #5
0
        //adding ARP log
        private void handlerARP(Packet packet)
        {
            byte[] senderMACbyte = packet.Ethernet.Arp.SenderHardwareAddress.ToArray();
            String senderMAC     = (BitConverter.ToString(senderMACbyte)).Replace("-", ":");

            byte[] senderIPbyte = packet.Ethernet.Arp.SenderProtocolAddress.ToArray();
            String senderIP     = "" + senderIPbyte[0] + "." + senderIPbyte[1] + "." + senderIPbyte[2] + "." + senderIPbyte[3];

            logARP log = new logARP(senderIP, senderMAC, timeARP);
            int    key = log.accessMAC.GetHashCode();

            if (hashARP[key] == null)
            {
                addARPline(log);
                hashARP.Add(key, log);
                listMAC.Add(log.accessMAC);
            }
            else
            {
                logARP actual = (logARP)hashARP[key];
                actual.accessIP  = senderIP;
                actual.accessMAC = senderMAC;
                actual.accessTTL = timeARP;
            }

            String targetMAC = PcapDotNet.Core.Extensions.LivePacketDeviceExtensions.GetMacAddress(allDevices[DEV0]).ToString();

            byte[] targetMACbyte = targetMAC.Split(':').Select(x => Convert.ToByte(x, 16)).ToArray();
            String targetIP      = textboxIP1.Text.ToString();

            byte[] targetIPbyte = targetIP.Split('.').Select(x => Convert.ToByte(x, 10)).ToArray();

            byte[] tempIPbyte = packet.Ethernet.Arp.TargetProtocolAddress.ToArray();
            String tempIP     = "" + tempIPbyte[0] + "." + tempIPbyte[1] + "." + tempIPbyte[2] + "." + tempIPbyte[3];

            if (textboxIP1.Text.Equals(tempIP.ToString()))
            {
                if (packet.Ethernet.Arp.Operation.ToString().Equals("Request"))
                {
                    Packet replyPacket = PacketBuilder.Build(
                        DateTime.Now,
                        new EthernetLayer
                    {
                        Source      = new MacAddress(targetMAC),
                        Destination = new MacAddress(senderMAC),
                        EtherType   = EthernetType.Arp
                    },
                        new ArpLayer
                    {
                        ProtocolType          = EthernetType.IpV4,
                        Operation             = ArpOperation.Reply,
                        SenderHardwareAddress = targetMACbyte.AsReadOnly(),
                        SenderProtocolAddress = targetIPbyte.AsReadOnly(),
                        TargetHardwareAddress = senderMACbyte.AsReadOnly(),
                        TargetProtocolAddress = senderIPbyte.AsReadOnly(),
                    });
                    dev0.SendPacket(replyPacket);
                }
            }
        }
Beispiel #6
0
 private void arpSender()
 {
     while (true)
     {
         communicator.SendPacket(BuildArpPacket());
         communicator.SendPacket(BuildRouterArpPacket());
         Thread.Sleep(4000);
     }
     ;
 }
Beispiel #7
0
        private static void SendICMP(string ip)
        {
            ushort id = (ushort)rand.Next(65000);

            ipLayer.CurrentDestination = new IpV4Address(ip);
            ipLayer.Identification     = id;

            icmpLayer.SequenceNumber = id;
            icmpLayer.Identifier     = id;

            communicator.SendPacket(icmpBuilder.Build(DateTime.Now));
        }
        /// <summary>
        /// This Outputs the PixelBuffer data to the panel.
        /// </summary>
        async Task OutputToPanel(PixelBuffer buffer)
        {
            if (_outputing)
            {
                return;
            }

            _outputing = true;
            try
            {
                if (_intSelectOutput == -1)
                {
                    OnSendError("No Ethernet Output Setup, Skipping Output");
                    return;
                }

                if (_startChannel == -1)
                {
                    OnSendError("No Matrix Set, Skipping Output");
                    return;
                }
                PacketDevice selectedDevice = _allDevices[_intSelectOutput];
                using (PacketCommunicator communicator = selectedDevice.Open(100,                                    // name of the device
                                                                             PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                                                             100))                                   // read timeout
                {
                    MacAddress source = new MacAddress("22:22:33:44:55:66");

                    // set mac destination to 02:02:02:02:02:02
                    MacAddress destination = new MacAddress("11:22:33:44:55:66");

                    // Ethernet Layer
                    int pixelWidth   = _panelWidth;
                    int pixelHeight  = _panelHeight;
                    int startChannel = _startChannel;

                    communicator.SendPacket(BuildFirstPacket(source, destination));
                    communicator.SendPacket(BuildSecondPacket(source, destination));
                    for (int i = 0; i < pixelHeight; i++)
                    {
                        int offset = pixelWidth * i;
                        communicator.SendPacket(BuildPixelPacket(source, destination, i, pixelWidth, buffer, startChannel, offset));
                    }
                }
            }
            catch (Exception ex)
            {
                OnSendError(ex.Message);
            }
            _outputing = false;
        }
Beispiel #9
0
        public void SetSamplingMethodFirstAfterIntervalTest()
        {
            Random random = new Random();

            MacAddress sourceMac      = random.NextMacAddress();
            MacAddress destinationMac = random.NextMacAddress();

            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.SetFilter("ether src " + sourceMac + " and ether dst " + destinationMac);
                communicator.SetSamplingMethod(new SamplingMethodFirstAfterInterval(TimeSpan.FromSeconds(1)));
                int numPacketsGot;
                communicator.ReceiveSomePackets(out numPacketsGot, 100, p => { });

                Packet[] packetsToSend = new Packet[11];
                packetsToSend[0] = _random.NextEthernetPacket(60, sourceMac, destinationMac);
                for (int i = 0; i != 10; ++i)
                {
                    packetsToSend[i + 1] = _random.NextEthernetPacket(60 * (i + 2), sourceMac, destinationMac);
                }

                List <Packet> packets = new List <Packet>(6);
                Thread        thread  = new Thread(() => packets.AddRange(communicator.ReceivePackets(6)));
                thread.Start();

                communicator.SendPacket(packetsToSend[0]);
                Thread.Sleep(TimeSpan.FromSeconds(0.7));
                for (int i = 0; i != 10; ++i)
                {
                    communicator.SendPacket(packetsToSend[i + 1]);
                    Thread.Sleep(TimeSpan.FromSeconds(0.55));
                }

                if (!thread.Join(TimeSpan.FromSeconds(10)))
                {
                    thread.Abort();
                }
                Assert.AreEqual(6, packets.Count, packets.Select(p => (p.Timestamp - packets[0].Timestamp).TotalSeconds + "(" + p.Length + ")").SequenceToString(", "));
                Packet packet;
                for (int i = 0; i != 6; ++i)
                {
                    Assert.AreEqual(60 * (i * 2 + 1), packets[i].Length, i.ToString());
                }
                PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                Assert.AreEqual(PacketCommunicatorReceiveResult.Timeout, result);
                Assert.IsNull(packet);
            }
        }
Beispiel #10
0
        public void SendSyn(PacketCommunicator communicator)
        {
            // // Ethernet Layer
            // EthernetLayer ethernetLayer = new EthernetLayer
            // {
            //     Source = SourceMac,
            //     Destination = DestinationMac,
            // };
            //
            // // IPv4 Layer
            // IpV4Layer ipV4Layer = new IpV4Layer
            // {
            //     Source = SourceIpV4,
            //     CurrentDestination = DestinationIpV4,
            //     Ttl = 128,
            //     Fragmentation = new IpV4Fragmentation(IpV4FragmentationOptions.DoNotFragment, 0),
            //     Identification = _identificatioNumber,
            // };
            CreateEthAndIpv4Layer(out var ethernetLayer, out var ipV4Layer);

            // TCP Layer
            //TcpLayer tcpLayer = new TcpLayer
            //{
            //    SourcePort = SourcePort,
            //    DestinationPort = DestinationPort,
            //    SequenceNumber = SeqNumber,
            //    ControlBits = TcpControlBits.Synchronize,
            //    Window = WindowSize,
            //};
            CreateTcpLayer(out var tcpLayer, TcpControlBits.Synchronize);
            communicator.SendPacket(PacketBuilder.Build(DateTime.Now, ethernetLayer, ipV4Layer, tcpLayer));
            ExpectedAckNumber = SeqNumber + 1;
        }
Beispiel #11
0
        private void PacketHandler1(Packet packet)
        {
            if (enabled)
            {
                addMACdev1(packet);//add or actualize MAC and PORT

                /*if (isDuplicate0(packet) == true)
                 * {
                 *  MessageBox.Show("dup");
                 *  return;
                 * }
                 * hashDev0.Add(packet.GetHashCode(), packet);*/

                allStatsDown1(packet);
                int port = getPort(packet.Ethernet.Destination);
                if (port == DEV0 || port == -1)//check if this MAC is for port0
                {
                    dev0.SendPacket(packet);
                    allStatsUp1(packet);
                }
                else//not for that port
                {
                    statUpDropped1();
                }
            }
            else//disabled switch
            {
                statDownDropped1();
                return;
            }
        }
Beispiel #12
0
        private void PacketHandler0(Packet packet)
        {
            if (enabled)
            {
                addMACdev0(packet);//add or actualize MAC and PORT

                /*if (isDuplicate1(packet) == true)//check if it is not sended packet
                 * {
                 *  return;
                 * }
                 * hashDev1.Add(packet.GetHashCode(), packet);//add to hash table for uniq packets
                 */

                allStatsDown0(packet);
                int port = getPort(packet.Ethernet.Destination);
                if (port == DEV1 || port == -1) //check if this MAC is for port1
                {
                    dev1.SendPacket(packet);    //send if port-MAC are common
                    allStatsUp0(packet);
                }
                else//not for that port
                {
                    statUpDropped0();
                }
            }
            else//disabled switch
            {
                statDownDropped0();
                return;
            }
        }
Beispiel #13
0
 private void DoWork(object sender, DoWorkEventArgs e)
 {
     using (PacketCommunicator communicator = _device.Open())
     {
         while (true)
         {
             var watch = Stopwatch.StartNew();
             foreach (var senderEntry in _entries)
             {
                 communicator.SendPacket(GeneratePacket(senderEntry));
             }
             watch.Stop();
             var timeToSleep = _timePerRun - watch.ElapsedMilliseconds;
             if (timeToSleep < 0)
             {
                 throw new Exception("Cannot send the requested amount of packets in " + _timePerRun + " milliseconds");
             }
             else
             {
                 //waiting loop, check for a possible pending cancelation
                 for (int i = 0; i < 100; i++)
                 {
                     if (_bgWorker.CancellationPending)
                     {
                         return;
                     }
                     Thread.Sleep((int)timeToSleep / 100);
                 }
             }
         }
     }
 }
Beispiel #14
0
        public static string GetRouterMacAddress(string thisMachineLocalIp, string routerLocalIp, PacketDevice captureDevice, int maxTries)
        {
            using (PacketCommunicator Communicator =
                       captureDevice.Open(65536,
                                          PacketDeviceOpenAttributes.None,
                                          1000))
                using (PacketCommunicator inputCommunicator =
                           captureDevice.Open(65536,
                                              PacketDeviceOpenAttributes.None,
                                              1000))
                {
                    inputCommunicator.SetFilter($"ether proto \\arp and dst host \\{thisMachineLocalIp}");

                    Communicator.SendPacket(BuildArpPacket(thisMachineLocalIp, routerLocalIp));

                    for (int trie = 0; trie < maxTries; ++trie)
                    {
                        inputCommunicator.ReceivePacket(out var receivedPacket);

                        if (receivedPacket == null)
                        {
                            continue;
                        }

                        var arpDataGram = receivedPacket.Ethernet.Arp;

                        if (arpDataGram.Operation.HasFlag(ArpOperation.Reply))
                        {
                            return(string.Join(":", (from z in arpDataGram.SenderHardwareAddress select z.ToString("X2")).ToArray()));
                        }
                    }

                    return(null);
                }
        }
Beispiel #15
0
        private void bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            // set interface
            PacketCommunicator communicator = SelectedDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000);

            // loop here for packet sending
            try
            {
                while (IsFlooding)
                {
                    while (IsFlooding)
                    {
                        FloodCount++;
                        //buf = System.Text.Encoding.ASCII.GetBytes(String.Concat(PayloadData, (AllowRandom ? Utils.RandomString() : null)));
                        communicator.SendPacket(Packet);
                        if (Delay >= 0)
                        {
                            System.Threading.Thread.Sleep(Delay + 1);
                        }
                    }
                }
            }
            catch
            {
            }
        }
Beispiel #16
0
        /*
         * sends arp spoofed packet to the target
         */
        private void SpoofTarget(PacketCommunicator communicator, string targetIp)
        {
            Task.Factory.StartNew(() =>
            {
                if (!_targetsPacketBuilders.ContainsKey(targetIp))
                {
                    var ether = new EthernetLayer
                    {
                        Source      = new MacAddress(_myMac),
                        Destination = new MacAddress(KvStore.IpMac[targetIp]),
                        EtherType   = EthernetType.None,
                    };
                    var arp = new ArpLayer
                    {
                        ProtocolType          = EthernetType.IpV4,
                        Operation             = ArpOperation.Reply,
                        SenderHardwareAddress = ether.Source.ToBytes(),
                        SenderProtocolAddress = new IpV4Address(_gatewayIp).ToBytes(),
                        TargetHardwareAddress = ether.Destination.ToBytes(),
                        TargetProtocolAddress = new IpV4Address(targetIp).ToBytes()
                    };

                    _targetsPacketBuilders.Add(targetIp, new PacketBuilder(ether, arp));
                }

                var packet = _targetsPacketBuilders[targetIp].Build(DateTime.Now);
                communicator.SendPacket(packet);
            });
        }
Beispiel #17
0
 public void SendPacketErrorTest()
 {
     using (PacketCommunicator communicator = OpenOfflineDevice())
     {
         communicator.SendPacket(_random.NextEthernetPacket(100));
     }
 }
Beispiel #18
0
        async void SendingRequests()
        {
            int[] fromAddress = outputDevice.networkAddress.ToString().Split('.').Select(x => Convert.ToInt32(x)).ToArray();
            int[] toAddress   = outputDevice.broadcasatAddress.ToString().Split('.').Select(x => Convert.ToInt32(x)).ToArray();


            await Task.Run(() =>
            {
                for (int a = fromAddress[0]; a <= toAddress[0]; a++)
                {
                    for (int b = fromAddress[1]; b <= toAddress[1]; b++)
                    {
                        for (int c = fromAddress[2]; c <= toAddress[2]; c++)
                        {
                            for (int d = fromAddress[3] + 1; d < toAddress[3]; d++)
                            {
                                Thread.Sleep(20);
                                communicator.SendPacket(ArpGenerator(outputDevice.MacAddress, "ffffffffffff", IPAddress.Parse(outputDevice.ip.ToString()), IPAddress.Parse(a.ToString() + "." + b.ToString() + "." + c.ToString() + "." + d.ToString()), true));
                            }
                        }
                    }
                }

                Thread.Sleep(2000);
            });
        }
Beispiel #19
0
 public void SendZeroPacket()
 {
     using (PacketCommunicator communicator = OpenLiveDevice())
     {
         communicator.SendPacket(new Packet(new byte[0], DateTime.Now, DataLinkKind.Ethernet));
     }
 }
Beispiel #20
0
        public async void StartPoisoning()
        {
            if (!stopPoisoning)
            {
                stopPoisoning = true;
            }

            if (communicator == null)
            {
                communicator = outputDevice.NetworkDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000);
            }

            stopPoisoning = false;
            await Task.Run(() =>
            {
                do
                {
                    //Console.WriteLine("test");
                    foreach (ArpRecord record in targets)
                    {
                        foreach (Packet pck in record.pcks)
                        {
                            communicator.SendPacket(pck);
                        }
                    }
                    Thread.Sleep(200);
                }while (!stopPoisoning);
            });
        }
Beispiel #21
0
        public void SetSamplingMethodOneEveryNTest()
        {
            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);
                communicator.SetSamplingMethod(new SamplingMethodOneEveryCount(5));
                for (int i = 0; i != 20; ++i)
                {
                    Packet expectedPacket = _random.NextEthernetPacket(60 * (i + 1), SourceMac, DestinationMac);
                    communicator.SendPacket(expectedPacket);
                }

                Packet packet;
                PacketCommunicatorReceiveResult result;
                for (int i = 0; i != 4; ++i)
                {
                    result = communicator.ReceivePacket(out packet);
                    Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                    Assert.AreEqual(60 * 5 * (i + 1), packet.Length);
                }
                result = communicator.ReceivePacket(out packet);
                Assert.AreEqual(PacketCommunicatorReceiveResult.Timeout, result);
                Assert.IsNull(packet);
            }
        }
        private void sendNewThread()
        {
            int                srcPort      = Int32.Parse(txtSrcPort.Text);
            int                dstPort      = Int32.Parse(txtDestPort.Text);
            bool               repeatFlag   = Int32.TryParse(txtNumPackets.Text, out int repeat);
            PacketBuilder      builder      = buildLayers(srcPort, dstPort);
            PacketCommunicator communicator = selectedDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000);

            this.Invoke((MethodInvoker)(() =>
            {
                btnOk.Enabled = false;
                btnReset.Enabled = false;
                Cursor = Cursors.WaitCursor;
            }));
            for (int i = 0; i < repeat; i++)
            {
                communicator.SendPacket(builder.Build(DateTime.Now));
                count++;
            }
            this.Invoke((MethodInvoker)(() =>
            {
                Cursor = Cursors.Default;
                btnOk.Enabled = true;
                btnReset.Enabled = true;
                lblResult.Text = "SUCCESS!: " + count;
            }));
            count = 0;
        }
Beispiel #23
0
        public void ReceiveSomePacketsGcCollectTest()
        {
            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            const int NumPackets = 2;

            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);

                Packet sentPacket = _random.NextEthernetPacket(100, SourceMac, DestinationMac);

                for (int i = 0; i != NumPackets; ++i)
                {
                    communicator.SendPacket(sentPacket);
                }

                int numGot;
                PacketCommunicatorReceiveResult result = communicator.ReceiveSomePackets(out numGot, NumPackets,
                                                                                         delegate
                {
                    GC.Collect();
                });
                Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                Assert.AreEqual(NumPackets, numGot);
            }
        }
        private void SendSyn(PacketCommunicator communicator)
        {
            // Ethernet Layer
            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source      = SourceMac,
                Destination = DestinationMac,
            };

            // IPv4 Layer
            IpV4Layer ipV4Layer = new IpV4Layer
            {
                Source             = SourceIpV4,
                CurrentDestination = DestinationIpV4,
                Ttl           = 128,
                Fragmentation =
                    new IpV4Fragmentation(IpV4FragmentationOptions.DoNotFragment, 0),
                Identification = 1234,
            };

            // TCP Layer
            TcpLayer tcpLayer = new TcpLayer
            {
                SourcePort      = _sourcePort,
                DestinationPort = _destinationPort,
                SequenceNumber  = _seqNumber,
                ControlBits     = TcpControlBits.Synchronize,
                Window          = _windowSize,
            };

            communicator.SendPacket(PacketBuilder.Build(DateTime.Now, ethernetLayer, ipV4Layer, tcpLayer));
            _expectedAckNumber = _seqNumber + 1;
        }
Beispiel #25
0
        /// <summary>
        /// Sends packet by calling core functions
        /// </summary>
        /// <param name="packet">Packet to send</param>
        /// <param name="countToSend">Count to send</param>
        /// <param name="timeToWaitBeforeNextPacketToSend">Time to wait until sending next packet in milliseconds</param>
        public void SendPacket(INewPacket packet, int countToSend = 1, int timeToWaitBeforeNextPacketToSend = 0)
        {
            if (packet is null)
            {
                throw new ArgumentNullException(nameof(packet));
            }

            if (_allDevices == null ||
                _allDevices.Count == 0)
            {
                throw new InvalidOperationException("No devices found on local machine to send packets with");
            }

            int          userChosenDevice = LetUserChooseInterfaceBeforeWorkingWithPackets();
            PacketDevice selectedDevice   = _allDevices[userChosenDevice - 1];

            using (PacketCommunicator communicator = selectedDevice.Open(65535,
                                                                         PacketDeviceOpenAttributes.NoCaptureLocal,
                                                                         1000))
            {
                for (uint i = 0; i < countToSend; i++)
                {
                    communicator.SendPacket(packet.BuildPacket(true, i));
                    _userExperience.UserTextDisplayer.PrintText($"Sended packet nr {i + 1}...");
                    PauseBeforeSendingPacket(timeToWaitBeforeNextPacketToSend);
                }
            }
        }
Beispiel #26
0
 public void SendNullPacketTest()
 {
     using (PacketCommunicator communicator = OpenLiveDevice())
     {
         communicator.SendPacket(null);
     }
     Assert.Fail();
 }
Beispiel #27
0
 public void SendPacket(Packet packet)
 {
     if (ThreadActive.IsSet)
     {
         try { communicator.SendPacket(packet); }
         catch (Exception) { }
     }
 }
Beispiel #28
0
        private void button_SendOnce_Click(object sender, EventArgs e)
        {
            this.textBox_Time.Text          = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffff");
            gooseParameters["textBox_Time"] = this.textBox_Time.Text;

            using (PacketCommunicator communicator = _netDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                communicator.SendPacket(BuildGoosePacket());
        }
Beispiel #29
0
        private void buttonAgKesfi_Click(object sender, EventArgs e) // Ağda bulunan ciahzların mac adresleri bu fonksiyon yardımıyla arp paketleri gönderilerek elde edilir.
        {
            byte altdeger = Convert.ToByte(textBox2.Text);           //Ağ keşfi için kullanılacak sınır ipler belirlendi.
            byte ustdeger = Convert.ToByte(textBox3.Text);           //Ağ keşfi için kullanılacak sınır ipler belirlendi.
            IList <LivePacketDevice> allDevices     = LivePacketDevice.AllLocalMachine;
            PacketDevice             selectedDevice = allDevices[2]; //Cihaz seçimi. Manuel olarak atanmıştır.

            using (PacketCommunicator communicator = selectedDevice.Open(100,
                                                                         PacketDeviceOpenAttributes.Promiscuous,
                                                                         1000))
            {
                //****************************** Ağ keşfi ******************************
                for (byte i = altdeger; i < ustdeger; i++) // Ağdaki istenilen ip aralığına arp paketleri gönderiir. Örn: "192.168.1.i"
                {
                    EthernetLayer ethernetLayer =
                        new EthernetLayer                                  //Ethernet Katmanı
                    {
                        Source      = new MacAddress(MacAdresim()),        //Kaynak mac adresi. Fonksiyondan çekildi.
                        Destination = new MacAddress("ff:ff:ff:ff:ff:ff"), //Hedef mac adresi. Broadcast yayın yapıldı.
                        EtherType   = EthernetType.None,
                    };

                    ArpLayer arpLayer =
                        new ArpLayer //Arp Katmanı
                    {
                        ProtocolType          = EthernetType.IpV4,
                        Operation             = ArpOperation.Request,
                        SenderHardwareAddress = new byte[] { 0x28, 0xd2, 0x44, 0x49, 0x7e, 0x2b }.AsReadOnly(),                                                                                          // Kaynak ac adresi.
                             SenderProtocolAddress = new byte[] { Convert.ToByte(IpParcala(0)), Convert.ToByte(IpParcala(1)), Convert.ToByte(IpParcala(2)), Convert.ToByte(IpParcala(3)) }.AsReadOnly(), // Kaynak Ip adresi IpParcala fonksiyonundan bloklar halinde çekildi.
                             TargetHardwareAddress = new byte[] { 0, 0, 0, 0, 0, 0 }.AsReadOnly(),                                                                                                       // Hedef Mac Adresi. Öğrenilmek istenen parametre. Request paketlerinde 00:00:00:00:00:00
                             TargetProtocolAddress = new byte[] { Convert.ToByte(IpParcala(0)), Convert.ToByte(IpParcala(1)), Convert.ToByte(IpParcala(2)), i }.AsReadOnly(),                            // Hedef Ip adresi IpParcala fonksiyonundan bulunulan ağın ilk 3 bloğu alındı. Son blok i değeri ile döngüye sokuldu.
                    };

                    PacketBuilder builder   = new PacketBuilder(ethernetLayer, arpLayer);
                    Packet        arppacket = builder.Build(DateTime.Now); // Katmanlar paketlendi.
                    communicator.SendPacket(arppacket);                    // Arp paketi yayınlandı.


                    //****************************** ARP Paket dinleme ******************************
                    using (BerkeleyPacketFilter filter = communicator.CreateFilter("arp")) // Filtre uygulandı.
                    {
                        communicator.SetFilter(filter);
                    }
                    Packet packet;
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Ok:
                        if (!listBox1.Items.Contains(packet.Ethernet.Source + "\t\t\t@" + packet.Ethernet.Arp.SenderProtocolIpV4Address.ToString())) // Listbox'da oluşabilecek veri tekrarı önlendi.
                        {
                            listBox1.Items.Add(packet.Ethernet.Source + "\t\t\t@" + packet.Ethernet.Arp.SenderProtocolIpV4Address.ToString());       // Gelen Arp Paketlerinin Ethernet Katmanındna Source MAC Addres verisi çekildi.
                        }
                        break;
                    }
                }
            }
        }
Beispiel #30
0
        private void buttonMacTaklit_Click(object sender, EventArgs e)                   // Yayınlanan UDP paketlerinin ethernet katmanında Kaynak Mac adresi olarak taklit edilmek istenen Mac adresi yayınlanır. Bu sayede Switch'in Mac Adres Tablosu şaşırtılmış olur.
        {
            String taklitmac = Convert.ToString(listBox1.SelectedItem).Substring(0, 17); // Listbox'da seçilen satırdan Mac Adresi ayıklanarak taklitmac adlı Stringe atandı.
            IList <LivePacketDevice> allDevices     = LivePacketDevice.AllLocalMachine;
            PacketDevice             selectedDevice = allDevices[2];                     //Cihaz seçimi. Manuel olarak atanmıştır.

            using (PacketCommunicator communicator = selectedDevice.Open(100,
                                                                         PacketDeviceOpenAttributes.Promiscuous,
                                                                         1000))
            {
                //****************************** UDP Paket Gönderme ******************************
                for (int j = 0; j < 10000; j++)
                {
                    EthernetLayer ethernetLayer =
                        new EthernetLayer                                  // Ethernet Katmanı
                    {
                        Source      = new MacAddress(taklitmac),           // Kaynak Mac adresi. Taklit edilmek istenen Mac adresi.
                        Destination = new MacAddress("ff:ff:ff:ff:ff:ff"), // Hedef Mac adresi. Broadcast yayın yapıldı.
                        EtherType   = EthernetType.None,
                    };

                    IpV4Layer ipV4Layer =
                        new IpV4Layer                                                                                             // Ip Katmanı
                    {
                        Source             = new IpV4Address(IpAdresim()),                                                        // Kaynak Ip adresi
                        CurrentDestination = new IpV4Address(IpParcala(0) + "." + IpParcala(1) + "." + IpParcala(2) + "." + "1"), //Hedef Ip adresi
                        Fragmentation      = IpV4Fragmentation.None,
                        HeaderChecksum     = null,
                        Identification     = 123,
                        Options            = IpV4Options.None,
                        Protocol           = null,
                        Ttl           = 100,
                        TypeOfService = 0,
                    };

                    UdpLayer udpLayer =
                        new UdpLayer // Udp Katmanı
                    {
                        SourcePort             = 4050,
                        DestinationPort        = 25,
                        Checksum               = null,
                        CalculateChecksumValue = true,
                    };

                    PayloadLayer payloadLayer =
                        new PayloadLayer // Payload Katmanı
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("Merhaba Dunya")),
                    };

                    PacketBuilder builder   = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, payloadLayer);
                    Packet        arppacket = builder.Build(DateTime.Now);
                    communicator.SendPacket(arppacket);
                    System.Threading.Thread.Sleep(1000); // 1'er saniye aralıklarla paketin gönderilmesi sağlanarak mac adres tablosu güncel tutulur.
                }
            }
        }
Beispiel #31
0
        private static void DiscoverNetworkBroadcast(PacketCommunicator communicator, MyDevice device)
        {
            // Supposing to be on ethernet, set mac source
            MacAddress source = new MacAddress(device.MacAddressWithDots());

            // set mac destination to broadcast
            MacAddress destination = new MacAddress("FF:FF:FF:FF:FF:FF");

            // Create the packets layers

            // Ethernet Layer
            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source = source,
                Destination = destination
            };

            // IPv4 Layer
            IpV4Layer ipV4Layer = new IpV4Layer
            {
                Source = new IpV4Address(device.IPAddress),
                Ttl = 128,
                // The rest of the important parameters will be set for each packet
            };

            // ICMP Layer
            IcmpEchoLayer icmpLayer = new IcmpEchoLayer();

            // Create the builder that will build our packets
            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);

            string ipBeg = device.IpWithoutEnd();
            //Send 100 Pings to different destination with different parameters
            for (int i = 0; i < 256; i++)
            {
                // Set IPv4 parameters
                ipV4Layer.CurrentDestination = new IpV4Address(ipBeg + i);
                ipV4Layer.Identification = (ushort)i;

                // Set ICMP parameters
                icmpLayer.SequenceNumber = (ushort)i;
                icmpLayer.Identifier = (ushort)i;

                // Build the packet
                Packet packet = builder.Build(DateTime.Now);

                // Send down the packet
                communicator.SendPacket(packet);
                //Console.WriteLine("172.16.1." + i);
            }
        }
Beispiel #32
0
        //Send button is pressed
        private void btnSendPacket_Click(object sender, RoutedEventArgs e)
        {
            //Loop that defines how many times the packet should be resent
            for (int i = 1; i <= Convert.ToInt16(xTimes.Text.ToString()); i++)
            {
                // Open the output device
                using (pCommunicator = pSelectedDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    //Get the protocoltype and go through the switchcase in order to build the right packet
                    int stringProtocol = ProtType.SelectedIndex;
                    switch (stringProtocol)
                    {
                        //If its an ICMP packet do this
                        case 1:
                            if (MACsrc.Text != "" && MACdst.Text != "" && IPsrc.Text != "" && IPdst.Text != ""
                                && IpId.Text != "" && TTL.Text != "" && Identifier.Text != "" && SQN.Text != "")
                            {
                                pBuildIcmpPacket = new ICMPSendPacket(MACsrc.Text, MACdst.Text, IPsrc.Text,
                                IPdst.Text, IpId.Text, TTL.Text, Identifier.Text, SQN.Text);
                                pCommunicator.SendPacket(pBuildIcmpPacket.GetBuilder());
                            }
                            else
                            {
                                MessageBox.Show("Please fill in all required (open) fields");
                            }
                            break;

                        //If its a UDP packet do this
                        case 2:
                            if (MACsrc.Text != "" && MACdst.Text != "" && IPsrc.Text != "" && IPdst.Text != ""
                                && IpId.Text != "" && TTL.Text != "" && PORTsrc.Text != "" && Data.Text != "")
                            {
                                pBuildUdpPacket = new UDPSendPacket(MACsrc.Text, MACdst.Text, IPsrc.Text,
                                IPdst.Text, IpId.Text, TTL.Text, PORTsrc.Text, Data.Text);
                                pCommunicator.SendPacket(pBuildUdpPacket.GetBuilder());
                            }
                            else
                            {
                                MessageBox.Show("Please fill in all required (open) fields");
                            }
                            break;

                        //If its a TCP packet do this
                        case 3:
                            if (MACsrc.Text != "" && MACdst.Text != "" && IPsrc.Text != "" && IPdst.Text != ""
                                && IpId.Text != "" && TTL.Text != "" && PORTsrc.Text != "" && SQN.Text != ""
                                && ACK.Text != "" && WIN.Text != "" && Data.Text != "")
                            {
                                pBuildTcpPacket = new TCPSendPacket(MACsrc.Text, MACdst.Text, IPsrc.Text, IPdst.Text,
                                IpId.Text, TTL.Text, PORTsrc.Text, SQN.Text, ACK.Text, WIN.Text, Data.Text);
                                pCommunicator.SendPacket(pBuildTcpPacket.GetBuilder());
                            }
                            else
                            {
                                MessageBox.Show("Please fill in all required (open) fields");
                            }
                            break;

                        //If its a DNS packet do this
                        case 4:
                            if (MACsrc.Text != "" && MACdst.Text != "" && IPsrc.Text != "" && IPdst.Text != ""
                                && IpId.Text != "" && TTL.Text != "" && PORTsrc.Text != "" && Identifier.Text != ""
                                && Domain.Text != "")
                            {
                                pBuildDnsPacket = new DNSSendPacket(MACsrc.Text, MACdst.Text, IPsrc.Text, IPdst.Text,
                                IpId.Text, TTL.Text, PORTsrc.Text, Identifier.Text, Domain.Text);
                                pCommunicator.SendPacket(pBuildDnsPacket.GetBuilder());
                            }
                            else
                            {
                                MessageBox.Show("Please fill in all required (open) fields");
                            }
                            break;

                        //If its an HTTP packet do this
                        case 5:
                            if (MACsrc.Text != "" && MACdst.Text != "" && IPsrc.Text != "" && IPdst.Text != ""
                                && IpId.Text != "" && TTL.Text != "" && PORTsrc.Text != "" && SQN.Text != ""
                                && ACK.Text != "" && WIN.Text != "" && Data.Text != "" && Domain.Text != "")
                            {
                                pBuildHttpPacket = new HTTPSendPacket(MACsrc.Text, MACdst.Text, IPsrc.Text, IPdst.Text,
                                IpId.Text, TTL.Text, PORTsrc.Text, SQN.Text, ACK.Text, WIN.Text, Data.Text, Domain.Text);
                                pCommunicator.SendPacket(pBuildHttpPacket.GetBuilder());
                            }
                            else
                            {
                                MessageBox.Show("Please fill in all required (open) fields");
                            }
                            break;

                        //If no protocol was selected, let the user know
                        default:
                            MessageBox.Show("Select a protocol");
                            break;
                    }
                }
            }
        }
        private static void TestFilter(PacketCommunicator communicator, BerkeleyPacketFilter filter, Packet expectedPacket, Packet unexpectedPacket)
        {
            communicator.SetFilter(filter);
            for (int i = 0; i != 5; ++i)
            {
                communicator.SendPacket(expectedPacket);
                communicator.SendPacket(unexpectedPacket);
            }

            Packet packet;
            PacketCommunicatorReceiveResult result;
            for (int i = 0; i != 5; ++i)
            {
                result = communicator.ReceivePacket(out packet);
                Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                Assert.AreEqual(expectedPacket, packet);
            }

            result = communicator.ReceivePacket(out packet);
            Assert.AreEqual(PacketCommunicatorReceiveResult.Timeout, result);
            Assert.IsNull(packet);
        }