Example #1
0
 internal ResolutionResult(int nestingLevel, DnsClient.Request request, DnsClient.Response response, NameServerCollection authorities)
 {
     this.NestingLevel = nestingLevel;
       this.Request = request;
       this.Response = response;
       _Authorities = authorities;
 }
        internal static ReadOnlyCollection<IRecord> GetRecords(Servers server, string recordName, DnsClient.RecordType type)
        {
            List<IRecord> records;

            return new ReadOnlyCollection<IRecord>(
                RecordRepository.TryGetValue(server, out records)
                    ? records.Where(r => r.Name == recordName && r.Type == type).ToList()
                    : new List<IRecord>());
        }
Example #3
0
 public DnsWaiters(DnsClient client)
 {
     this.client = client;
 }
Example #4
0
 public ModelLoad(IpTablesSystem iptables, Dictionary <int, IpTablesRuleSet> ruleSets, IpSetSets sets, DnsClient dns = null)
 {
     _iptables = iptables;
     _ruleSets = ruleSets;
     _sets     = sets;
     if (dns != null)
     {
         _dns = dns;
     }
 }
Example #5
0
        public DnsNSRecord(string nameServer)
        {
            DnsClient.IsDomainNameValid(nameServer, true);

            _nameServer = nameServer;
        }
Example #6
0
        protected override void Run()
        {
            /**
             * Packet creation and parsing tests
             **/

            /** Ethernet Packet Parsing Test **/
            byte[] ethernetPacketData = new byte[]
            {
                0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x0C, 0x29, 0xD5, 0xDB, 0x9D, 0x08, 0x00
            };
            EthernetPacket ethernetPacket = new EthernetPacket(ethernetPacketData);

            Equals(ethernetPacketData, ethernetPacket.RawData);

            /** IP Packet Parsing Test **/
            byte[] ipPacketData = new byte[]
            {
                0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x0C, 0x29, 0xD5, 0xDB, 0x9D, 0x08, 0x00, 0x45, 0x00, 0x01, 0x16, 0x00, 0x00, 0x00, 0x00, 0x80, 0x11, 0x39,
                0xD8, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF
            };
            IPPacket ipPacket = new IPPacket(ipPacketData);

            Equals(ipPacketData, ipPacket.RawData);

            /** UDP Packet Parsing Test **/
            byte[] udpPacketData = new byte[]
            {
                0x98, 0xFA, 0x9B, 0xD4, 0xEB, 0x29, 0xD8, 0xCE, 0x3A, 0x89, 0x3E, 0xD9, 0x08, 0x00, 0x45, 0x00, 0x00, 0x22, 0x0C, 0x74, 0x40, 0x00, 0x40, 0x11, 0xAA,
                0xBE, 0xC0, 0xA8, 0x01, 0x02, 0xC0, 0xA8, 0x01, 0x46, 0x10, 0x92, 0x10, 0x92, 0x00, 0x0E, 0x37, 0x22, 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x21
            };
            UDPPacket udpPacket = new UDPPacket(udpPacketData);

            Equals(udpPacketData, udpPacket.RawData);

            /** DNS Packet Parsing Test **/
            byte[] dnsPacketData = new byte[]
            {
                0xB8, 0xD9, 0x4D, 0xC1, 0xA5, 0xFC, 0x98, 0xFA, 0x9B, 0xD4, 0xEB, 0x29, 0x08, 0x00, 0x45, 0x00, 0x00, 0x38, 0xC3, 0x1C, 0x00, 0x00, 0x80, 0x11, 0x00,
                0x00, 0xC0, 0xA8, 0x01, 0x46, 0xC0, 0xA8, 0x01, 0xFE, 0xF0, 0x66, 0x00, 0x35, 0x00, 0x24, 0x84, 0xCA, 0xD6, 0x80, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x06, 0x67, 0x69, 0x74, 0x74, 0x65, 0x72, 0x03, 0x63, 0x6F, 0x6D, 0x00, 0x00, 0x01, 0x00, 0x01
            };
            DNSPacket dnsPacket = new DNSPacket(dnsPacketData);

            Equals(dnsPacketData, dnsPacket.RawData);

            /** DHCP Packet Parsing Test **/
            byte[] dhcpPacketData = new byte[]
            {
                0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xB8, 0xD9, 0x4D, 0xC1, 0xA5, 0xFC, 0x08, 0x00, 0x45, 0xC0, 0x01, 0x59, 0x46, 0x3F, 0x00, 0x00, 0x40, 0x11, 0x6F,
                0xEF, 0xC0, 0xA8, 0x01, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x43, 0x00, 0x44, 0x01, 0x45, 0xD3, 0xC8, 0x02, 0x01, 0x06, 0x00, 0x84, 0xA9, 0x5A, 0x66,
                0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xA8, 0x01, 0x47, 0xC0, 0xA8, 0x01, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x34, 0xE1, 0x2D, 0xA3, 0x06,
                0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x63, 0x82, 0x53, 0x63, 0x35, 0x01, 0x05, 0x36, 0x04, 0xC0, 0xA8, 0x01, 0xFE, 0x33, 0x04, 0x00, 0x01, 0x51, 0x80, 0x3A, 0x04, 0x00,
                0x00, 0xA8, 0xC0, 0x3B, 0x04, 0x00, 0x01, 0x27, 0x50, 0x1C, 0x04, 0xC0, 0xA8, 0x01, 0xFF, 0x51, 0x12, 0x03, 0xFF, 0xFF, 0x44, 0x45, 0x53, 0x4B, 0x54,
                0x4F, 0x50, 0x2D, 0x49, 0x51, 0x48, 0x4A, 0x33, 0x31, 0x43, 0x06, 0x04, 0xC0, 0xA8, 0x01, 0xFE, 0x0F, 0x03, 0x6C, 0x61, 0x6E, 0x03, 0x04, 0xC0, 0xA8,
                0x01, 0xFE, 0x01, 0x04, 0xFF, 0xFF, 0xFF, 0x00, 0xFF
            };
            DHCPPacket dhcpPacket = new DHCPPacket(dhcpPacketData);

            Equals(dhcpPacketData, dhcpPacket.RawData);

            /** TCP Packet Parsing Test **/
            byte[] tcpPacketData = new byte[]
            {
                0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x08, 0x00, 0x45, 0x00, 0x00, 0x3C, 0x64, 0x92, 0x40, 0x00, 0x40, 0x06, 0x51,
                0xA2, 0xC0, 0xA8, 0x01, 0xD3, 0xC0, 0xA8, 0x01, 0x64, 0xA8, 0xAB, 0x10, 0x92, 0x67, 0x7C, 0xCE, 0x18, 0x00, 0x00, 0x00, 0x00, 0xA0, 0x02, 0x72, 0x10,
                0x5F, 0xF0, 0x00, 0x00, 0x02, 0x04, 0x05, 0xB4, 0x04, 0x02, 0x08, 0x0A, 0x58, 0x1A, 0xAA, 0x8A, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x03, 0x07
            };
            TCPPacket tcpPacket = new TCPPacket(tcpPacketData);

            Equals(tcpPacket.SourcePort, 43179);
            Equals(tcpPacket.DestinationPort, 4242);
            Equals(tcpPacket.SequenceNumber, 0x677CCE18);
            Equals(tcpPacket.AckNumber, 0);
            Equals(tcpPacket.TCPFlags, Flags.SYN);
            Equals(tcpPacket.WindowSize, 29200);
            Equals(tcpPacket.Checksum, 0x5FF0);
            Equals(tcpPacket.UrgentPointer, 0);

            /** ARP Packet Parsing Test **/
            byte[] arpPacketData = new byte[]
            {
                0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xB8, 0xD9, 0x4D, 0xC1, 0xA5, 0xFC, 0x08, 0x06, 0x00, 0x01, 0x08, 0x00, 0x06, 0x04, 0x00, 0x01, 0xB8, 0xD9, 0x4D,
                0xC1, 0xA5, 0xFC, 0xC0, 0xA8, 0x01, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xA8, 0x01, 0x46, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
            };
            ARPPacket arpPacket = new ARPPacket(arpPacketData);

            Equals(arpPacketData, arpPacket.RawData);

            TestController.Completed();

            /**
             * Clients tests
             **/
            var dhcpCLient = new DHCPClient();

            dhcpCLient.Close();

            var dnsClient = new DnsClient();

            dnsClient.Close();

            var udpClient = new UdpClient();

            udpClient.Close();

            var tcpClient = new TcpClient(4242);

            tcpClient.Close();

            var icmpClient = new ICMPClient();

            icmpClient.Close();
        }
Example #7
0
        public DnsPTRRecord(string domain)
        {
            DnsClient.IsDomainNameValid(domain, true);

            _domain = domain;
        }
