DnsResponse ProcessRequest(DnsRequest request)
        {
            DnsStandard.RecordType questionType = request.Question.Type;
            DnsResponse            response     = new DnsResponse(request);

            response.Header.IsAuthoritativeAnswer = true;

            switch (response.Question.Type)
            {
            default:
                throw new DnsServerException(DnsStandard.ResponseCode.NotImplemented);

            case DnsStandard.RecordType.ANAME:
                ProcessANAMEQuestion(response);
                break;

            case DnsStandard.RecordType.NS:
                ProcessNSQuestion(response);
                break;

            case DnsStandard.RecordType.MX:
                ProcessMXQuestion(response);
                break;

            case DnsStandard.RecordType.SOA:
                ProcessSOAQuestion(response);
                break;

            case DnsStandard.RecordType.CERT:
                ProcessCERTQuestion(response);
                break;

            case DnsStandard.RecordType.CNAME:
                ProcessCNAMEQuestion(response);
                break;

            case DnsStandard.RecordType.SRV:
                ProcessSRVQuestion(response);
                break;
            }

            return(response);
        }
Exemple #2
0
        public void DnsResolver_Single_Lookup()
        {
            IPAddress   dnsEP = GetDns();
            DnsRequest  request;
            DnsResponse response;

            IPAddress[]      stdAddrs;
            List <IPAddress> addrs;

            // This test assumes that www.lilltek.com maps to
            // a single IP address.  I'm going to compare the
            // address I get back from the standard Dns class
            // with what I get back from DnsResolver.

            stdAddrs = Dns.GetHostAddresses("www.lilltek.com.");
            if (stdAddrs.Length != 1)
            {
                Assert.Inconclusive("www.lilltek.com is configured with multiple A records.");
            }

            request  = new DnsRequest(DnsFlag.RD, "www.lilltek.com.", DnsQType.A);
            response = DnsResolver.Query(dnsEP, request, timeout);

            if ((response.Flags & DnsFlag.RA) == 0)
            {
                Assert.Inconclusive(NoRecursionMsg);
            }

            Assert.AreEqual(DnsFlag.RCODE_OK, response.RCode);

            addrs = new List <IPAddress>();
            for (int i = 0; i < response.Answers.Count; i++)
            {
                if (response.Answers[i].RRType == DnsRRType.A)
                {
                    addrs.Add(((A_RR)response.Answers[i]).Address);
                }
            }

            Assert.AreEqual(1, addrs.Count);
            Assert.AreEqual(stdAddrs[0], addrs[0]);
        }
Exemple #3
0
        public DnsResponse ProcessRequest(DnsRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException();
            }

            this.Received.SafeInvoke(request);

            DnsResponse response = null;

            try
            {
                this.Validate(request);

                response = m_store.Get(request);
                if (response == null || !response.IsSuccess)
                {
                    throw new DnsServerException(DnsStandard.ResponseCode.NameError);
                }

                this.FixupTTL(response);
            }
            catch (DnsProtocolException)
            {
                response = this.ProcessError(request, DnsStandard.ResponseCode.FormatError);
            }
            catch (DnsServerException serverEx)
            {
                response = this.ProcessError(request, serverEx.ResponseCode);
            }
            catch (Exception ex)
            {
                this.HandleException(ex);
                response = this.ProcessError(request, DnsStandard.ResponseCode.ServerFailure);
            }

            this.Responding.SafeInvoke(response);

            return(response);
        }
        public DnsResponse Get(DnsRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException();
            }

            DnsQuestion question = request.Question;

            if (question == null || question.Class != DnsStandard.Class.IN)
            {
                throw new DnsServerException(DnsStandard.ResponseCode.NotImplemented);
            }

            DnsResponse response = this.ProcessRequest(request);

            //
            // Usually need some post-processing on the response
            //
            return(this.ProcessResponse(response));
        }
Exemple #5
0
        public SocketHelper(DnsRequest request, string server, TimeSpan timeout)
        {
            try
            {
                IPAddress ip;
                IPAddress.TryParse(server, out ip);

                if (ip == null)
                {
                    IPAddress.TryParse(Dns.GetHostEntry(server).AddressList[0].ToString(), out ip);
                }

                _server = new IPEndPoint(ip, 53);
            }
            catch
            {
                throw new InvalidNameserverException(server);
            }

            _request = request;
            _timeout = timeout;
        }
