Exemple #1
0
        public DhcpPacket Deserialize(byte[] data)
        {
            int        packetLength = data.Length;
            DhcpPacket result       = new DhcpPacket();

            using (MemoryStream stm = new MemoryStream(data))
                using (BinaryReader rdr = new BinaryReader(stm))
                {
                    result.Op      = rdr.ReadByte();
                    result.HType   = rdr.ReadByte();
                    result.HLen    = rdr.ReadByte();
                    result.Hops    = rdr.ReadByte();
                    result.XID     = rdr.ReadBytes(4);
                    result.Secs    = rdr.ReadBytes(2);
                    result.Flags   = rdr.ReadBytes(2);
                    result.CIAddr  = rdr.ReadBytes(4);
                    result.YIAddr  = rdr.ReadBytes(4);
                    result.SIAddr  = rdr.ReadBytes(4);
                    result.GIAddr  = rdr.ReadBytes(4);
                    result.CHAddr  = rdr.ReadBytes(16);
                    result.SName   = rdr.ReadBytes(64);
                    result.File    = rdr.ReadBytes(128);
                    result.Cookie  = rdr.ReadBytes(4);
                    result.Options = rdr.ReadBytes(packetLength - OPTION_OFFSET);
                }


            return(result);
        }
Exemple #2
0
        public void DiscoveryOptions_Expect_MessageTypeOfDiscover()
        {
            DhcpPacket discoveryPacket = DhcpFakes.FakeDhcpDiscoverPacket();
            var        sut             = _messagerSerializer.ToMessage(discoveryPacket);

            Assert.Equal(DhcpMessageType.Discover, sut.DhcpMessageType);
        }
Exemple #3
0
        private void SendNotification(DhcpPacket packet)
        {
            var factory = new ConnectionFactory()
            {
                HostName = string.IsNullOrEmpty(configuration.MessageQueueHost) ?
                           "localhost" :
                           configuration.MessageQueueHost,
                UserName = configuration.MessageQueueUserName,
                Password = configuration.MessageQueuePassword
            };

            using (var connection = factory.CreateConnection()){
                using (var channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare(exchange: configuration.MessageQueueExchangeName, type: "fanout");

                    string message = BuildMessage(packet);
                    var    body    = Encoding.UTF8.GetBytes(message);

                    channel.BasicPublish(exchange: string.IsNullOrEmpty(configuration.MessageQueueExchangeName) ? "": configuration.MessageQueueExchangeName,
                                         routingKey: "",
                                         basicProperties: null,
                                         body: body);
                }
            }
        }
Exemple #4
0
        public void DiscoveryOptions_Expect_CorrectHostName()
        {
            DhcpPacket discoveryPacket = DhcpFakes.FakeDhcpDiscoverPacket();
            var        sut             = _messagerSerializer.ToMessage(discoveryPacket);

            Assert.Equal("SpeedwayR-11-7A-3C", sut.HostName);
        }
Exemple #5
0
        public void ShouldParseDhcpDiscover()
        {
            using (var stream = new FileStream(pathToBinFiles + "dhcpdiscover.bin", FileMode.Open, FileAccess.Read))
                using (var reader = new BinaryReader(stream))
                {
                    var        bytes  = reader.ReadBytes((int)stream.Length);
                    DhcpPacket packet = new DhcpPacket(bytes);
                    Assert.Equal(1, packet.BootPMessageType);
                    Assert.Equal(HardwareType.Ethernet, packet.HType);
                    Assert.Equal(6, packet.HLen);
                    Assert.Equal(0, packet.Hops);
                    Assert.Equal(0x9d2b3df6, packet.XId);
                    Assert.Equal(0, packet.Secs);
                    Assert.Equal(0x8000, packet.BootPFlags);
                    Assert.Equal(IPAddress.Any, packet.CIAddr);
                    Assert.Equal(IPAddress.Any, packet.YIAddr);
                    Assert.Equal(IPAddress.Any, packet.GIAddr);
                    Assert.Equal(IPAddress.Any, packet.SIAddr);

                    var physAddressExpected = new byte[] { 0xf4, 0xf5, 0xa5, 0x83, 0x2d, 0x16 };
                    var physAddressActual   = packet.CHAddrTruncated;

                    Assert.Equal(new List <byte>(physAddressExpected), new List <byte>(physAddressActual.GetAddressBytes()));
                    Assert.Equal(string.Empty, packet.ServerName);
                    Assert.Equal(string.Empty, packet.BootFileName);

                    Assert.True(packet.IsActualDhcp);

                    Assert.Equal(5, packet.Options.Count);
                    Assert.Equal(DhcpMessageType.Discover, packet.GetDhcpMessageType());
                }
        }