Example #8
0
        private async Task <bool> RefreshZoneAsync(IReadOnlyList <NameServerAddress> nameServers)
        {
            try
            {
                {
                    LogManager log = _dnsServer.LogManager;
                    if (log != null)
                    {
                        log.Write("DNS Server has started zone refresh for stub zone: " + (_name == "" ? "<root>" : _name));
                    }
                }

                DnsClient client = new DnsClient(nameServers);

                client.Proxy       = _dnsServer.Proxy;
                client.PreferIPv6  = _dnsServer.PreferIPv6;
                client.Timeout     = REFRESH_TIMEOUT;
                client.Retries     = REFRESH_RETRIES;
                client.Concurrency = 1;

                DnsDatagram soaRequest  = new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, false, false, false, false, DnsResponseCode.NoError, new DnsQuestionRecord[] { new DnsQuestionRecord(_name, DnsResourceRecordType.SOA, DnsClass.IN) }, null, null, null, DnsDatagram.EDNS_DEFAULT_UDP_PAYLOAD_SIZE);
                DnsDatagram soaResponse = await client.ResolveAsync(soaRequest);

                if (soaResponse.RCODE != DnsResponseCode.NoError)
                {
                    LogManager log = _dnsServer.LogManager;
                    if (log != null)
                    {
                        log.Write("DNS Server received RCODE=" + soaResponse.RCODE.ToString() + " for '" + (_name == "" ? "<root>" : _name) + "' stub zone refresh from: " + soaResponse.Metadata.NameServerAddress.ToString());
                    }

                    return(false);
                }

                if ((soaResponse.Answer.Count < 1) || (soaResponse.Answer[0].Type != DnsResourceRecordType.SOA) || !_name.Equals(soaResponse.Answer[0].Name, StringComparison.OrdinalIgnoreCase))
                {
                    LogManager log = _dnsServer.LogManager;
                    if (log != null)
                    {
                        log.Write("DNS Server received an empty response for SOA query for '" + (_name == "" ? "<root>" : _name) + "' stub zone refresh from: " + soaResponse.Metadata.NameServerAddress.ToString());
                    }

                    return(false);
                }

                DnsResourceRecord currentSoaRecord  = _entries[DnsResourceRecordType.SOA][0];
                DnsResourceRecord receivedSoaRecord = soaResponse.Answer[0];

                DnsSOARecordData currentSoa  = currentSoaRecord.RDATA as DnsSOARecordData;
                DnsSOARecordData receivedSoa = receivedSoaRecord.RDATA as DnsSOARecordData;

                //compare using sequence space arithmetic
                if (!_resync && !currentSoa.IsZoneUpdateAvailable(receivedSoa))
                {
                    LogManager log = _dnsServer.LogManager;
                    if (log != null)
                    {
                        log.Write("DNS Server successfully checked for '" + (_name == "" ? "<root>" : _name) + "' stub zone update from: " + soaResponse.Metadata.NameServerAddress.ToString());
                    }

                    return(true);
                }

                //update available; do zone sync with TCP transport
                List <NameServerAddress> tcpNameServers = new List <NameServerAddress>();

                foreach (NameServerAddress nameServer in nameServers)
                {
                    tcpNameServers.Add(nameServer.ChangeProtocol(DnsTransportProtocol.Tcp));
                }

                nameServers = tcpNameServers;
                client      = new DnsClient(nameServers);

                client.Proxy       = _dnsServer.Proxy;
                client.PreferIPv6  = _dnsServer.PreferIPv6;
                client.Timeout     = REFRESH_TIMEOUT;
                client.Retries     = REFRESH_RETRIES;
                client.Concurrency = 1;

                DnsDatagram nsRequest  = new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, false, false, false, false, DnsResponseCode.NoError, new DnsQuestionRecord[] { new DnsQuestionRecord(_name, DnsResourceRecordType.NS, DnsClass.IN) });
                DnsDatagram nsResponse = await client.ResolveAsync(nsRequest);

                if (nsResponse.RCODE != DnsResponseCode.NoError)
                {
                    LogManager log = _dnsServer.LogManager;
                    if (log != null)
                    {
                        log.Write("DNS Server received RCODE=" + nsResponse.RCODE.ToString() + " for '" + (_name == "" ? "<root>" : _name) + "' stub zone refresh from: " + nsResponse.Metadata.NameServerAddress.ToString());
                    }

                    return(false);
                }

                if (nsResponse.Answer.Count < 1)
                {
                    LogManager log = _dnsServer.LogManager;
                    if (log != null)
                    {
                        log.Write("DNS Server received an empty response for NS query for '" + (_name == "" ? "<root>" : _name) + "' stub zone from: " + nsResponse.Metadata.NameServerAddress.ToString());
                    }

                    return(false);
                }

                //prepare sync records
                List <DnsResourceRecord> nsRecords = new List <DnsResourceRecord>(nsResponse.Answer.Count);

                foreach (DnsResourceRecord record in nsResponse.Answer)
                {
                    if ((record.Type == DnsResourceRecordType.NS) && record.Name.Equals(_name, StringComparison.OrdinalIgnoreCase))
                    {
                        record.SyncGlueRecords(nsResponse.Additional);
                        nsRecords.Add(record);
                    }
                }

                receivedSoaRecord.CopyRecordInfoFrom(currentSoaRecord);

                //sync records
                _entries[DnsResourceRecordType.NS]  = nsRecords;
                _entries[DnsResourceRecordType.SOA] = new DnsResourceRecord[] { receivedSoaRecord };

                {
                    LogManager log = _dnsServer.LogManager;
                    if (log != null)
                    {
                        log.Write("DNS Server successfully refreshed '" + (_name == "" ? "<root>" : _name) + "' stub zone from: " + nsResponse.Metadata.NameServerAddress.ToString());
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                LogManager log = _dnsServer.LogManager;
                if (log != null)
                {
                    string strNameServers = null;

                    foreach (NameServerAddress nameServer in nameServers)
                    {
                        if (strNameServers == null)
                        {
                            strNameServers = nameServer.ToString();
                        }
                        else
                        {
                            strNameServers += ", " + nameServer.ToString();
                        }
                    }

                    log.Write("DNS Server failed to refresh '" + (_name == "" ? "<root>" : _name) + "' stub zone from: " + strNameServers);
                    log.Write(ex);
                }

                return(false);
            }
        }
Example #9
0
 public static LogMessage ResourceRecordFound(DnsClient.Response response, DnsClient.DNS.RR rr)
 {
     return Create(Resources.LogMessages.ResourceRecordFound,
     new object[] { rr.Base.TYPE, (DnsDomain)rr.Base.NAME });
 }
Example #10
0
 public static LogMessage RecordResolutionSucceeded(DnsClient.DNS.QTYPE qtype, int count)
 {
     return Create(Resources.LogMessages.RecordResolutionSucceeded2,
     new object[] { qtype, count });
 }
Example #11
0
 public static LogMessage UnexpectedRCode(int rcodeValue, DnsClient.DNS.RCODE rcode)
 {
     return Create(Resources.LogMessages.UnexpectedRCode, new object[] { rcodeValue, rcode });
 }
Example #12
0
 public static LogMessage QueryNotImplemented(DnsClient.DNS.QTYPE question)
 {
     return Create(Resources.LogMessages.QueryNotImplemented, new object[] { question });
 }
Example #13
0
 public static LogMessage MissingRecords(DnsClient.DNS.QTYPE question)
 {
     return Create(Resources.LogMessages.MissingRecords, new object[] { question });
 }
Example #14
0
            public static LogMessage ResolutionSucceded(
        DnsDomain domain, DnsClient.DNS.QTYPE question, IEnumerable<DnsClient.DNS.RR> requestedAnswerRecords)
            {
                // must be true:
                // requestedAnswerRecords.Any()

                int count = requestedAnswerRecords.Count();
                if (count == 1)
                {
                  DnsClient.DNS.RR rr = requestedAnswerRecords.First();
                  DnsClient.DNS.Records.Address address;
                  DnsClient.DNS.Records.PTR pointer;

                  if (!Object.ReferenceEquals(null, (address = rr as DnsClient.DNS.Records.Address)))
                  {
                // "The name '{0}' was successfully resolved to {1}."
                return RESPONSE.INFO.SingleAddressResolutionSucceeded(domain, address.ADDRESS);
                  }

                  if (!Object.ReferenceEquals(null, (pointer = rr as DnsClient.DNS.Records.PTR)))
                  {
                // "Pointer resolution succeeded with the name '{0}'."
                return RESPONSE.INFO.SinglePointerResolutionSucceeded(pointer.PTRDNAME);
                  }

                  // "A Resouce Records of type {0} was found."
                  return RESPONSE.INFO.RecordResolutionSucceeded(question);
                }

                // "{1} Resouce Records of type {0} were found."
                return RESPONSE.INFO.RecordResolutionSucceeded(question, count);
            }
Example #15
0
 /// <summary>
 /// &quot;Non-Zero RCODE received: {0} ({1}).&quot;
 /// </summary>
 /// <param name="rcodeValue"></param>
 /// <param name="rcode"></param>
 /// <returns></returns>
 public static LogMessage ResponseNonZero(byte rcodeValue, DnsClient.DNS.RCODE rcode)
 {
   return Create(
     Resources.LogMessages.ResponseNonZero,
       new object[] { rcodeValue, rcode });
 }
Example #16
0
        public void ResolveIPAddress(NameServerAddress[] nameServers = null, NetProxy proxy = null, bool preferIPv6 = false, DnsTransportProtocol protocol = DnsTransportProtocol.Udp, int retries = 2, int timeout = 2000)
        {
            lock (_ipEndPointResolverLock)
            {
                if (_ipEndPointExpires && (DateTime.UtcNow < _ipEndPointExpiresOn))
                {
                    return;
                }

                string domain;

                if (_dohEndPoint != null)
                {
                    domain = _dohEndPoint.Host;
                }
                else if (_domainEndPoint != null)
                {
                    domain = _domainEndPoint.Address;
                }
                else
                {
                    return;
                }

                if (domain == "localhost")
                {
                    _ipEndPoint = new IPEndPoint((preferIPv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback), this.Port);
                    return;
                }

                if (IPAddress.TryParse(domain, out IPAddress address))
                {
                    _ipEndPoint = new IPEndPoint(address, this.Port);
                    return;
                }

                DnsClient dnsClient;

                if (nameServers == null)
                {
                    dnsClient = new DnsClient();
                }
                else
                {
                    dnsClient = new DnsClient(nameServers);
                }

                dnsClient.Proxy      = proxy;
                dnsClient.PreferIPv6 = preferIPv6;
                dnsClient.Protocol   = protocol;
                dnsClient.Retries    = retries;
                dnsClient.Timeout    = timeout;

                IPAddress[] serverIPs = dnsClient.ResolveIP(domain, preferIPv6);

                if (serverIPs.Length == 0)
                {
                    throw new DnsClientException("No IP address was found for name server: " + domain);
                }

                _ipEndPoint          = new IPEndPoint(serverIPs[0], this.Port);
                _ipEndPointExpires   = true;
                _ipEndPointExpiresOn = DateTime.UtcNow.AddSeconds(60);
            }
        }