Exemple #6
0
        /// <summary>
        /// Look up a DNS SRV record, returning the best host and port number to connect to.
        /// </summary>
        /// <param name="prefix">The SRV prefix, ending with a dot.  Example: "_xmpp-client._tcp."</param>
        /// <param name="domain">The domain to check</param>
        /// <param name="host">The host name to connect to</param>
        /// <param name="port">The port number to connect to</param>
        public static void LookupSRV(string prefix, string domain, ref string host, ref int port)
        {
            if (prefix == null)
            {
                throw new ArgumentNullException("prefix");
            }
            if (domain == null)
            {
                throw new ArgumentNullException("domain");
            }
            if (!prefix.EndsWith("."))
            {
                throw new ArgumentOutOfRangeException("Prefix must end in '.'", "prefix");
            }
            try
            {
                SRVRecord record;

                if (Environment.OSVersion.Platform != PlatformID.Unix)
                {
                    DnsRequest  request  = new DnsRequest(prefix + domain);
                    DnsResponse response = request.GetResponse(DnsRecordType.SRV);
                    record = PickSRV(response.SRVRecords);
                }
                else
                {
                    var records = UnixDnsResolver.ResolveSRV(prefix + domain);
                    record = PickSRV(records);
                }
                host = record.NameNext;
                port = record.Port;

                Debug.WriteLine(string.Format("SRV found: {0}:{1}", host, port));
            }
            catch
            {
                host = domain;
            }
        }
Exemple #7
0
        protected virtual bool OnRequest(DnsRequest request, EndPoint remoteEP)
        {
            var pac = this.m_poTUN2Socks.GetPAC();
            if (!pac.IsReady())
            {
                return this.SuperiorAcquired(request, (message, response) => this.SendTo(response.ToArray(), remoteEP));
            }
            lock (this.m_poDnsMap)
            {
                this.m_poDnsMap.TryGetValue(request.Domain, out IPAddress address);
                if (address != null)
                {
                    return this.SendTo(this.CreateResponse(request, address).ToArray(), remoteEP);
                }
            }
            return this.SuperiorAcquired(request, (message, response) =>
            {
                string hijacked = string.Empty;
                lock (this.m_poDnsMap)
                {
                    //var addresses = DnsResponse.GetAddresses(response.Answers);
                    //if (!this.IsNotAllowAgent(addresses))
                    {
                        hijacked = "[:hijacked] ";

                        IPAddress address = this.NewVirtualAddress();
                        {
                            this.m_poDnsMap[request.Domain] = address;
                            this.m_poDnsMapFar[address] = request.Domain;
                        }
                        response = this.CreateResponse(request, address);
                    }
                }

                TUN2Socks.PrintTraceLine($"NSLookup[{request.QueryType}, {request.QueryClass}]: {request.Domain} {hijacked}-> {string.Join(" ", DnsResponse.FetchAddresses(response.Answers))}");
                this.SendTo(response.ToArray(), remoteEP);
            });
        }
Exemple #8
0
        /// <summary>
        /// Look up a DNS TXT record.
        /// </summary>
        /// <param name="prefix">The prefix, ending in '.'.  Example: "_xmppconnect."</param>
        /// <param name="domain">The domain to search</param>
        /// <param name="attribute">The attribute name to look for.  Example: "_xmpp-client-xbosh"</param>
        /// <returns></returns>
        public static string LookupTXT(string prefix, string domain, string attribute)
        {
            if (prefix == null)
            {
                throw new ArgumentNullException("prefix");
            }
            if (domain == null)
            {
                throw new ArgumentNullException("domain");
            }
            if (attribute == null)
            {
                throw new ArgumentNullException("attribute");
            }
            if (!prefix.EndsWith("."))
            {
                throw new ArgumentOutOfRangeException("Prefix must end in '.'", "prefix");
            }

            try
            {
                DnsRequest  request  = new DnsRequest(prefix + domain);
                DnsResponse response = request.GetResponse(DnsRecordType.TEXT);
                string      attr     = attribute + "=";
                foreach (TXTRecord txt in response.TXTRecords)
                {
                    if (txt.StringArray.StartsWith(attr))
                    {
                        Debug.WriteLine(string.Format("TXT found: {0}", txt.StringArray));
                        return(txt.StringArray.Substring(attr.Length));
                    }
                }
            }
            catch
            {
            }
            return(null);
        }