Exemple #6
0
        private static byte[] buildDhcpPayload()
        {
            // Create optional payload bytes that can be added to the main payload.
            DhcpOption dhcpServerIdentifierOption = new DhcpOption()
            {
                optionId     = dhcpOptionIds.DhcpMessageType,
                optionLength = new byte[] { 0x01 },
                optionValue  = new byte[] { 0x03 },
            };

            DhcpOption dhcpRequestedIpAddressOption = new DhcpOption()
            {
                optionId     = dhcpOptionIds.RequestedIpAddress,
                optionLength = new byte[] { 0x04 },
                optionValue  = IPAddress.Parse("192.168.178.101").GetAddressBytes(),
            };

            // Create the main payload of the dhcp-packet and add the options to it.
            DhcpPacket dhcpDiscoveryPacket = new DhcpPacket()
            {
                transactionID = new byte[] { 0x00, 0x00, 0x00, 0x00 },
                dhcpOptions   = dhcpServerIdentifierOption.buildDhcpOption().Concat(dhcpRequestedIpAddressOption.buildDhcpOption()).ToArray(),
            };

            return(dhcpDiscoveryPacket.buildPacket());
        }
Exemple #7
0
        public void Serialize(BinaryWriter writer, DhcpPacket packet)
        {
            writer.Write(packet.Op);
            writer.Write(packet.HType);
            writer.Write(packet.HLen);
            writer.Write(packet.Hops);
            writer.Write(packet.XID);

            byte[] secsBytes = new byte[2];
            packet.Secs.CopyTo(secsBytes, 0);
            writer.Write(secsBytes);

            byte[] flagBytes = new byte[2];
            packet.Flags.CopyTo(flagBytes, 0);
            writer.Write(flagBytes);

            writer.Write(packet.CIAddr);
            writer.Write(packet.YIAddr);
            writer.Write(packet.SIAddr);
            writer.Write(packet.GIAddr);
            writer.Write(packet.CHAddr);

            byte[] snameBytes = new byte[64];
            writer.Write(snameBytes);

            byte[] fileBytes = new byte[128];
            writer.Write(fileBytes);

            writer.Write(GetDhcpMagicNumber());
            writer.Write(packet.Options);
        }
Exemple #8
0
        /// <summary>This is used to process a dhcp packet on the node side, that
        /// includes placing data such as the local Brunet Address, Ipop Namespace,
        /// and other optional parameters in our request to the dhcp server.  When
        /// receiving the results, if it is successful, the results are written to
        /// the TAP device.</summary>
        /// <param name="ipp"> The IPPacket that contains the Dhcp Request</param>
        /// <param name="dhcp_params"> an object containing any extra parameters for
        /// the dhcp server</param>
        /// <returns> true on if dhcp is supported.</returns>
        protected virtual bool HandleDhcp(IPPacket ipp)
        {
            UdpPacket  udpp        = new UdpPacket(ipp.Payload);
            DhcpPacket dhcp_packet = new DhcpPacket(udpp.Payload);
            MemBlock   ether_addr  = dhcp_packet.chaddr;

            if (_dhcp_config == null)
            {
                return(true);
            }

            DhcpServer dhcp_server = CheckOutDhcpServer(ether_addr);

            if (dhcp_server == null)
            {
                return(true);
            }

            MemBlock last_ip = null;

            _ether_to_ip.TryGetValue(ether_addr, out last_ip);
            byte[] last_ipb = (last_ip == null) ? null : (byte[])last_ip;

            WaitCallback wcb = delegate(object o) {
                ProtocolLog.WriteIf(IpopLog.DhcpLog, String.Format(
                                        "Attempting Dhcp for: {0}", Utils.MemBlockToString(ether_addr, '.')));

                DhcpPacket rpacket = null;
                try {
                    rpacket = dhcp_server.ProcessPacket(dhcp_packet,
                                                        AppNode.Node.Address.ToString(), last_ipb);
                } catch (Exception e) {
                    ProtocolLog.WriteIf(IpopLog.DhcpLog, e.Message);
                    CheckInDhcpServer(dhcp_server);
                    return;
                }

                /* Check our allocation to see if we're getting a new address */
                MemBlock new_addr = rpacket.yiaddr;
                UpdateMapping(ether_addr, new_addr);

                MemBlock destination_ip = ipp.SourceIP;
                if (destination_ip.Equals(IPPacket.ZeroAddress))
                {
                    destination_ip = IPPacket.BroadcastAddress;
                }

                UdpPacket res_udpp = new UdpPacket(_dhcp_server_port, _dhcp_client_port, rpacket.Packet);
                IPPacket  res_ipp  = new IPPacket(IPPacket.Protocols.Udp, rpacket.siaddr,
                                                  destination_ip, res_udpp.ICPacket);
                EthernetPacket res_ep = new EthernetPacket(ether_addr, EthernetPacket.UnicastAddress,
                                                           EthernetPacket.Types.IP, res_ipp.ICPacket);
                Ethernet.Send(res_ep.ICPacket);
                CheckInDhcpServer(dhcp_server);
            };

            ThreadPool.QueueUserWorkItem(wcb);
            return(true);
        }