Example #17
0
        protected override WebRequest GetWebRequest(Uri address)
        {
            HttpWebRequest request = null;

            switch (_networkType)
            {
            case WebClientExNetworkType.IPv4Only:
                if (IPAddress.TryParse(address.Host, out IPAddress ipv4))
                {
                    if (ipv4.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        throw new WebException("WebClientEx current network type does not allow url address family: " + ipv4.AddressFamily.ToString());
                    }

                    request = base.GetWebRequest(address) as HttpWebRequest;
                }
                else
                {
                    try
                    {
                        DnsClient dns = new DnsClient();
                        IReadOnlyList <IPAddress> ipAddresses = dns.ResolveIPAsync(address.Host).Sync();

                        if (ipAddresses.Count == 0)
                        {
                            throw new WebException("WebClientEx could not resolve IPv4 address for host: " + address.Host);
                        }

                        foreach (IPAddress ipAddress in ipAddresses)
                        {
                            if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                            {
                                Uri newAddress = new Uri(address.Scheme + "://" + ipAddress.ToString() + ":" + address.Port + address.PathAndQuery);
                                request      = base.GetWebRequest(newAddress) as HttpWebRequest;
                                request.Host = address.Host;
                                break;
                            }
                        }
                    }
                    catch (DnsClientException ex)
                    {
                        throw new WebException("WebClientEx could not resolve IPv4 address for host: " + address.Host, ex);
                    }

                    if (request == null)
                    {
                        throw new WebException("WebClientEx could not resolve IPv4 address for host: " + address.Host);
                    }
                }
                break;

            case WebClientExNetworkType.IPv6Only:
                if (IPAddress.TryParse(address.Host, out IPAddress ipv6))
                {
                    if (ipv6.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6)
                    {
                        throw new WebException("WebClientEx current network type does not allow url address family: " + ipv6.AddressFamily.ToString());
                    }

                    request = base.GetWebRequest(address) as HttpWebRequest;
                }
                else
                {
                    try
                    {
                        DnsClient dns = new DnsClient(true);
                        IReadOnlyList <IPAddress> ipAddresses = dns.ResolveIPAsync(address.Host, true).Sync();

                        if (ipAddresses.Count == 0)
                        {
                            throw new WebException("WebClientEx could not resolve IPv6 address for host: " + address.Host);
                        }

                        foreach (IPAddress ipAddress in ipAddresses)
                        {
                            if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                            {
                                Uri newAddress = new Uri(address.Scheme + "://[" + ipAddress.ToString() + "]:" + address.Port + address.PathAndQuery);
                                request      = base.GetWebRequest(newAddress) as HttpWebRequest;
                                request.Host = address.Host;
                                break;
                            }
                        }
                    }
                    catch (DnsClientException ex)
                    {
                        throw new WebException("WebClientEx could not resolve IPv6 address for host: " + address.Host, ex);
                    }

                    if (request == null)
                    {
                        throw new WebException("WebClientEx could not resolve IPv6 address for host: " + address.Host);
                    }
                }
                break;

            default:
                request = base.GetWebRequest(address) as HttpWebRequest;
                break;
            }

            if (_timeout > 0)
            {
                request.Timeout = _timeout;
            }

            request.CookieContainer = _cookie;

            if (_ifModifiedSince > DateTime.MinValue)
            {
                request.IfModifiedSince = _ifModifiedSince;
            }

            if (_userAgent != null)
            {
                request.UserAgent = _userAgent;
            }

            request.KeepAlive = _keepAlive;

            if (_enableAutomaticDecompression)
            {
                request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }

            foreach (KeyValuePair <string, string> header in _headers)
            {
                switch (header.Key.ToLower())
                {
                case "accept":
                    request.Accept = header.Value;
                    break;

                case "connection":
                    request.KeepAlive = header.Value.Equals("keep-alive", StringComparison.OrdinalIgnoreCase);
                    break;

                case "content-type":
                    request.ContentType = header.Value;
                    break;

                case "user-agent":
                    request.UserAgent = header.Value;
                    break;

                case "host":
                    request.Host = header.Value;
                    break;

                default:
                    request.Headers.Add(header.Key, header.Value);
                    break;
                }
            }

            return(request);
        }
Example #18
0
 public static LogMessage ResourceRecordFoundAAAA(DnsClient.Response response, DnsClient.DNS.Records.AAAA rr)
 {
     return Create(Resources.LogMessages.ResourceRecordFoundAAAA,
     new object[] { (DnsDomain)rr.Base.NAME, rr.ADDRESS });
 }
Example #19
0
        public DnsNSRecord(string nsDomainName)
        {
            DnsClient.IsDomainNameValid(nsDomainName, true);

            _nsDomainName = nsDomainName;
        }
Example #20
0
 public static LogMessage ResourceRecordFoundNS(DnsClient.Response response, DnsClient.DNS.Records.NS rr)
 {
     return Create(Resources.LogMessages.ResourceRecordFoundNS,
     new object[] { (DnsDomain)rr.NSDNAME });
 }
 internal AddressResolutionResult(int nestingLevel, DnsClient.Request request, DnsClient.Response response, NameServerCollection authorities)
     : base(nestingLevel, request, response, authorities)
 {
 }
Example #22
0
 public static LogMessage ResourceRecordFoundPTR(DnsClient.Response response, DnsClient.DNS.Records.PTR rr)
 {
     return Create(Resources.LogMessages.ResourceRecordFoundPTR,
     new object[] { (DnsDomain)rr.Base.NAME, (DnsDomain)rr.PTRDNAME });
 }
        private Queue <string> ReadListFile(Uri listUrl, bool isAllow)
        {
            Queue <string> domains = new Queue <string>();

            try
            {
                LogManager log = _dnsServer.LogManager;
                if (log != null)
                {
                    log.Write("DNS Server is reading " + (isAllow ? "allow" : "block") + " list from: " + listUrl.AbsoluteUri);
                }

                using (FileStream fS = new FileStream(GetBlockListFilePath(listUrl), FileMode.Open, FileAccess.Read))
                {
                    //parse hosts file and populate block zone
                    StreamReader sR = new StreamReader(fS, true);
                    string       line;
                    string       firstWord;
                    string       secondWord;
                    string       hostname;

                    while (true)
                    {
                        line = sR.ReadLine();
                        if (line == null)
                        {
                            break; //eof
                        }
                        line = line.TrimStart(' ', '\t');

                        if (line.Length == 0)
                        {
                            continue; //skip empty line
                        }
                        if (line.StartsWith("#"))
                        {
                            continue; //skip comment line
                        }
                        firstWord = PopWord(ref line);


                        if (line.Length == 0)
                        {
                            hostname = firstWord;
                        }
                        else
                        {
                            secondWord = PopWord(ref line);

                            if (secondWord.Length == 0)
                            {
                                hostname = firstWord;
                            }
                            else
                            {
                                hostname = secondWord;
                            }
                        }

                        hostname = hostname.Trim('.').ToLower();

                        switch (hostname)
                        {
                        case "":
                        case "localhost":
                        case "localhost.localdomain":
                        case "local":
                        case "broadcasthost":
                        case "ip6-localhost":
                        case "ip6-loopback":
                        case "ip6-localnet":
                        case "ip6-mcastprefix":
                        case "ip6-allnodes":
                        case "ip6-allrouters":
                        case "ip6-allhosts":
                            continue;     //skip these hostnames
                        }

                        if (!DnsClient.IsDomainNameValid(hostname))
                        {
                            continue;
                        }

                        if (IPAddress.TryParse(hostname, out _))
                        {
                            continue; //skip line when hostname is IP address
                        }
                        domains.Enqueue(hostname);
                    }
                }

                if (log != null)
                {
                    log.Write("DNS Server " + (isAllow ? "allow" : "block") + " list file was read (" + domains.Count + " domains) from: " + listUrl.AbsoluteUri);
                }
            }
            catch (Exception ex)
            {
                LogManager log = _dnsServer.LogManager;
                if (log != null)
                {
                    log.Write("DNS Server failed to read " + (isAllow ? "allow" : "block") + " list from: " + listUrl.AbsoluteUri + "\r\n" + ex.ToString());
                }
            }

            return(domains);
        }
Example #24
0
 public static LogMessage SendingRequest(System.Net.IPAddress address, DnsClient.NetworkProtocol proto)
 {
     return Create(Resources.LogMessages.SendingRequest, new object[] { address, proto });
 }
Example #25
0
        /// <summary>
        /// Gets the reverse lookup FQDN of the given IP Address.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <returns>A <see cref="System.String" /> that represents the current object.</returns>
        public static Task <string> GetDnsPointerEntryAsync(IPAddress query)
        {
            var client = new DnsClient(GetIPv4DnsServers().FirstOrDefault());

            return(client.Reverse(query));
        }
Example #26
0
 private bool FindCanonical(DnsDomain sname, out DnsClient.DNS.Records.CNAME cname)
 {
     IEnumerable<DnsClient.DNS.Records.CNAME> cnames = Response.AnswerRecords.Select<
     DnsClient.DNS.Records.CNAME>().Where(cn => sname.Equals(cn.Base.NAME));
       switch (cnames.Count())
       {
     case 0:
       cname = null;
       return false;
     case 1:
       cname = cnames.First();
       return true;
     default:
       // Ambigious CNAME records
       throw new QueryException(QueryState.AmbigiousCNAME, sname);
       }
 }
Example #27
0
        private static async Task <IReadOnlyList <NameServerAddress> > GetNameServerAddressesAsync(DnsServer dnsServer, DnsResourceRecord record)
        {
            string nsDomain;

            switch (record.Type)
            {
            case DnsResourceRecordType.NS:
                nsDomain = (record.RDATA as DnsNSRecord).NameServer;
                break;

            case DnsResourceRecordType.SOA:
                nsDomain = (record.RDATA as DnsSOARecord).PrimaryNameServer;
                break;

            default:
                throw new InvalidOperationException();
            }

            List <NameServerAddress> nameServers = new List <NameServerAddress>(2);

            IReadOnlyList <DnsResourceRecord> glueRecords = record.GetGlueRecords();

            if (glueRecords.Count > 0)
            {
                foreach (DnsResourceRecord glueRecord in glueRecords)
                {
                    switch (glueRecord.Type)
                    {
                    case DnsResourceRecordType.A:
                        nameServers.Add(new NameServerAddress(nsDomain, (glueRecord.RDATA as DnsARecord).Address));
                        break;

                    case DnsResourceRecordType.AAAA:
                        if (dnsServer.PreferIPv6)
                        {
                            nameServers.Add(new NameServerAddress(nsDomain, (glueRecord.RDATA as DnsAAAARecord).Address));
                        }

                        break;
                    }
                }
            }
            else
            {
                //resolve addresses
                try
                {
                    DnsDatagram response = await dnsServer.DirectQueryAsync(new DnsQuestionRecord(nsDomain, DnsResourceRecordType.A, DnsClass.IN));

                    if ((response != null) && (response.Answer.Count > 0))
                    {
                        IReadOnlyList <IPAddress> addresses = DnsClient.ParseResponseA(response);
                        foreach (IPAddress address in addresses)
                        {
                            nameServers.Add(new NameServerAddress(nsDomain, address));
                        }
                    }
                }
                catch
                { }

                if (dnsServer.PreferIPv6)
                {
                    try
                    {
                        DnsDatagram response = await dnsServer.DirectQueryAsync(new DnsQuestionRecord(nsDomain, DnsResourceRecordType.AAAA, DnsClass.IN));

                        if ((response != null) && (response.Answer.Count > 0))
                        {
                            IReadOnlyList <IPAddress> addresses = DnsClient.ParseResponseAAAA(response);
                            foreach (IPAddress address in addresses)
                            {
                                nameServers.Add(new NameServerAddress(nsDomain, address));
                            }
                        }
                    }
                    catch
                    { }
                }
            }

            return(nameServers);
        }