Exemple #9
0
        public DnsResponse Get(DnsRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException();
            }

            DnsQuestion question = request.Question;

            if (question == null || question.Class != DnsStandard.Class.IN)
            {
                return(null);
            }

            IEnumerable <DnsResourceRecord> matches = m_records[request.Question.Domain];

            if (matches == null)
            {
                return(null);
            }

            return(this.CreateResponse(request, matches));
        }
Exemple #10
0
        public void DnsSerialization_CNAME_Request()
        {
            // Request packet captured for:
            //
            //      nslookup -type=cname lilltek.com.

            const string raw =
                @" 
                              00 03 01 00 00 01
00 00 00 00 00 00 07 6C 69 6C 6C 74 65 6B 03 63
6F 6D 00 00 05 00 01
";

            byte[]     packet = Helper.FromHex(raw);
            DnsRequest message;

            // Test parsing

            message = new DnsRequest();
            Assert.IsTrue(message.ParsePacket(packet, packet.Length));

            Assert.AreEqual(DnsOpcode.QUERY, message.Opcode);
            Assert.AreEqual(DnsQClass.IN, message.QClass);
            Assert.AreEqual(DnsQType.CNAME, message.QType);
            Assert.AreEqual("lilltek.com.", message.QName);
            Assert.IsTrue((message.Flags & DnsFlag.QR) == 0);
            Assert.IsTrue((message.Flags & DnsFlag.TC) == 0);
            Assert.IsTrue((message.Flags & DnsFlag.RD) != 0);
            Assert.IsTrue((message.Flags & DnsFlag.RA) == 0);

            Assert.AreEqual(0, message.Answers.Count);
            Assert.AreEqual(0, message.Authorities.Count);

            // Test rendering

            CollectionAssert.AreEqual(packet, Serialize(message));
        }
Exemple #11
0
        public void DnsResolver_CancelAll()
        {
            IPAddress    dns = IPAddress.Loopback;
            DnsRequest   request;
            DnsResponse  response;
            IAsyncResult ar;

            // This test sends a DNS request to the loopback address
            // assuming that there is no DNS server running locally
            // and then calls DnsResolver.CancelAll() which should
            // terminate the query with a CancelException.

            request = new DnsRequest(DnsFlag.RD, "www.lilltek.com.", DnsQType.A);
            ar      = DnsResolver.BeginQuery(dns, request, timeout, null, null);

            DnsResolver.CancelAll();
            try
            {
                response = DnsResolver.EndQuery(ar);
                Assert.Fail("Expected a CancelException");
            }
            catch (CancelException)
            {
            }
            catch
            {
                Assert.Fail("Expected a CancelException");
            }
            finally
            {
                Thread.Sleep(1000);     // $todo(jeff.lill):

                // This test causes some problems for some other
                //tests unless I add this (I'm not sure why).
            }
        }
        /// <summary>
        /// overrides base resolve method to provide cache funcationality at time of resolution
        /// </summary>
        /// <param name="request"></param>
        /// <returns>DnsResponse containing the results either pulled from cache or manually resolved</returns>
        public override DnsResponse Resolve(DnsRequest request)
        {
            //----------------------------------------------------------------------------------------------------
            //---check to see if the item is in the cache
            DnsResponse dr = m_cache.Get(request);

            if (dr != null)
            {
                return(dr);
            }

            //----------------------------------------------------------------------------------------------------
            //---item as not found in cache, try to get it from the base class
            dr = base.Resolve(request);
            if (dr != null)
            {
                //----------------------------------------------------------------------------------------------------
                //---if found store in the cache for future use
                //---Potential for negative caching here
                m_cache.Put(dr);
            }

            return(dr);
        }