Exemple #9
0
        public void DiscoveryOptions_Expect_CorrectClientHAddr()
        {
            DhcpPacket      discoveryPacket = DhcpFakes.FakeDhcpDiscoverPacket();
            var             sut             = _messagerSerializer.ToMessage(discoveryPacket);
            PhysicalAddress expeced         = new PhysicalAddress(new byte[] { 0, 22, 37, 17, 122, 60 });

            Assert.Equal(expeced, sut.ClientHardwareAddress);
        }
Exemple #10
0
        public void DiscoveryCIAddr_Expect_CorrectClientIP()
        {
            DhcpPacket discoveryPacket = DhcpFakes.FakeDhcpDiscoverPacket();

            discoveryPacket.CIAddr = new byte[] { 0, 0, 0, 0 };
            var sut = _messagerSerializer.ToMessage(discoveryPacket);

            Assert.Equal("0.0.0.0", sut.ClientIPAddress.ToString());
        }
 public static byte[] GetBytes(this DhcpPacket packet, IDhcpPacketSerializer serializer)
 {
     using (MemoryStream ms = new MemoryStream())
         using (BinaryWriter br = new BinaryWriter(ms))
         {
             serializer.Serialize(br, packet);
             return(ms.ToArray());
         }
 }
Exemple #12
0
        public void DiscoveryOptions_Expect_CorrectXID()
        {
            DhcpPacket discoveryPacket = DhcpFakes.FakeDhcpDiscoverPacket();

            discoveryPacket.XID = new byte[] { 0x19, 0xe1, 0x79, 0x50 };
            var sut         = _messagerSerializer.ToMessage(discoveryPacket);
            var expectedHex = "19e17950";

            Assert.Equal(expectedHex, sut.TransactionId.ToString("x4"));
        }