Example #28
0
 public QueryProcessor(DnsDomain sname, DnsClient.DNS.QTYPE stype, DnsClient.Response response)
 {
     this.SNAME = sname;
       this.STYPE = stype;
       this.Response = response;
 }
Example #29
0
 public DnsServer(IPEndPoint endServer)
 {
     this.emitter    = new EventEmitter();
     this.client     = new DnsClient(endServer, new UdpRequestResolver());
     this.masterFile = new MasterFile();
 }
Example #30
0
 internal NameServerEventArgs(NameServer server, DnsClient.DNS.QTYPE question, string domain)
 {
     _NameServer = server;
       _QuestionType = question;
       _Domain = domain;
 }
Example #31
0
        public static NameServerAddress[] GetNameServersFromResponse(DnsDatagram response, bool preferIPv6)
        {
            List <NameServerAddress> nameServers = new List <NameServerAddress>(response.Authority.Length);

            DnsResourceRecord[] authorityRecords;

            if ((response.Question.Length > 0) && (response.Question[0].Type == DnsResourceRecordType.NS) && (response.Answer.Length > 0))
            {
                authorityRecords = response.Answer;
            }
            else
            {
                authorityRecords = response.Authority;
            }

            foreach (DnsResourceRecord authorityRecord in authorityRecords)
            {
                if (authorityRecord.Type == DnsResourceRecordType.NS)
                {
                    DnsNSRecord nsRecord = (DnsNSRecord)authorityRecord.RDATA;
                    IPEndPoint  endPoint = null;

                    //find ip address of authoritative name server from additional records
                    foreach (DnsResourceRecord rr in response.Additional)
                    {
                        if (nsRecord.NSDomainName.Equals(rr.Name, StringComparison.OrdinalIgnoreCase))
                        {
                            switch (rr.Type)
                            {
                            case DnsResourceRecordType.A:
                                endPoint = new IPEndPoint(((DnsARecord)rr.RDATA).Address, 53);
                                nameServers.Add(new NameServerAddress(nsRecord.NSDomainName, endPoint));
                                break;

                            case DnsResourceRecordType.AAAA:
                                endPoint = new IPEndPoint(((DnsAAAARecord)rr.RDATA).Address, 53);

                                if (preferIPv6)
                                {
                                    nameServers.Add(new NameServerAddress(nsRecord.NSDomainName, endPoint));
                                }

                                break;
                            }
                        }
                    }

                    if (endPoint == null)
                    {
                        nameServers.Add(new NameServerAddress(new DomainEndPoint(nsRecord.NSDomainName, 53)));
                    }
                }
            }

            NameServerAddress[] nsArray = nameServers.ToArray();

            DnsClient.ShuffleArray(nsArray);

            if (preferIPv6)
            {
                Array.Sort(nsArray);
            }

            return(nsArray);
        }