Exemple #13
0
        /// <summary>
        /// Handles background tasks when operating in UDP mode.
        /// </summary>
        /// <param name="state">Not used.</param>
        private void OnBkTask(object state)
        {
            try
            {
                using (TimedLock.Lock(syncLock))
                {
                    if (!isOpen || settings.Mode != DynDnsMode.Udp)
                    {
                        return;
                    }

                    if (settings.Domain.IsHost && domainRefreshTimer.HasFired)
                    {
                        // Perform a NS lookup for the domain and populate
                        // settings.NameServer with the results.

                        // $todo(jeff.lill):
                        //
                        // Note that I'm going to ignore any CNAME records returned
                        // for now.  It might be important to make sure these are
                        // added to the staticHosts table, but I need to think about
                        // this some more.

                        try
                        {
                            var         nameServers = new Dictionary <IPAddress, bool>();
                            string      qname;
                            DnsRequest  request;
                            DnsResponse response;

                            qname = settings.Domain.Host;
                            if (!qname.EndsWith("."))
                            {
                                qname += ".";
                            }

                            request  = new DnsRequest(DnsFlag.RD, qname, DnsQType.NS);
                            response = DnsResolver.QueryWithRetry(NetHelper.GetDnsServers(), request, TimeSpan.FromMilliseconds(500), 4);

                            if (response.RCode != DnsFlag.RCODE_OK)
                            {
                                SysLog.LogWarning("DynDnsClient: Domain NS query failed with error [{0}].", response.RCode);
                            }
                            else
                            {
                                // Build the set of name server endpoints by resolving the
                                // name server names returned in the NS response into IP addresses.

                                foreach (var answer in response.Answers)
                                {
                                    if (answer.RRType == DnsRRType.NS)
                                    {
                                        NS_RR nsAnswer = (NS_RR)answer;

                                        try
                                        {
                                            foreach (var address in Dns.GetHostAddresses(nsAnswer.NameServer).IPv4Only())
                                            {
                                                if (!nameServers.ContainsKey(address))
                                                {
                                                    nameServers.Add(address, true);
                                                }
                                            }
                                        }
                                        catch
                                        {
                                            // Ignorning
                                        }
                                    }
                                }

                                if (nameServers.Count == 0)
                                {
                                    // Note that I'm going to keep any name server addresses I already have
                                    // in the case where the name server queries above return nothing.  This
                                    // will give us some resiliency in the face of transient network problems, etc.
                                    // I'm going to set the timer to retry in 1 minute in this case.

                                    domainRefreshTimer.ResetTemporary(TimeSpan.FromMinutes(1));
                                }
                                else
                                {
                                    var newServers = new List <NetworkBinding>(nameServers.Count);

                                    foreach (var address in nameServers.Keys)
                                    {
                                        newServers.Add(new IPEndPoint(address, settings.Domain.Port));
                                    }

                                    settings.NameServers = newServers.ToArray();
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            domainRefreshTimer.Reset(TimeSpan.FromSeconds(60));
                            SysLog.LogException(e);
                        }
                    }

                    if (udpRegisterTimer.HasFired)
                    {
                        // It's time to transmit host registrations to the dynamic DNS servers.

                        DynDnsMessage message;
                        byte[]        packet;

                        foreach (var entry in hosts.Values)
                        {
                            message = new DynDnsMessage(DynDnsMessageFlag.OpRegister, entry);
                            packet  = message.ToArray(settings.SharedKey);

                            foreach (var nameServer in settings.NameServers)
                            {
                                socket.SendTo(packet, nameServer);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                SysLog.LogException(e);
            }
        }
Exemple #14
0
        public DnsClientRequest FromArray(byte[] message)
        {
            var request = DnsRequest.FromArray(message);

            return(new DnsClientRequest(dns, request, resolver));
        }
Exemple #15
0
    public override ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        int         sequenceNumber = 0;
        string      context        = "Execute";
        DnsResponse response       = new DnsResponse
        {
            Results = new List <ActionResult>()
        };

        try
        {
            _mainProgressMsg = "Deserializing incoming request...";
            _result.Status   = StatusType.Initializing;
            ++sequenceNumber;
            OnProgress(context, _mainProgressMsg, _result.Status, sequenceNumber);
            OnLogMessage(context, _subProgressMsg);
            DnsRequest parms = DeserializeOrNew <DnsRequest>(startInfo.Parameters);


            _mainProgressMsg = "Processing individual child request...";
            _result.Status   = StatusType.Running;
            ++sequenceNumber;
            OnProgress(context, _mainProgressMsg, _result.Status, sequenceNumber);

            if (parms?.DnsActions != null)
            {
                foreach (DnsActionDetail request in parms.DnsActions)
                {
                    bool subTaskSucceed = false;
                    try
                    {
                        _subProgressMsg = "Verifying child request parameters...";
                        OnLogMessage(context, _subProgressMsg);
                        OnLogMessage(context, request.ToString());

                        if (ValidateActionParameters(request))
                        {
                            _subProgressMsg = "Executing request" + (startInfo.IsDryRun ? " in dry run mode..." : "...");
                            OnLogMessage(context, _subProgressMsg);
                            subTaskSucceed  = ExecuteDnsActions(request, _config, startInfo.IsDryRun);
                            _subProgressMsg = "Processed child request.";
                            OnLogMessage(context, _subProgressMsg);
                        }
                    }
                    catch (Exception ex)
                    {
                        _subProgressMsg = ex.Message;
                        OnLogMessage(context, _subProgressMsg);
                        subTaskSucceed = false;
                    }
                    finally
                    {
                        response.Results.Add(new ActionResult()
                        {
                            Action     = request.Action,
                            RecordType = request.RecordType,
                            Hostname   = request.Hostname,
                            IpAddress  = request.IpAddress,
                            ExitCode   = subTaskSucceed ? 0 : -1,
                            Note       = _subProgressMsg
                        });
                    }
                }
                _result.Status = StatusType.Complete;
            }
            else
            {
                _result.Status   = StatusType.Failed;
                _mainProgressMsg = "No DNS action is found from the incoming request.";
                OnLogMessage(context, _mainProgressMsg, LogLevel.Error);
            }
        }
        catch (Exception ex)
        {
            _result.Status   = StatusType.Failed;
            _mainProgressMsg = $"Execution has been aborted due to: {ex.Message}";
            OnLogMessage(context, _mainProgressMsg, LogLevel.Error);
        }

        _mainProgressMsg = startInfo.IsDryRun ? "Dry run execution is completed." : "Execution is completed.";
        response.Summary = _mainProgressMsg;
        _result.ExitData = JsonConvert.SerializeObject(response);

        OnProgress(context, _mainProgressMsg, _result.Status, int.MaxValue);

        return(_result);
    }
Exemple #16
0
        public void SaveToDatabase(string cid, string offset)
        {
            Detection detection = new Detection();

            detection.AccountId         = GetAccountId();
            detection.CommandLine       = data.CommandLine;
            detection.CustomerId        = GetCustomerId(cid);
            detection.CustomSeverityId  = detection.VendorSeverityId = GetSeverityId();
            detection.Description       = data.DetectDescription;
            detection.DetectionDeviceId = GetDetectionDeviceId();
            detection.FalconHostLink    = data.FalconHostLink;
            detection.FileName          = data.FileName;
            detection.FilePath          = data.FilePath;
            detection.Name             = data.DetectName;
            detection.ResponderId      = data.ResponderId;
            detection.MD5              = data.MD5String;
            detection.Offset           = offset;
            detection.ParentProcessId  = data.ParentProcessId;
            detection.ProcessEndTime   = data.FormattedProcessEndTime;
            detection.ProcessStartTime = data.FormattedProcessStartTime;
            detection.ProcessId        = data.ProcessId;
            detection.SHA1             = data.SHA1String;
            detection.SHA256           = data.SHA256String;
            detection.Timestamp        = DateTime.UtcNow;
            if (data.StatusId.HasValue)
            {
                detection.StatusId = (int)data.StatusId;
            }
            else
            {
                detection.StatusId = 1;
            }

            using (FalconOrchestratorDB db = new FalconOrchestratorDB())
            {
                db.Detections.Add(detection);
                db.SaveChanges();

                if (data.TaxonomyIds != null)
                {
                    foreach (int line in data.TaxonomyIds)
                    {
                        DetectionTaxonomy dt = new DetectionTaxonomy();
                        dt.DetectionId = detection.DetectionId;
                        dt.TaxonomyId  = line;
                        db.DetectionTaxonomies.Add(dt);
                    }
                }

                if (data.DnsRequest != null)
                {
                    foreach (DnsRequestsModel line in data.DnsRequest)
                    {
                        DnsRequest dns = new DnsRequest();
                        dns.CausedDetect   = line.CausedDetect;
                        dns.DetectionId    = detection.DetectionId;
                        dns.DomainName     = line.DomainName;
                        dns.InterfaceIndex = line.InterfaceIndex;
                        dns.RequestType    = line.RequestType;
                        dns.Timestamp      = line.FormattedTimestamp;
                        db.DnsRequests.Add(dns);
                    }
                }

                if (data.DocumentsAccessed != null)
                {
                    foreach (DocumentsAccessedModel line in data.DocumentsAccessed)
                    {
                        DocumentsAccess doc = new DocumentsAccess();
                        doc.Timestamp   = line.FormattedTimestamp;
                        doc.FileName    = line.FileName;
                        doc.FilePath    = line.FilePath;
                        doc.DetectionId = detection.DetectionId;
                        db.DocumentsAccesses.Add(doc);
                    }
                }

                if (data.ExecutablesWritten != null)
                {
                    foreach (ExecutableWrittenModel line in data.ExecutablesWritten)
                    {
                        ExecutablesWritten exe = new ExecutablesWritten();
                        exe.Timestamp   = line.FormattedTimestamp;
                        exe.FileName    = line.FileName;
                        exe.FilePath    = line.FilePath;
                        exe.DetectionId = detection.DetectionId;
                        db.ExecutablesWrittens.Add(exe);
                    }
                }

                if (data.NetworkAccesses != null)
                {
                    foreach (NetworkAccessesModel line in data.NetworkAccesses)
                    {
                        NetworkAccess network = new NetworkAccess();
                        network.Timestamp           = line.FormattedTimestamp;
                        network.AccessType          = line.AccessType;
                        network.ConnectionDirection = line.ConnectionDirection;
                        network.IsIPv6        = line.IsIPV6;
                        network.LocalAddress  = line.LocalAddress;
                        network.LocalPort     = line.LocalPort;
                        network.Protocol      = line.Protocol;
                        network.RemoteAddress = line.RemoteAddress;
                        network.RemotePort    = line.RemotePort;
                        network.DetectionId   = detection.DetectionId;
                        db.NetworkAccesses.Add(network);
                    }
                }

                if (data.ScanResults != null)
                {
                    foreach (ScanResultsModel line in data.ScanResults)
                    {
                        ScanResult scan = new ScanResult();
                        scan.DetectionId = detection.DetectionId;
                        scan.Engine      = line.Engine;
                        scan.ResultName  = line.ResultName;
                        scan.Version     = line.Version;
                        db.ScanResults.Add(scan);
                    }
                }
                db.SaveChanges();
                AppConfiguration.FALCON_STREAM_LAST_OFFSET = offset;
            }
        }
Exemple #17
0
 public void TestCert(string domain)
 {
     Resolve(DnsRequest.CreateCERT(domain));
 }
Exemple #18
0
 public void TestA(string domain)
 {
     Resolve(DnsRequest.CreateA(domain));
 }
Exemple #19
0
        static void Main(string[] args)
        {
            //NetBIOS nbt = new NetBIOS();
            //nbt.Register("HANS", IPAddress.Parse("192.168.177.1"));

            //try
            //{
            //    IPAddress ip = nbt.QueryName("HANS");
            //    Console.WriteLine("NetBIOS IP address for HANS: " + ip);
            //}
            //catch(Exception)
            //{
            //    Console.WriteLine("Could not get IP address for HANS.");
            //}



            // Retreiving the mail record (MX) of a domain

            Console.WriteLine("Retreiving MX record for domain google.com...");

            DnsRequest r = new DnsRequest();
            Question   q = new Question("google.com", DnsType.MX, DnsClass.IN);

            r.Questions.Add(q);

            DnsResolver dns = new DnsResolver();

            dns.LoadNetworkConfiguration();                             // using local IP configuration

            DnsResponse res = dns.Resolve(r);

            foreach (Answer a in res.Answers)
            {
                Console.WriteLine(a);
            }

            Console.WriteLine();
            Console.WriteLine();

            // Retreiving the IP address of an host

            Console.WriteLine("Retreiving A record for domain www.microsoft.com...");

            r = new DnsRequest();
            r.Questions.Add(new Question("www.microsoft.com", DnsType.A, DnsClass.IN));

            res = dns.Resolve(r);

            foreach (Answer a in res.Answers)
            {
                Console.WriteLine(a);
            }

            Console.WriteLine();
            Console.WriteLine();

            // Retreiving the IP address of an host

            Console.WriteLine("Retreiving TXT record (i.e. SPF) for domain microsoft.com...");

            r = new DnsRequest();
            r.Questions.Add(new Question("microsoft.com", DnsType.TXT, DnsClass.IN));

            res = dns.Resolve(r);

            foreach (Answer a in res.Answers)
            {
                Console.WriteLine(a);
            }
        }
Exemple #20
0
        DnsResponse ProcessRequest(DnsRequest request)
        {
            IEnumerable <IPAddress> nameServers = GetNameServers(request.Question.Domain);

            if (nameServers == null)
            {
                throw new DnsServerException(DnsStandard.ResponseCode.NameError);
            }

            bool useUdp = request.Question.Type == DnsStandard.RecordType.CERT ? false : true;

            int         count    = 0;
            DnsResponse response = null;

            foreach (IPAddress nameserver in nameServers)
            {
                DnsClient client = null;
                try
                {
                    if (m_doCache)
                    {
                        client = new DnsClientWithCache(new IPEndPoint(nameserver, m_dnsResolutionPort));
                    }
                    else
                    {
                        client = new DnsClient(new IPEndPoint(nameserver, m_dnsResolutionPort));
                    }

                    client.Timeout     = Timeout;
                    client.UseUDPFirst = useUdp;
                    DnsRequest newRequest = new DnsRequest(new DnsQuestion(request.Question));
                    response = client.Resolve(newRequest);

                    if (response != null)
                    {
                        // Clone the response before returning it since the response may be cached
                        // and we don't want the cached response to be modified.
                        response = response.Clone();

                        // updates the TTL of records to reflect the elapsed time since the
                        // record was cached.
                        response.UpdateRecordsTTL();
                        break;
                    }
                }
                catch (DnsException)
                {
                    continue;
                }
                finally
                {
                    if (client != null)
                    {
                        client.Dispose();
                    }
                }

                count++;
                if (count > m_maxNameServersToAttempt)
                {
                    break;
                }
            }

            if (response == null)
            {
                throw new DnsServerException(DnsStandard.ResponseCode.ServerFailure);
            }

            response.RequestID = request.RequestID;

            return(response);
        }
Exemple #21
0
        public void DnsResolver_Multiple_Lookup_Bind()
        {
            // This test repeats the A_Multiple test, but this time
            // after binding the DnsResolver to 5 client side sockets.

            IPAddress dns = GetDns();

            string[] gtld = new string[] {
                "a.gtld-servers.net.",
                "b.gtld-servers.net.",
                "c.gtld-servers.net.",
                "d.gtld-servers.net.",
                "e.gtld-servers.net.",
                "f.gtld-servers.net.",
                "g.gtld-servers.net.",
                "h.gtld-servers.net.",
                "i.gtld-servers.net.",
                "j.gtld-servers.net.",
                "k.gtld-servers.net.",
                "l.gtld-servers.net.",
                "m.gtld-servers.net.",
            };

            DnsRequest[]   requests  = new DnsRequest[gtld.Length];
            DnsResponse[]  responses = new DnsResponse[gtld.Length];
            IAsyncResult[] rgAR      = new IAsyncResult[gtld.Length];
            IPEndPoint[]   clientEPs;

            clientEPs = new IPEndPoint[10];
            for (int i = 0; i < clientEPs.Length; i++)
            {
                clientEPs[i] = new IPEndPoint(IPAddress.Any, 0);
            }

            DnsResolver.Bind(clientEPs, 128 * 1024, 128 * 1024);

            try
            {
                for (int j = 0; j < 10; j++)
                {
                    // Repeat the test 10 times just for fun

                    for (int i = 0; i < gtld.Length; i++)
                    {
                        requests[i] = new DnsRequest(DnsFlag.RD, gtld[i], DnsQType.A);
                    }

                    for (int i = 0; i < gtld.Length; i++)
                    {
                        rgAR[i] = DnsResolver.BeginQuery(dns, requests[i], timeout, null, null);
                    }

                    for (int i = 0; i < gtld.Length; i++)
                    {
                        responses[i] = DnsResolver.EndQuery(rgAR[i]);
                    }

                    for (int i = 0; i < gtld.Length; i++)
                    {
                        Assert.AreEqual(requests[i].QID, responses[i].QID);
                        Assert.AreEqual(requests[i].QName, responses[i].QName);
                    }
                }
            }
            finally
            {
                DnsResolver.Bind();
            }
        }