Exemple #13
0
        /// <summary></summary>
        public DhcpPacket ProcessPacket(DhcpPacket packet, string unique_id,
                                        byte[] last_ip, params object[] dhcp_params)
        {
            DhcpPacket.MessageTypes message_type = (DhcpPacket.MessageTypes)
                                                   packet.Options[DhcpPacket.OptionTypes.MESSAGE_TYPE][0];

            byte[] requested_ip = last_ip;
            bool   renew        = false;

            if (message_type == DhcpPacket.MessageTypes.DISCOVER)
            {
                message_type = DhcpPacket.MessageTypes.OFFER;
            }
            else if (message_type == DhcpPacket.MessageTypes.REQUEST)
            {
                if (packet.Options.ContainsKey(DhcpPacket.OptionTypes.REQUESTED_IP))
                {
                    requested_ip = packet.Options[DhcpPacket.OptionTypes.REQUESTED_IP];
                }
                else if (!packet.ciaddr.Equals(IPPacket.ZeroAddress))
                {
                    requested_ip = packet.ciaddr;
                }
                renew        = true;
                message_type = DhcpPacket.MessageTypes.ACK;
            }
            else
            {
                throw new Exception("Unsupported message type!");
            }

            byte[] reply_ip = RequestLease(requested_ip, renew, unique_id, dhcp_params);

            Dictionary <DhcpPacket.OptionTypes, MemBlock> options =
                new Dictionary <DhcpPacket.OptionTypes, MemBlock>();

            if (OSDependent.OSVersion == OSDependent.OS.Windows)
            {
                options[DhcpPacket.OptionTypes.DOMAIN_NAME] = Encoding.UTF8.GetBytes(Dns.DomainName);
                //The following option is needed for dhcp to "succeed" in Vista, but they break Linux
                //options[DhcpPacket.OptionTypes.ROUTER] = reply.ip;
                options[DhcpPacket.OptionTypes.DOMAIN_NAME_SERVER] = MemBlock.Reference(ServerIP);
            }
            options[DhcpPacket.OptionTypes.SUBNET_MASK]  = MemBlock.Reference(Netmask);
            options[DhcpPacket.OptionTypes.LEASE_TIME]   = _lease_time;
            options[DhcpPacket.OptionTypes.MTU]          = _mtu;
            options[DhcpPacket.OptionTypes.SERVER_ID]    = MemBlock.Reference(ServerIP);
            options[DhcpPacket.OptionTypes.MESSAGE_TYPE] = MemBlock.Reference(new byte[] { (byte)message_type });
            DhcpPacket rpacket = new DhcpPacket(2, packet.xid, packet.ciaddr, reply_ip,
                                                ServerIP, packet.chaddr, options);

            return(rpacket);
        }
        private DhcpPacket SetClientHardwareAddressFields(DhcpPacket packet, DhcpMessage message)
        {
            var addressBytes  = message.ClientHardwareAddress.GetAddressBytes();
            var addressLength = addressBytes.Length;

            byte[] chAddressArray = new byte[16];

            addressBytes.CopyTo(chAddressArray, 0);

            packet.CHAddr = chAddressArray;
            packet.HLen   = (byte)addressLength;

            return(packet);
        }