Example #32
0
        public string Lookup(string domain, DnsClient.RecordType recordtype, bool onlyGetOneRecord)
        {
            StringBuilder output = new StringBuilder();
            if (domain.Trim().Length == 0)
            {
                output.Append("");
            }
            else
            {
                try
                {
                    DnsClient.RequestOptions options = new DnsClient.RequestOptions();

                    if (EnableCustomDnsServers)
                    {
                        options.DnsServers = new IPAddress[] { PrimaryDnsServer, SecondaryDnsServer };
                    }
                    options.TimeOut = new TimeSpan(0, 0, Timeout);
                    options.RetryCount = RetryCount;

                    if (recordtype == DnsClient.RecordType.PTR)
                    {
                        string[] hostnames;
                        IPAddress ip;
                        if (IPAddress.TryParse(domain, out ip))
                        {
                            hostnames = DnsClient.LookupReverse(ip, options);
                            if (onlyGetOneRecord)
                            {
                                if (EnableDebugLogging)
                                {
                                    output.Append(String.Format("IP: {0} Type: {1} Result: {2}", ip.ToString(), recordtype, hostnames[hostnames.Length - 1]));
                                }
                                else
                                {
                                    output.Append(hostnames[hostnames.Length - 1]);
                                }
                            }
                            else
                            {
                                for (int i = 0; i < hostnames.Length; i++)
                                {
                                    if (i == hostnames.Length - 1)
                                    {
                                        // It's the last record, end the output without a linebreak.
                                        if (EnableDebugLogging)
                                        {
                                            output.Append(String.Format("IP: {0} Type: {1} Result: {2}", ip.ToString(), recordtype, hostnames[i]));
                                        }
                                        else
                                        {
                                            output.Append(hostnames[i]);
                                        }
                                    }
                                    else
                                    {
                                        if (EnableDebugLogging)
                                        {
                                            output.AppendLine(String.Format("IP: {0} Type: {1} Result: {2}", ip.ToString(), recordtype, hostnames[i]));
                                        }
                                        else
                                        {
                                            output.AppendLine(hostnames[i]);
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            output.Append(String.Format("Error: {0} is not a valid IP address", domain));
                        }
                    }
                    //else if (recordtype == DnsClient.RecordType.MX)
                    //{
                    //    // TODO: Implement this - add support for MX Priority stuff in output?
                    //    DnsClient.MXHost[] mailhosts = DnsClient.LookupMX(domain, options);
                    //    if (onlyGetOneRecord)
                    //    {

                    //    }
                    //    else
                    //    {
                    //        foreach(var m in mailhosts)
                    //            output.AppendLine(String.Format("Preference: {2} Hostname: {0} IP: ", m.HostName, m.IPAddresses, m.Preference));

                    //    }
                    //}
                    else
                    {
                        DnsClient.Response response = DnsClient.Lookup(domain, recordtype, options);
                        if (onlyGetOneRecord)
                        {
                            // We should only get one record, so we'll pick the last record looked up in the chain.
                            // It's most likely the one needed in typical recursive A-record lookups.
                            DnsClient.Response.Record record = response.AnswerRecords[response.AnswerRecords.Count - 1];
                            if (EnableDebugLogging)
                            {
                                output.Append(String.Format("Domain: {0} Type: {1} TTL: {2} Result: {3}", record.Name, record.Type, record.TTL, record.Data));
                            }
                            else
                            {
                                output.Append(record.Data);
                            }
                        }
                        else
                        {
                            for (int i = 0; i < response.AnswerRecords.Count; i++)
                            {
                                if (i == response.AnswerRecords.Count - 1)
                                {
                                    // It's the last record, end the output without a linebreak.
                                    if (EnableDebugLogging)
                                    {
                                        output.Append(String.Format("Domain: {0} Type: {1} TTL: {2} Result: {3}", response.AnswerRecords[i].Name, response.AnswerRecords[i].Type, response.AnswerRecords[i].TTL, response.AnswerRecords[i].Data));
                                    }
                                    else
                                    {
                                        output.Append(response.AnswerRecords[i].Data);
                                    }
                                }
                                else
                                {
                                    if (EnableDebugLogging)
                                    {
                                        output.AppendLine(String.Format("Domain: {0} Type: {1} TTL: {2} Result: {3}", response.AnswerRecords[i].Name, response.AnswerRecords[i].Type, response.AnswerRecords[i].TTL, response.AnswerRecords[i].Data));
                                    }
                                    else
                                    {
                                        output.AppendLine(response.AnswerRecords[i].Data);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (DnsClient.NXDomainException nxd)
                {
                    if (EnableDebugLogging)
                    {
                        output.Append(nxd.Message);

                    }
                    else
                    {
                        output.Append("The domain name does not exist.");
                    }
                }
                catch (DnsClient.NoDefinitiveAnswerException nda)
                {
                    if (EnableDebugLogging)
                    {
                        for (int i = 0; i < nda.ServerProblems.Count; i++)
                        {
                            if (i == nda.ServerProblems.Count - 1)
                            {
                                // It's the last record, end the output without a linebreak
                                output.Append(String.Format("DNS Server: {0} Problem: {1} ({2})", nda.ServerProblems[i].Server, nda.ServerProblems[i].ProblemDescription, nda.ServerProblems[i].Problem));
                            }
                            else
                            {
                                output.AppendLine(String.Format("DNS Server: {0} Problem: {1} ({2})", nda.ServerProblems[i].Server, nda.ServerProblems[i].ProblemDescription, nda.ServerProblems[i].Problem));
                            }
                        }
                    }
                    else
                    {
                        output.Append("No definitive answer from server.");
                    }
                }
                catch (Exception ex)
                {
                    output.Append("Error: " + ex.Message);
                }
            }
            return output.ToString();
        }
Example #33
0
        public void RecursiveResolveIPAddress(DnsCache cache = null, NetProxy proxy = null, bool preferIPv6 = false, DnsTransportProtocol protocol = DnsTransportProtocol.Udp, int retries = 2, int timeout = 2000, DnsTransportProtocol recursiveResolveProtocol = DnsTransportProtocol.Udp)
        {
            lock (_ipEndPointResolverLock)
            {
                if (_ipEndPointExpires && (DateTime.UtcNow < _ipEndPointExpiresOn))
                {
                    return;
                }

                string domain;

                if (_dohEndPoint != null)
                {
                    domain = _dohEndPoint.Host;
                }
                else if (_domainEndPoint != null)
                {
                    domain = _domainEndPoint.Address;
                }
                else
                {
                    return;
                }

                if (domain == "localhost")
                {
                    _ipEndPoint = new IPEndPoint((preferIPv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback), this.Port);
                    return;
                }

                if (IPAddress.TryParse(domain, out IPAddress address))
                {
                    _ipEndPoint = new IPEndPoint(address, this.Port);
                    return;
                }

                IPEndPoint ipEndPoint          = null;
                DateTime   ipEndPointExpiresOn = DateTime.MinValue;

                if (preferIPv6)
                {
                    DnsDatagram nsResponse = DnsClient.RecursiveResolve(new DnsQuestionRecord(domain, DnsResourceRecordType.AAAA, DnsClass.IN), null, cache, proxy, true, protocol, retries, timeout, recursiveResolveProtocol);
                    if ((nsResponse.Header.RCODE == DnsResponseCode.NoError) && (nsResponse.Answer.Length > 0) && (nsResponse.Answer[0].Type == DnsResourceRecordType.AAAA))
                    {
                        ipEndPoint          = new IPEndPoint((nsResponse.Answer[0].RDATA as DnsAAAARecord).Address, this.Port);
                        ipEndPointExpiresOn = DateTime.UtcNow.AddSeconds(nsResponse.Answer[0].TtlValue);
                    }
                }

                if (ipEndPoint == null)
                {
                    DnsDatagram nsResponse = DnsClient.RecursiveResolve(new DnsQuestionRecord(domain, DnsResourceRecordType.A, DnsClass.IN), null, cache, proxy, false, protocol, retries, timeout, recursiveResolveProtocol);
                    if ((nsResponse.Header.RCODE == DnsResponseCode.NoError) && (nsResponse.Answer.Length > 0) && (nsResponse.Answer[0].Type == DnsResourceRecordType.A))
                    {
                        ipEndPoint          = new IPEndPoint((nsResponse.Answer[0].RDATA as DnsARecord).Address, this.Port);
                        ipEndPointExpiresOn = DateTime.UtcNow.AddSeconds(nsResponse.Answer[0].TtlValue);
                    }
                }

                if (ipEndPoint == null)
                {
                    throw new DnsClientException("No IP address was found for name server: " + domain);
                }

                _ipEndPoint          = ipEndPoint;
                _ipEndPointExpires   = true;
                _ipEndPointExpiresOn = ipEndPointExpiresOn;
            }
        }
Example #34
0
        public DnsPTRRecord(string ptrDomainName)
        {
            DnsClient.IsDomainNameValid(ptrDomainName, true);

            _ptrDomainName = ptrDomainName;
        }
Example #35
0
        /// <summary>
        /// Finds the best matching SRV record.
        /// </summary>
        /// <param name="domain">The domain.</param>
        /// <returns>DnsSrvRecord(will be null if lookup failed).</returns>
        private DnsSrvRecord FindBestMatchingSrvRecord(string domain)
        {
            List <DnsSrvRecord> dnsSrvRecordList;

            try
            {
                // Make DnsQuery call to get collection of SRV records.
                dnsSrvRecordList = DnsClient.DnsQuery <DnsSrvRecord>(domain, this.service.DnsServerAddress);
            }
            catch (DnsException ex)
            {
                string dnsExcMessage = string.Format(
                    "DnsQuery returned error error '{0}' error code 0x{1:X8}.",
                    ex.Message,
                    ex.NativeErrorCode);
                this.service.TraceMessage(TraceFlags.AutodiscoverConfiguration, dnsExcMessage);
                return(null);
            }
            catch (SecurityException ex)
            {
                // In restricted environments, we may not be allowed to call unmanaged code.
                this.service.TraceMessage(
                    TraceFlags.AutodiscoverConfiguration,
                    string.Format("DnsQuery cannot be called. Security error: {0}.", ex.Message));
                return(null);
            }

            this.service.TraceMessage(
                TraceFlags.AutodiscoverConfiguration,
                string.Format("{0} SRV records were returned.", dnsSrvRecordList.Count));

            // If multiple records were returned, they will be returned sorted by priority
            // (and weight) order. Need to find the index of the first record that supports SSL.
            int  priority    = int.MinValue;
            int  weight      = int.MinValue;
            bool recordFound = false;

            foreach (DnsSrvRecord dnsSrvRecord in dnsSrvRecordList)
            {
                if (dnsSrvRecord.Port == SslPort)
                {
                    priority    = dnsSrvRecord.Priority;
                    weight      = dnsSrvRecord.Weight;
                    recordFound = true;
                    break;
                }
            }

            // Records were returned but nothing matched our criteria.
            if (!recordFound)
            {
                this.service.TraceMessage(
                    TraceFlags.AutodiscoverConfiguration,
                    "No appropriate SRV records were found.");

                return(null);
            }

            // Collect all records with the same (highest) priority.
            // (Aren't lambda expressions cool? ;-)
            List <DnsSrvRecord> bestDnsSrvRecordList = dnsSrvRecordList.FindAll(
                record => (record.Port == SslPort) && (record.Priority == priority) && (record.Weight == weight));

            // The list must contain at least one matching record since we found one earlier.
            EwsUtilities.Assert(
                dnsSrvRecordList.Count > 0,
                "AutodiscoverDnsClient.FindBestMatchingSrvRecord",
                "At least one DNS SRV record must match the criteria.");

            // If we have multiple records with the same priority and weight, randomly pick one.
            int recordIndex = (bestDnsSrvRecordList.Count > 1)
                ? randomTieBreakerSelector.Next(bestDnsSrvRecordList.Count)
                : 0;

            DnsSrvRecord bestDnsSrvRecord = bestDnsSrvRecordList[recordIndex];

            string traceMessage = string.Format(
                "Returning SRV record {0} of {1} records. Target: {2}, Priority: {3}, Weight: {4}",
                recordIndex,
                dnsSrvRecordList.Count,
                bestDnsSrvRecord.NameTarget,
                bestDnsSrvRecord.Priority,
                bestDnsSrvRecord.Weight);

            this.service.TraceMessage(TraceFlags.AutodiscoverConfiguration, traceMessage);

            return(bestDnsSrvRecord);
        }
Example #36
0
 protected virtual void OnMissingRecords(DnsClient.Response response)
 {
     // "No Resource Record of type {0} was found."
       LogMessageCreate(Logging.LogMessageText.RESPONSE.ERROR.MissingRecords(Question));
 }
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            switch (_networkType)
            {
            case HttpClientNetworkType.IPv4Only:
                if (IPAddress.TryParse(request.RequestUri.Host, out IPAddress ipv4))
                {
                    if (ipv4.AddressFamily != AddressFamily.InterNetwork)
                    {
                        throw new HttpRequestException("HttpClient current network type allows only IPv4 addresses.");
                    }

                    return(await base.SendAsync(request, cancellationToken));
                }
                else
                {
                    try
                    {
                        DnsClient dns = new DnsClient();
                        IReadOnlyList <IPAddress> ipAddresses = await dns.ResolveIPAsync(request.RequestUri.Host);

                        foreach (IPAddress ipAddress in ipAddresses)
                        {
                            if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
                            {
                                request.Headers.Host = request.RequestUri.Host;
                                request.RequestUri   = new Uri(request.RequestUri.Scheme + "://" + ipAddress.ToString() + ":" + request.RequestUri.Port + request.RequestUri.PathAndQuery);
                                return(await base.SendAsync(request, cancellationToken));
                            }
                        }

                        throw new HttpRequestException("HttpClient could not resolve IPv4 address for host: " + request.RequestUri.Host);
                    }
                    catch (DnsClientException ex)
                    {
                        throw new HttpRequestException("HttpClient could not resolve IPv4 address for host: " + request.RequestUri.Host, ex);
                    }
                }

            case HttpClientNetworkType.IPv6Only:
                if (IPAddress.TryParse(request.RequestUri.Host, out IPAddress ipv6))
                {
                    if (ipv6.AddressFamily != AddressFamily.InterNetworkV6)
                    {
                        throw new HttpRequestException("HttpClient current network type allows only IPv6 addresses.");
                    }

                    return(await base.SendAsync(request, cancellationToken));
                }
                else
                {
                    try
                    {
                        DnsClient dns = new DnsClient();
                        IReadOnlyList <IPAddress> ipAddresses = await dns.ResolveIPAsync(request.RequestUri.Host, true);

                        foreach (IPAddress ipAddress in ipAddresses)
                        {
                            if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
                            {
                                request.Headers.Host = request.RequestUri.Host;
                                request.RequestUri   = new Uri(request.RequestUri.Scheme + "://[" + ipAddress.ToString() + "]:" + request.RequestUri.Port + request.RequestUri.PathAndQuery);
                                return(await base.SendAsync(request, cancellationToken));
                            }
                        }

                        throw new HttpRequestException("HttpClient could not resolve IPv6 address for host: " + request.RequestUri.Host);
                    }
                    catch (DnsClientException ex)
                    {
                        throw new HttpRequestException("HttpClient could not resolve IPv6 address for host: " + request.RequestUri.Host, ex);
                    }
                }

            default:
                return(await base.SendAsync(request, cancellationToken));
            }
        }
Example #38
0
        protected virtual void OnRCodeNonZero(DnsClient.Response response)
        {
            switch (response.Header.RCODE)
              {
            case DnsClient.DNS.RCODE.NameError:
              // "The name '{0}' does not exist."
              LogMessageCreate(Logging.LogMessageText.RESPONSE.ERROR.NameNotExisting(Resolver.Domain));
              break;

            case DnsClient.DNS.RCODE.NotImplemented:
              // "The name server does not support queries of type '{0}'."
              LogMessageCreate(Logging.LogMessageText.RESPONSE.ERROR.QueryNotImplemented(Question));
              break;

            case DnsClient.DNS.RCODE.Refused:
              // "The name server refuses to perform the specified operation for policy easons."
              LogMessageCreate(Logging.LogMessageText.RESPONSE.ERROR.ServerRefused());
              break;

            case DnsClient.DNS.RCODE.ServerFailure:
              // "The name server was unable to process this query due to a problem with the name server."
              LogMessageCreate(Logging.LogMessageText.RESPONSE.ERROR.ServerFailure());
              break;

            default:
              // "Unexpected RCODE value {0} '{1}' received."
              LogMessageCreate(Logging.LogMessageText.RESPONSE.ERROR.UnexpectedRCode(response.Header.RCODEValue, response.Header.RCODE));
              break;

              }
        }
Example #39
0
 public DnsListener(StatefulServiceContext context)
 {
     _server = new ARSoft.Tools.Net.Dns.DnsServer(10, 10);
     _server.QueryReceived += _server_QueryReceived;
     client = new DnsClient(System.Net.IPAddress.Parse("114.114.114.114"), 5);
 }
Example #40
0
 internal ResolutionIterator(DomainResolver resolver, DnsClient.DNS.QTYPE question, Caching.AddressCache addressCache)
     : base(resolver, question, addressCache)
 {
     NestingLevel = 0;
 }
Example #41
0
        private async void ProcessMessageAsync(UdpReceiveResult udpMessage)
        {
            await Task.Run(async() =>
            {
                try
                {
                    DnsMessage message;
                    DnsQuestion question;
                    var respondedFromCache = false;

                    try
                    {
                        message  = DnsMessage.Parse(udpMessage.Buffer);
                        question = message.Questions[0];
                    }
                    catch (Exception)
                    {
                        throw new ParsingException();
                    }

                    // Check for authorized subnet access
                    if (_networkWhitelist != null)
                    {
                        if (_networkWhitelist.All(pair =>
                                                  !pair.Key.GetNetworkAddress(pair.Value)
                                                  .Equals(udpMessage.RemoteEndPoint.Address.GetNetworkAddress(pair.Value))))
                        {
                            Logger.Info("-> {0} is not authorized, who requested {1}.",
                                        udpMessage.RemoteEndPoint.Address,
                                        question);
                            message.ReturnCode = ReturnCode.Refused;
                            message.IsQuery    = false;
                        }
                    }
                    Logger.Info("-> {0} requested {1} (#{2}, {3}).", udpMessage.RemoteEndPoint.Address, question.Name,
                                message.TransactionID, question.RecordType);

                    // Query cache
                    if (Options.CacheResponse)
                    {
                        if (Cache.ContainsKey(question.Name) && Cache[question.Name].ContainsKey(question.RecordType))
                        {
                            var entry = Cache[question.Name][question.RecordType];
                            if (!entry.IsExpired)
                            {
                                var cachedMessage = entry.Message;
                                Logger.Info("-> #{0} {2} served from cache.", message.TransactionID,
                                            cachedMessage.TransactionID, question.Name);
                                cachedMessage.TransactionID = message.TransactionID; // Update transaction ID
                                cachedMessage.TSigOptions   = message.TSigOptions;   // Update TSig options
                                message            = cachedMessage;
                                respondedFromCache = true;
                            }
                        }
                    }

                    var targetNameServer       = Options.DefaultNameServer;
                    var useHttpQuery           = Options.UseHttpQuery;
                    var queryTimeout           = Options.QueryTimeout;
                    var useCompressionMutation = Options.CompressionMutation;

                    // Match rules
                    if (message.IsQuery &&
                        (question.RecordType == RecordType.A || question.RecordType == RecordType.Aaaa || question.RecordType == RecordType.Ptr))
                    {
                        for (var i = Rules.Count - 1; i >= 0; i--)
                        {
                            var match = Regex.Match(question.Name, Rules[i].Pattern);
                            if (!match.Success)
                            {
                                continue;
                            }

                            // Domain name matched

                            var recordType = question.RecordType;
                            if (Rules[i].ForceAAAA != null && Rules[i].ForceAAAA.Value) // RecordType override
                            {
                                recordType = RecordType.Aaaa;
                            }

                            if (Rules[i].NameServer != null) // Name server override
                            {
                                targetNameServer = Rules[i].NameServer;
                            }

                            if (Rules[i].UseHttpQuery != null) // HTTP query override
                            {
                                useHttpQuery = Rules[i].UseHttpQuery.Value;
                            }

                            if (Rules[i].QueryTimeout != null) // Query timeout override
                            {
                                queryTimeout = Rules[i].QueryTimeout.Value;
                            }

                            if (Rules[i].CompressionMutation != null) // Compression pointer mutation override
                            {
                                useCompressionMutation = Rules[i].CompressionMutation.Value;
                            }

                            if (Rules[i].Address != null)
                            {
                                IPAddress ip;
                                IPAddress.TryParse(Rules[i].Address, out ip);
                                if (ip == null) // Invalid IP, may be a domain name
                                {
                                    var address = string.Format(Rules[i].Address, match.Groups.Cast <object>().ToArray());
                                    if (recordType == RecordType.A && useHttpQuery)
                                    {
                                        await ResolveWithHttp(targetNameServer, address, queryTimeout, message);
                                    }
                                    else if (recordType == RecordType.Ptr)
                                    {
                                        var answerRecord = new PtrRecord(question.Name, 600, Rules[i].Address);
                                        message.AnswerRecords.Add(answerRecord);
                                        message.ReturnCode = ReturnCode.NoError;
                                        message.IsQuery    = false;
                                    }
                                    else
                                    {
                                        var serverEndpoint = Utils.CreateIpEndPoint(targetNameServer, 53);
                                        var dnsClient      = new DnsClient(serverEndpoint.Address, queryTimeout,
                                                                           serverEndpoint.Port);
                                        var response =
                                            await
                                            Task <DnsMessage> .Factory.FromAsync(dnsClient.BeginResolve,
                                                                                 dnsClient.EndResolve,
                                                                                 address, recordType, question.RecordClass, null);
                                        if (response == null)
                                        {
                                            Logger.Warning($"Remote resolve failed for {address}.");
                                            return;
                                        }
                                        foreach (var answerRecord in response.AnswerRecords)
                                        {
                                            answerRecord.Name = question.Name;
                                            message.AnswerRecords.Add(answerRecord);
                                        }
                                        message.ReturnCode = response.ReturnCode;
                                        message.IsQuery    = false;
                                    }
                                }
                                else
                                {
                                    if (recordType == RecordType.A &&
                                        ip.AddressFamily == AddressFamily.InterNetwork)
                                    {
                                        message.AnswerRecords.Add(new ARecord(question.Name, 600, ip));
                                    }
                                    else if (recordType == RecordType.Aaaa &&
                                             ip.AddressFamily == AddressFamily.InterNetworkV6)
                                    {
                                        message.AnswerRecords.Add(new AaaaRecord(question.Name, 600, ip));
                                    }
                                    else // Type mismatch
                                    {
                                        continue;
                                    }

                                    message.ReturnCode = ReturnCode.NoError;
                                    message.IsQuery    = false;
                                }
                            }

                            break;
                        }
                    }

                    // TODO: Consider how to integrate System.Net.Dns with this project.
                    // Using System.Net.Dns to forward query if compression mutation is disabled
                    //if (message.IsQuery && !useCompressionMutation &&
                    //    (question.RecordType == RecordType.A || question.RecordType == RecordType.Aaaa))
                    //{
                    //    var dnsResponse = await Dns.GetHostAddressesAsync(question.Name);

                    //    if (question.RecordType == RecordType.A)
                    //    {
                    //        message.AnswerRecords.AddRange(dnsResponse.Where(
                    //            ip => ip.AddressFamily == AddressFamily.InterNetwork).Select(
                    //                ip => new ARecord(question.Name, 0, ip)));
                    //    else if (question.RecordType == RecordType.Aaaa)
                    //    {
                    //        message.AnswerRecords.AddRange(dnsResponse.Where(
                    //            ip => ip.AddressFamily == AddressFamily.InterNetworkV6).Select(
                    //                ip => new AaaaRecord(question.Name, 0, ip)));
                    //    }
                    //    message.ReturnCode = ReturnCode.NoError;
                    //    message.IsQuery = false;
                    //}

                    if (message.IsQuery && question.RecordType == RecordType.A && useHttpQuery)
                    {
                        await ResolveWithHttp(targetNameServer, question.Name, queryTimeout, message);
                    }

                    if (message.IsQuery)
                    {
                        // Use internal forwarder to forward query to another name server
                        await ForwardMessage(message, udpMessage, Utils.CreateIpEndPoint(targetNameServer, 53),
                                             queryTimeout, useCompressionMutation);
                    }
                    else
                    {
                        // Already answered, directly return to the client
                        byte[] responseBuffer;
                        message.Encode(false, out responseBuffer);
                        if (responseBuffer != null)
                        {
                            await
                            _udpListener.SendAsync(responseBuffer, responseBuffer.Length, udpMessage.RemoteEndPoint);

                            // Update cache
                            if (Options.CacheResponse && !respondedFromCache)
                            {
                                Cache.Update(question, message, Options.CacheAge);
                            }
                        }
                    }
                }
                catch (ParsingException)
                {
                }
                catch (SocketException e)
                {
                    Logger.Error("[Listener.Send] Unexpected socket error:\n{0}", e);
                }
                catch (Exception e)
                {
                    Logger.Error("[Processor] Unexpected exception:\n{0}", e);
                }
            });
        }
Example #42
0
        protected virtual void OnResolutionSucceeded(DnsClient.Response response, IEnumerable<DnsClient.DNS.RR> matching)
        {
            foreach (DnsClient.DNS.RR rr in matching)
              {
            Logging.LogMessage message;

            // try to find logging method by QTYPE
            string methodName = String.Format(
              "ResourceRecordFound{0}", rr.Base.TYPE.ToString());
            MethodInfo method;
            if (!object.ReferenceEquals(null, (method = typeof(
              Logging.LogMessageText.RESPONSE.INFO).GetMethod(methodName,
              BindingFlags.Static | BindingFlags.Public))))
            {
              message = (Logging.LogMessage)method.Invoke(null, new object[] { response, rr });
            }
            else
            {
              message = Logging.LogMessageText.RESPONSE.INFO.ResourceRecordFound(response, rr);
            }

            LogMessageCreate(message);
              }
        }
Example #43
0
 /// <summary>
 /// Mailbox eXchange
 /// </summary>
 /// <param name="Name">Name</param>
 /// <param name="Type">Resource Record Type</param>
 /// <param name="Class">Resource Record Class</param>
 /// <param name="Ttl">Time to live</param>
 /// <param name="Data">RR-specific binary data.</param>
 public MX(string Name, TYPE Type, CLASS Class, uint Ttl, Stream Data)
     : base(Name, Type, Class, Ttl)
 {
     this.preference = DnsClient.ReadUInt16(Data);
     this.exchange   = DnsClient.ReadName(Data);
 }
Example #44
0
 // sub iterators: Address / CName
 protected ResolutionIterator(DomainResolver resolver, DnsClient.DNS.QTYPE question, Caching.AddressCache addressCache, int nestingLevel)
     : base(resolver, question, addressCache)
 {
     this.NestingLevel = nestingLevel;
 }
        public override void ExecuteCmdlet()
        {
            bool         deleted           = false;
            DnsRecordSet recordSetToDelete = null;

            if (this.ParameterSetName == "Fields")
            {
                if (this.Name.EndsWith("."))
                {
                    this.Name = this.Name.TrimEnd('.');
                    this.WriteWarning(string.Format("Modifying recordset name to remove terminating '.'.  Recordset name used is \"{0}\".", this.Name));
                }

                recordSetToDelete = new DnsRecordSet
                {
                    Name              = this.Name,
                    Etag              = null,
                    RecordType        = this.RecordType,
                    ResourceGroupName = this.ResourceGroupName,
                    ZoneName          = this.ZoneName,
                };
            }
            else if (this.ParameterSetName == "Mixed")
            {
                if (this.Name.EndsWith("."))
                {
                    this.Name = this.Name.TrimEnd('.');
                    this.WriteWarning(string.Format("Modifying recordset name to remove terminating '.'.  Recordset name used is \"{0}\".", this.Name));
                }

                recordSetToDelete = new DnsRecordSet
                {
                    Name              = this.Name,
                    Etag              = null,
                    RecordType        = this.RecordType,
                    ResourceGroupName = this.Zone.ResourceGroupName,
                    ZoneName          = this.Zone.Name,
                };
            }
            else if (this.ParameterSetName == "Object")
            {
                if ((string.IsNullOrWhiteSpace(this.RecordSet.Etag) || this.RecordSet.Etag == "*") && !this.Overwrite.IsPresent)
                {
                    throw new PSArgumentException(string.Format(ProjectResources.Error_EtagNotSpecified, typeof(DnsRecordSet).Name));
                }

                recordSetToDelete = this.RecordSet;
            }

            if (recordSetToDelete.ZoneName != null && recordSetToDelete.ZoneName.EndsWith("."))
            {
                recordSetToDelete.ZoneName = recordSetToDelete.ZoneName.TrimEnd('.');
                this.WriteWarning(string.Format("Modifying zone name to remove terminating '.'.  Zone name used is \"{0}\".", recordSetToDelete.ZoneName));
            }

            bool overwrite = this.Overwrite.IsPresent || this.ParameterSetName != "Object";

            ConfirmAction(
                ProjectResources.Progress_RemovingRecordSet,
                this.Name,
                () =>
            {
                deleted = DnsClient.DeleteDnsRecordSet(recordSetToDelete, overwrite);
                if (deleted)
                {
                    WriteVerbose(ProjectResources.Success);
                    WriteVerbose(ProjectResources.Success_RemoveRecordSet);
                }

                if (this.PassThru)
                {
                    WriteObject(deleted);
                }
            });
        }
Example #46
0
 // The connectivity state may have get lost, e.g. during serialization.
 private void EnsureConnection(DnsClient.IDnsClient client)
 {
     Resolver.Connect(client);
 }
Example #47
0
        /// <summary>
        /// CommandEcho
        /// </summary>
        /// <param name="arguments">Arguments</param>
        public override ReturnInfo Execute(List <string> arguments)
        {
            int PacketSent     = 0;
            int PacketReceived = 0;
            int PacketLost     = 0;
            int PercentLoss;

            Address source;
            Address destination = Address.Parse(arguments[0]);

            if (destination != null)
            {
                source = IPConfig.FindNetwork(destination);
            }
            else //Make a DNS request if it's not an IP
            {
                var xClient = new DnsClient();
                xClient.Connect(DNSConfig.Server(0));
                xClient.SendAsk(arguments[0]);
                destination = xClient.Receive();
                xClient.Close();

                if (destination == null)
                {
                    return(new ReturnInfo(this, ReturnCode.ERROR, "Failed to get DNS response for " + arguments[0]));
                }

                source = IPConfig.FindNetwork(destination);
            }

            try
            {
                Console.WriteLine("Sending ping to " + destination.ToString());

                var xClient = new ICMPClient();
                xClient.Connect(destination);

                for (int i = 0; i < 4; i++)
                {
                    xClient.SendEcho();

                    PacketSent++;

                    var endpoint = new EndPoint(Address.Zero, 0);

                    int second = xClient.Receive(ref endpoint, 4000);

                    if (second == -1)
                    {
                        Console.WriteLine("Destination host unreachable.");
                        PacketLost++;
                    }
                    else
                    {
                        if (second < 1)
                        {
                            Console.WriteLine("Reply received from " + endpoint.address.ToString() + " time < 1s");
                        }
                        else if (second >= 1)
                        {
                            Console.WriteLine("Reply received from " + endpoint.address.ToString() + " time " + second + "s");
                        }

                        PacketReceived++;
                    }
                }

                xClient.Close();
            }
            catch
            {
                return(new ReturnInfo(this, ReturnCode.ERROR, "Ping process error."));
            }

            PercentLoss = 25 * PacketLost;

            Console.WriteLine();
            Console.WriteLine("Ping statistics for " + destination.ToString() + ":");
            Console.WriteLine("    Packets: Sent = " + PacketSent + ", Received = " + PacketReceived + ", Lost = " + PacketLost + " (" + PercentLoss + "% loss)");

            return(new ReturnInfo(this, ReturnCode.OK));
        }
Example #48
0
 private void OnSubIteratorLogMessage(Object sender, DnsClient.Logging.LogMessageEventArgs e)
 {
     if (LogMessageCreated != null)
       {
     LogMessageCreated(sender, e);
       }
 }
Example #49
0
        /// <summary>
        /// Gets the reverse lookup FQDN of the given IP Address.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="dnsServer">The DNS server.</param>
        /// <param name="port">The port.</param>
        /// <returns>A <see cref="System.String" /> that represents the current object.</returns>
        public static Task <string> GetDnsPointerEntryAsync(IPAddress query, IPAddress dnsServer, int port)
        {
            var client = new DnsClient(dnsServer, port);

            return(client.Reverse(query));
        }
Example #50
0
        public void Configure(IApplicationBuilder app, IHostEnvironment env)
        {
            int staticFilesCachePeriod;

            if (env.IsDevelopment())
            {
                staticFilesCachePeriod = 60;
                app.UseDeveloperExceptionPage();
            }
            else
            {
                staticFilesCachePeriod = 14400;
            }

            app.UseDefaultFiles();
            app.UseStaticFiles(new StaticFileOptions()
            {
                OnPrepareResponse = delegate(StaticFileResponseContext ctx)
                {
                    ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={staticFilesCachePeriod}");
                }
            });

            app.Run(async(context) =>
            {
                HttpRequest request   = context.Request;
                HttpResponse response = context.Response;

                if (request.Path == "/api/dnsclient/")
                {
                    try
                    {
                        string server = request.Query["server"];
                        string domain = request.Query["domain"];
                        DnsResourceRecordType type = (DnsResourceRecordType)Enum.Parse(typeof(DnsResourceRecordType), request.Query["type"], true);

                        domain = domain.Trim();

                        if (domain.EndsWith("."))
                        {
                            domain = domain.Substring(0, domain.Length - 1);
                        }

                        bool preferIpv6        = Configuration.GetValue <bool>("PreferIpv6");
                        bool randomizeName     = false;
                        bool qnameMinimization = false;
                        int retries            = Configuration.GetValue <int>("Retries");
                        int timeout            = Configuration.GetValue <int>("Timeout");

                        DnsDatagram dnsResponse;

                        if (server == "recursive-resolver")
                        {
                            DnsQuestionRecord question;

                            if ((type == DnsResourceRecordType.PTR) && IPAddress.TryParse(domain, out IPAddress address))
                            {
                                question = new DnsQuestionRecord(address, DnsClass.IN);
                            }
                            else
                            {
                                question = new DnsQuestionRecord(domain, type, DnsClass.IN);
                            }

                            dnsResponse = await DnsClient.RecursiveResolveAsync(question, null, null, preferIpv6, randomizeName, qnameMinimization, retries, timeout);
                        }
                        else
                        {
                            DnsTransportProtocol protocol = (DnsTransportProtocol)Enum.Parse(typeof(DnsTransportProtocol), request.Query["protocol"], true);

                            if ((protocol == DnsTransportProtocol.Tls) && !server.Contains(":853"))
                            {
                                server += ":853";
                            }

                            NameServerAddress nameServer = new NameServerAddress(server, protocol);

                            if (nameServer.IPEndPoint == null)
                            {
                                await nameServer.ResolveIPAddressAsync(null, null, preferIpv6);
                            }
                            else if (nameServer.DomainEndPoint == null)
                            {
                                try
                                {
                                    await nameServer.ResolveDomainNameAsync(null, null, preferIpv6);
                                }
                                catch
                                { }
                            }

                            DnsClient dnsClient = new DnsClient(nameServer);

                            dnsClient.PreferIPv6    = preferIpv6;
                            dnsClient.RandomizeName = randomizeName;
                            dnsClient.Retries       = retries;
                            dnsClient.Timeout       = timeout;

                            dnsResponse = await dnsClient.ResolveAsync(domain, type);
                        }

                        string jsonResponse = JsonConvert.SerializeObject(dnsResponse, new StringEnumConverter());

                        response.Headers.Add("Content-Type", "application/json; charset=utf-8");
                        await response.WriteAsync("{\"status\":\"ok\", \"response\":" + jsonResponse + "}");
                    }
                    catch (Exception ex)
                    {
                        string jsonResponse = JsonConvert.SerializeObject(ex);

                        response.Headers.Add("Content-Type", "application/json; charset=utf-8");
                        await response.WriteAsync("{\"status\":\"error\", \"response\":" + jsonResponse + "}");
                    }
                }
            });
        }
Example #51
0
        private async Task <bool> RefreshZoneAsync(IReadOnlyList <NameServerAddress> primaryNameServers)
        {
            try
            {
                {
                    LogManager log = _dnsServer.LogManager;
                    if (log != null)
                    {
                        log.Write("DNS Server has started zone refresh for stub zone: " + _name);
                    }
                }

                DnsClient client = new DnsClient(primaryNameServers);
                client.Timeout = REFRESH_TIMEOUT;
                client.Retries = REFRESH_RETRIES;

                DnsDatagram soaRequest  = new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, false, false, false, false, DnsResponseCode.NoError, new DnsQuestionRecord[] { new DnsQuestionRecord(_name, DnsResourceRecordType.SOA, DnsClass.IN) });
                DnsDatagram soaResponse = await client.ResolveAsync(soaRequest);

                if (soaResponse.RCODE != DnsResponseCode.NoError)
                {
                    LogManager log = _dnsServer.LogManager;
                    if (log != null)
                    {
                        log.Write("DNS Server received RCODE=" + soaResponse.RCODE.ToString() + " for '" + _name + "' stub zone refresh from: " + soaResponse.Metadata.NameServerAddress.ToString());
                    }

                    return(false);
                }

                if (soaResponse.Answer.Count < 1)
                {
                    LogManager log = _dnsServer.LogManager;
                    if (log != null)
                    {
                        log.Write("DNS Server received an empty response for SOA query for '" + _name + "' stub zone refresh from: " + soaResponse.Metadata.NameServerAddress.ToString());
                    }

                    return(false);
                }

                DnsSOARecord currentSoaRecord  = _entries[DnsResourceRecordType.SOA][0].RDATA as DnsSOARecord;
                DnsSOARecord receivedSoaRecord = soaResponse.Answer[0].RDATA as DnsSOARecord;

                //compare using sequence space arithmetic
                if (!currentSoaRecord.IsZoneUpdateAvailable(receivedSoaRecord))
                {
                    LogManager log = _dnsServer.LogManager;
                    if (log != null)
                    {
                        log.Write("DNS Server successfully checked for update to '" + _name + "' stub zone from: " + soaResponse.Metadata.NameServerAddress.ToString());
                    }

                    return(true);
                }

                //update available; do zone sync with TCP transport
                List <NameServerAddress> tcpNameServers = new List <NameServerAddress>();

                foreach (NameServerAddress nameServer in primaryNameServers)
                {
                    tcpNameServers.Add(new NameServerAddress(nameServer, DnsTransportProtocol.Tcp));
                }

                primaryNameServers = tcpNameServers;
                client             = new DnsClient(primaryNameServers);
                client.Timeout     = REFRESH_TIMEOUT;
                client.Retries     = REFRESH_RETRIES;

                DnsDatagram nsRequest  = new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, false, false, false, false, DnsResponseCode.NoError, new DnsQuestionRecord[] { new DnsQuestionRecord(_name, DnsResourceRecordType.NS, DnsClass.IN) });
                DnsDatagram nsResponse = await client.ResolveAsync(nsRequest);

                if (nsResponse.RCODE != DnsResponseCode.NoError)
                {
                    LogManager log = _dnsServer.LogManager;
                    if (log != null)
                    {
                        log.Write("DNS Server received RCODE=" + nsResponse.RCODE.ToString() + " for '" + _name + "' stub zone refresh from: " + nsResponse.Metadata.NameServerAddress.ToString());
                    }

                    return(false);
                }

                if (nsResponse.Answer.Count < 1)
                {
                    LogManager log = _dnsServer.LogManager;
                    if (log != null)
                    {
                        log.Write("DNS Server received an empty response for NS query for '" + _name + "' stub zone from: " + nsResponse.Metadata.NameServerAddress.ToString());
                    }

                    return(false);
                }

                List <DnsResourceRecord> allRecords = new List <DnsResourceRecord>();

                allRecords.AddRange(nsResponse.Answer);
                allRecords.AddRange(soaResponse.Answer); //to sync latest SOA record

                _dnsServer.AuthZoneManager.SyncRecords(_name, allRecords, nsResponse.Additional, true);

                {
                    LogManager log = _dnsServer.LogManager;
                    if (log != null)
                    {
                        log.Write("DNS Server successfully refreshed '" + _name + "' stub zone from: " + nsResponse.Metadata.NameServerAddress.ToString());
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                LogManager log = _dnsServer.LogManager;
                if (log != null)
                {
                    string strNameServers = null;

                    foreach (NameServerAddress nameServer in primaryNameServers)
                    {
                        if (strNameServers == null)
                        {
                            strNameServers = nameServer.ToString();
                        }
                        else
                        {
                            strNameServers += ", " + nameServer.ToString();
                        }
                    }

                    log.Write("DNS Server failed to refresh '" + _name + "' stub zone from: " + strNameServers);
                    log.Write(ex);
                }

                return(false);
            }
        }
Example #52
0
 public CustomDnsResolver()
 {
     _client = new DnsClient("1.1.1.1");
 }
        protected override WebRequest GetWebRequest(Uri address)
        {
            HttpWebRequest request = null;

            if (_proxy == null)
            {
                switch (_networkType)
                {
                case WebClientExNetworkType.IPv4Only:
                    if (IPAddress.TryParse(address.Host, out IPAddress ipv4))
                    {
                        if (ipv4.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            throw new WebException("WebClientEx current network type does not allow url address family: " + ipv4.AddressFamily.ToString());
                        }

                        request = base.GetWebRequest(address) as HttpWebRequest;
                    }
                    else
                    {
                        try
                        {
                            DnsClient   dns         = new DnsClient();
                            IPAddress[] ipAddresses = dns.ResolveIP(address.Host);

                            if (ipAddresses.Length == 0)
                            {
                                throw new WebException("WebClientEx could not resolve IPv4 address for host: " + address.Host);
                            }

                            foreach (IPAddress ipAddress in ipAddresses)
                            {
                                if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                                {
                                    Uri newAddress = new Uri(address.Scheme + "://" + ipAddress.ToString() + ":" + address.Port + address.PathAndQuery);
                                    request      = base.GetWebRequest(newAddress) as HttpWebRequest;
                                    request.Host = address.Host;
                                    break;
                                }
                            }
                        }
                        catch (DnsClientException ex)
                        {
                            throw new WebException("WebClientEx could not resolve IPv4 address for host: " + address.Host, ex);
                        }

                        if (request == null)
                        {
                            throw new WebException("WebClientEx could not resolve IPv4 address for host: " + address.Host);
                        }
                    }
                    break;

                case WebClientExNetworkType.IPv6Only:
                    if (IPAddress.TryParse(address.Host, out IPAddress ipv6))
                    {
                        if (ipv6.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6)
                        {
                            throw new WebException("WebClientEx current network type does not allow url address family: " + ipv6.AddressFamily.ToString());
                        }

                        request = base.GetWebRequest(address) as HttpWebRequest;
                    }
                    else
                    {
                        try
                        {
                            DnsClient   dns         = new DnsClient(true);
                            IPAddress[] ipAddresses = dns.ResolveIP(address.Host, true);

                            if (ipAddresses.Length == 0)
                            {
                                throw new WebException("WebClientEx could not resolve IPv6 address for host: " + address.Host);
                            }

                            foreach (IPAddress ipAddress in ipAddresses)
                            {
                                if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                                {
                                    Uri newAddress = new Uri(address.Scheme + "://[" + ipAddress.ToString() + "]:" + address.Port + address.PathAndQuery);
                                    request      = base.GetWebRequest(newAddress) as HttpWebRequest;
                                    request.Host = address.Host;
                                    break;
                                }
                            }
                        }
                        catch (DnsClientException ex)
                        {
                            throw new WebException("WebClientEx could not resolve IPv6 address for host: " + address.Host, ex);
                        }

                        if (request == null)
                        {
                            throw new WebException("WebClientEx could not resolve IPv6 address for host: " + address.Host);
                        }
                    }
                    break;

                default:
                    request = base.GetWebRequest(address) as HttpWebRequest;
                    break;
                }
            }
            else
            {
                switch (_proxy.Type)
                {
                case NetProxyType.Http:
                    request       = base.GetWebRequest(address) as HttpWebRequest;
                    request.Proxy = _proxy.HttpProxy;
                    break;

                case NetProxyType.Socks5:
                    _proxyRequestHandler = _proxy.SocksProxy.Connect(address.Host, address.Port);

                    if (address.Scheme == "https")
                    {
                        IWebProxy httpProxy = _proxyRequestHandler.CreateLocalHttpProxyConnectTunnel();

                        request       = base.GetWebRequest(address) as HttpWebRequest;
                        request.Proxy = httpProxy;
                    }
                    else
                    {
                        IPEndPoint localTunnelEP = _proxyRequestHandler.CreateLocalTunnel();
                        Uri        proxyUri      = new Uri("http://" + localTunnelEP.Address.ToString() + ":" + localTunnelEP.Port + address.PathAndQuery);

                        request      = base.GetWebRequest(proxyUri) as HttpWebRequest;
                        request.Host = address.Host;
                    }
                    break;

                default:
                    throw new NotSupportedException("Proxy type not supported.");
                }
            }

            if (_timeout > 0)
            {
                request.Timeout = _timeout;
            }

            request.CookieContainer = _cookie;

            if (_ifModifiedSince > (new DateTime()))
            {
                request.IfModifiedSince = _ifModifiedSince;
            }

            if (_userAgent != null)
            {
                request.UserAgent = _userAgent;
            }

            request.KeepAlive = _keepAlive;

            request.AllowAutoRedirect = false;

            foreach (KeyValuePair <string, string> header in _headers)
            {
                switch (header.Key.ToLower())
                {
                case "accept":
                    request.Accept = header.Value;
                    break;

                case "connection":
                    request.KeepAlive = (header.Value.ToLower() == "keep-alive");
                    break;

                case "content-type":
                    request.ContentType = header.Value;
                    break;

                case "user-agent":
                    request.UserAgent = header.Value;
                    break;

                default:
                    request.Headers.Add(header.Key, header.Value);
                    break;
                }
            }

            return(request);
        }
Example #54
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string server = Request.QueryString["server"];
                string domain = Request.QueryString["domain"];
                DnsResourceRecordType type = (DnsResourceRecordType)Enum.Parse(typeof(DnsResourceRecordType), Request.QueryString["type"]);

                DnsDatagram dnsResponse;

                if (server == "root-servers")
                {
                    dnsResponse = DnsClient.ResolveViaRootNameServers(domain, type, new SimpleDnsCache(), null, PREFER_IPv6, TCP, RETRIES, MAX_STACK_COUNT);
                }
                else
                {
                    NameServerAddress[] nameServers;

                    if (IPAddress.TryParse(server, out IPAddress serverIP))
                    {
                        string serverDomain = null;

                        try
                        {
                            serverDomain = (new DnsClient()
                            {
                                PreferIPv6 = PREFER_IPv6, Tcp = TCP, Retries = RETRIES
                            }).ResolvePTR(serverIP);
                        }
                        catch
                        { }

                        nameServers = new NameServerAddress[] { new NameServerAddress(serverDomain, serverIP) };
                    }
                    else
                    {
                        IPAddress[] serverIPs = (new DnsClient()
                        {
                            PreferIPv6 = PREFER_IPv6, Tcp = TCP, Retries = RETRIES
                        }).ResolveIP(server, PREFER_IPv6);

                        nameServers = new NameServerAddress[serverIPs.Length];

                        for (int i = 0; i < serverIPs.Length; i++)
                        {
                            nameServers[i] = new NameServerAddress(server, serverIPs[i]);
                        }
                    }

                    dnsResponse = (new DnsClient(nameServers)
                    {
                        PreferIPv6 = PREFER_IPv6, Tcp = TCP, Retries = RETRIES
                    }).Resolve(domain, type);
                }

                string jsonResponse = JsonConvert.SerializeObject(dnsResponse, new StringEnumConverter());

                Response.AddHeader("Content-Type", "application/json; charset=utf-8");
                Response.Write("{\"status\":\"ok\", \"response\":" + jsonResponse + "}");
            }
            catch (Exception ex)
            {
                string jsonResponse = JsonConvert.SerializeObject(ex);

                Response.AddHeader("Content-Type", "application/json; charset=utf-8");
                Response.Write("{\"status\":\"error\", \"response\":" + jsonResponse + "}");
            }
        }
Example #55
0
 public DnsLookup()
 {
     _dnsClient    = DnsClient.Default;
     _sDnsResolver = new DnsStubResolver(_dnsClient);
 }
Example #56
0
 /// <summary>
 /// Create a new request iterator for resolving the specified question.
 /// </summary>
 /// <param name="question">The question to resolve.</param>
 /// <returns></returns>
 public Iterators.ResolutionIterator GetIterator(DnsClient.DNS.QTYPE question)
 {
     return new Iterators.ResolutionIterator(this, question, new Caching.AddressCache());
 }