Exemple #15
0
        public static DhcpPacket FakeDhcpDiscoverPacket()
        {
            DhcpPacket packet = new DhcpPacket
            {
                CHAddr = new byte[] { 0, 22, 37, 17, 122, 60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
                Op     = 0x01,
                HType  = 0x01,
                HLen   = 0x06,
                Hops   = 0x00,
                XID    = new byte[] { 137, 168, 215, 101 },
                Secs   = new byte[] { 0, 0 },
                Flags  = new byte[] { 0, 0 },
                CIAddr = new byte[] { 0, 0, 0, 0 },
                YIAddr = new byte[] { 0, 0, 0, 0 },
                SIAddr = new byte[] { 0, 0, 0, 0 },
                GIAddr = new byte[] { 0, 0, 0, 0 },
                File   = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                      0, 0, 0 },
                Cookie  = new byte[] { 99, 130, 83, 99 },
                Options = new byte[] { 53, 1, 1, 12, 18, 83, 112, 101, 101, 100, 119, 97, 121, 82, 45, 49, 49, 45, 55,
                                       65, 45, 51, 67, 55, 8, 12, 1, 28, 3, 15, 6, 42, 2, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
            };

            return(packet);
        }
Exemple #16
0
        private DhcpMessage ParseRequest(DhcpData dhcpData, IDhcpPacketSerializer pSerializer, IDhcpMessageSerializer mSerializer)
        {
            DhcpPacket  packet = pSerializer.Deserialize(dhcpData.MessageBuffer);
            DhcpMessage message;

            try
            {
                message = mSerializer.ToMessage(packet);
            }
            catch (Exception ex)
            {
                Log.Error($"Error Parsing Dhcp Message {ex.Message}");
                throw;
            }

            return(message);
        }
Exemple #17
0
        private string BuildMessage(DhcpPacket packet)
        {
            var deviceName = packet.GetHostName();
            var ip         = packet.GetClientIp();
            var mac        = packet.GetClientMac();

            var message = new
            {
                DeviceName       = deviceName,
                DeviceIpAddress  = ip == null ? string.Empty: ip.ToString(),
                DeviceMacAddress = mac == null ? string.Empty : mac.ToString(),
                TimeStamp        = DateTime.UtcNow,
                DetectedBy       = configuration.SensorName
            };

            return(JsonConvert.SerializeObject(message));
        }
Exemple #18
0
        private static byte[] buildDhcpPayload()
        {
            // Create optional payload bytes that can be added to the main payload.
            DhcpOption dhcpMessageTypeOption = new DhcpOption()
            {
                optionId     = dhcpOptionIds.DhcpMessageType,
                optionLength = new byte[] { 0x01 },
                optionValue  = new byte[] { 0x01 },
            };

            // Create the main payload of the dhcp-packet and add the options to it.
            DhcpPacket dhcpDiscoveryPacket = new DhcpPacket()
            {
                transactionID = new byte[] { 0x00, 0x00, 0x00, 0x00 },
                dhcpOptions   = dhcpServerIdentifierOption.buildDhcpOption().ToArray(),
            };

            return(dhcpDiscoveryPacket.buildPacket());
        }
        public DhcpPacket ToPacket(DhcpMessage message, byte[] options)
        {
            DhcpPacket packet = new DhcpPacket
            {
                Op      = (byte)message.OperationCode,
                HType   = (byte)message.HardwareType,
                Hops    = (byte)message.Hops,
                XID     = BitConverter.GetBytes(message.TransactionId).ReverseArray(),
                Secs    = BitConverter.GetBytes(message.SecondsElapsed),
                Flags   = BitConverter.GetBytes(message.Flags),
                CIAddr  = message.ClientIPAddress.GetAddressBytes(),
                YIAddr  = message.YourIPAddress.GetAddressBytes(),
                SIAddr  = message.ServerIPAddress.GetAddressBytes(),
                GIAddr  = message.GatewayIPAddress.GetAddressBytes(),
                Options = options
            };

            packet = SetClientHardwareAddressFields(packet, message);
            return(packet);
        }
Exemple #20
0
        private static byte[] buildDhcpReleasePacket(IPAddress pClientIpAddress, PhysicalAddress pClientHwAddress, IPAddress pDestinationIpAddress)
        {
            Random rand = new Random();

            byte[] _transactionID = new byte[4];
            rand.NextBytes(_transactionID);

            DhcpOption dhcpMessageTypeOption = new DhcpOption()
            {
                optionId     = dhcpOptionIds.DhcpMessageType,
                optionLength = new byte[] { 0x01 },
                optionValue  = new byte[] { 0x07 },
            };

            DhcpOption dhcpServerIdOption = new DhcpOption()
            {
                optionId     = dhcpOptionIds.ServerIdentifier,
                optionLength = new byte[] { 0x04 },
                optionValue  = pDestinationIpAddress.GetAddressBytes(),
            };

            DhcpOption clientIdOption = new DhcpOption()
            {
                optionId     = dhcpOptionIds.ClientIdentifier,
                optionLength = new byte[] { 0x04 },
                optionValue  = pClientIpAddress.GetAddressBytes(),
            };

            byte[] options = dhcpMessageTypeOption.buildDhcpOption().Concat(dhcpServerIdOption.buildDhcpOption()).Concat(clientIdOption.buildDhcpOption()).ToArray();

            DhcpPacket dhcpReleasePacket = new DhcpPacket()
            {
                transactionID = _transactionID,
                clientIP      = pClientIpAddress.GetAddressBytes(),
                clientMac     = pClientHwAddress.GetAddressBytes(),

                dhcpOptions = options,
            };

            return(dhcpReleasePacket.buildPacket());
        }
Exemple #21
0
        private async Task SendReply(DhcpPacket packet)
        {
            try
            {
                var response = packet.GetBytes(PacketSerializer);
                using (UdpClient client = new UdpClient())
                {
                    IPEndPoint endPoint = new IPEndPoint(IPAddress.Broadcast, DHCP_CLIENT_PORT);
                    client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
                    client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontRoute, 1);

                    await client.SendAsync(response, response.Length, endPoint)
                    .ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                Log.Error($"Error sending Dhcp reply: {ex.Message}");
                throw;
            }
        }
        public DhcpMessage ToMessage(DhcpPacket packet)
        {
            DhcpOptionParser parser = new DhcpOptionParser();
            DhcpMessage      result = new DhcpMessage
            {
                OperationCode         = (DhcpOperation)packet.Op,
                HardwareType          = (HardwareType)packet.HType,
                HardwareAddressLength = packet.HLen,
                Hops                  = packet.Hops,
                TransactionId         = BitConverter.ToInt32(packet.XID.Reverse().ToArray(), 0),
                SecondsElapsed        = BitConverter.ToUInt16(packet.Secs, 0),
                Flags                 = BitConverter.ToUInt16(packet.Flags, 0),
                ClientIPAddress       = new IPAddress(packet.CIAddr),
                YourIPAddress         = new IPAddress(packet.YIAddr),
                ServerIPAddress       = new IPAddress(packet.SIAddr),
                GatewayIPAddress      = new IPAddress(packet.GIAddr),
                ClientHardwareAddress = new PhysicalAddress(packet.CHAddr.Take(packet.HLen).ToArray()),
                File                  = packet.File,
                Cookie                = packet.Cookie,
                Options               = parser.GetOptions(packet.Options)
            };

            return(result);
        }
        public async Task StartAsyncReadData(CancellationToken cancellationToken)
        {
            logger.Info("TAP started");
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var buffer = new byte[4096];

                    var readBytes = await tapStream.ReadAsync(buffer, 0, 4096, cancellationToken);

                    if (readBytes <= 0)
                    {
                        continue;
                    }
                    var p = EthernetPacket.Parse(buffer.Take(readBytes).ToArray());
                    if (p.DestinationAddress.GetAddressBytes().Take(3).SequenceEqual(new byte[] { 0x01, 0x00, 0x5E }))
                    {
                        continue;
                    }
                    // ReSharper disable once SwitchStatementMissingSomeCases
                    switch (p.Type)
                    {
                    case EthernetPacket.PacketType.IpV4:
                    {
                        var intId = GetIdFromPhysicalAddress(p.DestinationAddress);
                        if (intId >= 0)
                        {
                            if (HostExists((ushort)intId) || intId == selfId)
                            {
                                await Send(p.Payload, (ushort)intId);
                            }
                            continue;
                        }

                        var ipPacket = (IPv4Packet)p.PayloadPacket;

                        switch (intId)
                        {
                        case -ipMacPoolShift:
                        {
                            if (ipPacket.PayloadPacket is UdpPacket udpPacket &&
                                udpPacket.PayloadPacket is DhcpPacket dhcpPacket)
                            {
                                if (dhcpPacket.Op != 1)
                                {
                                    continue;
                                }

                                var dhcpMessageType =
                                    dhcpPacket.Options.ContainsKey(53) &&
                                    dhcpPacket.Options[53].Length > 0
                                                        ? dhcpPacket.Options[53][0]
                                                        : -1;
                                DhcpPacket answerDhcpPacket;

                                switch (dhcpMessageType)
                                {
                                case 1:                     // DHCPDISCOVER
                                    answerDhcpPacket = new DhcpPacket
                                    {
                                        Xid                   = dhcpPacket.Xid,
                                        YourIpAddress         = GetIpFromId(selfId),
                                        ServerIpAddress       = GetIpFromId(-1),
                                        ClientHardwareAddress = dhcpPacket.ClientHardwareAddress,
                                        Options               =
                                            new Dictionary <byte, byte[]>
                                        {
                                            { 53, new byte[] { 2 } },
                                            { 1, new byte[] { 255, 255, 0, 0 } },
                                            {
                                                51,
                                                BitConverter.GetBytes(30 * 60).Reverse().ToArray()
                                            },
                                            { 54, GetIpFromId(-1).GetAddressBytes() },
                                            { 6, GetIpFromId(-1).GetAddressBytes() }
                                        }
                                    };
                                    break;

                                case 3:                     // DHCPREQUEST
                                    answerDhcpPacket = new DhcpPacket
                                    {
                                        Xid                   = dhcpPacket.Xid,
                                        YourIpAddress         = GetIpFromId(selfId),
                                        ServerIpAddress       = GetIpFromId(-1),
                                        ClientHardwareAddress = dhcpPacket.ClientHardwareAddress,
                                        Options               =
                                            new Dictionary <byte, byte[]>
                                        {
                                            { 53, new byte[] { 5 } },
                                            { 1, new byte[] { 255, 255, 0, 0 } },
                                            {
                                                51,
                                                BitConverter.GetBytes(30 * 60).Reverse().ToArray()
                                            },
                                            { 54, GetIpFromId(-1).GetAddressBytes() },
                                            { 6, GetIpFromId(-1).GetAddressBytes() }
                                        }
                                    };
                                    break;

                                default:
                                    continue;
                                }

                                var answerIpV4Packet = new IPv4Packet(GetIpFromId(-1),
                                                                      IPAddress.Broadcast);
                                answerIpV4Packet.SetPayloadPacket(new UdpPacket(67, 68,
                                                                                answerDhcpPacket, answerIpV4Packet));
                                var answerEthernetPacket = new EthernetPacket(
                                    GetPhysicalAddressFromId(-1),
                                    p.SourceAddress, answerIpV4Packet, EthernetPacket.PacketType.IpV4);
                                var answerData = answerEthernetPacket.ToBytes();
                                await tapStream.WriteAsync(answerData, 0, answerData.Length,
                                                           cancellationToken);

                                continue;
                            }

                            await Broadcast(p.Payload);
                        }
                            continue;

                        case -1:
                        {
                            if (ipPacket.PayloadPacket is UdpPacket udpPacket &&
                                udpPacket.PayloadPacket is DnsPacket dnsPacket)
                            {
                                if (dnsPacket.Queries.Count == 1 && dnsPacket.Queries[0].Type == 1 &&
                                    dnsPacket.Queries[0].Class == 1 && DomainNameUtil.GetName(string.Join(".", dnsPacket.Queries[0].Labels), dnsFormat) != null)
                                {
                                    var name = DomainNameUtil.GetName(string.Join(".", dnsPacket.Queries[0].Labels), dnsFormat);
                                    if (string.IsNullOrEmpty(name))
                                    {
                                        continue;
                                    }
                                    if (name == selfName)
                                    {
                                        await DnsReply(dnsPacket.TransactionId, dnsPacket.Queries[0].Labels, selfId, udpPacket.SourcePort);
                                    }
                                    else
                                    {
                                        var clientId = GetNodes().FirstOrDefault(x =>
                                                                                 x.GetDnmpNodeData().DomainName == name)?.Id;
                                        if (clientId != null)
                                        {
                                            await DnsReply(dnsPacket.TransactionId, dnsPacket.Queries[0].Labels, clientId.Value, udpPacket.SourcePort);
                                        }
                                    }
                                }
                            }
                        }
                            continue;
                        }
                    }
                    break;

                    case EthernetPacket.PacketType.Arp:
                    {
                        var arpPacket = (ArpPacket)p.PayloadPacket;
                        var targetIp  = new IPAddress(arpPacket.TargetProtocolAddress);
                        if (!targetIp.GetAddressBytes().Take(2).SequenceEqual(tapIpPrefix))
                        {
                            continue;
                        }
                        var targetId = GetIdFromPhysicalAddress(GetPhysicalAddressFromIp(targetIp));
                        if (targetId == -ipMacPoolShift)
                        {
                            continue;
                        }
                        if (!HostExists((ushort)targetId) && targetId != -1)
                        {
                            break;
                        }
                        var answerArpPacket = new ArpPacket
                        {
                            TargetHardwareAddress = arpPacket.SenderHardwareAddress,
                            TargetProtocolAddress = arpPacket.SenderProtocolAddress,
                            SenderHardwareAddress = GetPhysicalAddressFromIp(targetIp).GetAddressBytes(),
                            SenderProtocolAddress = arpPacket.TargetProtocolAddress,
                            Operation             = ArpPacket.OperationType.Response,
                            HardwareType          = 0x0001,
                            ProtocolType          = 0x0800
                        };
                        var answerEthernetPacket = new EthernetPacket(GetPhysicalAddressFromIp(targetIp),
                                                                      new PhysicalAddress(arpPacket.SenderHardwareAddress), answerArpPacket,
                                                                      EthernetPacket.PacketType.Arp);
                        var answerData = answerEthernetPacket.ToBytes();
                        await tapStream.WriteAsync(answerData, 0, answerData.Length, cancellationToken);
                    }
                    break;

                    default:
                        continue;
                    }
                }
                catch (TaskCanceledException)
                {
                    return;
                }
                catch (Exception e)
                {
                    logger.Error(e, "Exception in processing packet from TAP-Windows");
                }
            }
        }
Exemple #24
0
        public void ShouldLoadEmptyPacket()
        {
            var packet = new DhcpPacket(new byte[300]);

            Assert.Equal(DhcpMessageType.Unknown, packet.GetDhcpMessageType());
        }
Exemple #25
0
 public byte[] Serialize(DhcpPacket packet)
 {
     throw new System.NotImplementedException();
 }