Beispiel #1
0
        static DnsMessageBase ProcessQuery(DnsMessageBase message, IPAddress clientAddress, ProtocolType protocol)
        {
            message.IsQuery = false;

            DnsMessage query = message as DnsMessage;

            if ((query != null) && (query.Questions.Count == 1))
            {
                // send query to upstream server
                DnsQuestion question = query.Questions[0];
                Random rnd = new Random();
                Console.WriteLine(question.Name);

                System.Threading.Tasks.Parallel.ForEach(dnslist, (site, state) =>
                {
                    Console.WriteLine("Get Info from: " +site);
                    DnsClient cd = new DnsClient(IPAddress.Parse(dnslist[rnd.Next(0, dnslist.Length - 1)]), 500);
                    DnsMessage answer = cd.Resolve(question.Name, question.RecordType, question.RecordClass);

                        if (answer != null)
                        {
                            foreach (DnsRecordBase record in (answer.AnswerRecords))
                            {
                                lock (query)
                                {
                                    query.AnswerRecords.Add(record);
                                }
                                Console.WriteLine(record.Name);
                            }
                            foreach (DnsRecordBase record in (answer.AdditionalRecords))
                            {
                                lock (query)
                                {
                                    query.AnswerRecords.Add(record);
                                }
                                Console.WriteLine(record.Name);
                            }
                            lock (query)
                            {
                                query.ReturnCode = ReturnCode.NoError;
                                state.Break();
                            }
                        }
                });
                // if got an answer, copy it to the message sent to the client
            }
            if (query.ReturnCode == ReturnCode.NoError)
            {
                return query;
            }
            // Not a valid query or upstream server did not answer correct
            message.ReturnCode = ReturnCode.ServerFailure;
            return message;
        }
        /// <summary>
        ///   Queries a the upstream DNS server(s) for specified records.
        /// </summary>
        /// <typeparam name="T"> Type of records, that should be returned </typeparam>
        /// <param name="name"> Domain, that should be queried </param>
        /// <param name="recordType"> Type the should be queried </param>
        /// <param name="recordClass"> Class the should be queried </param>
        /// <returns> A list of matching <see cref="DnsRecordBase">records</see> </returns>
        public List <T> Resolve <T>(DomainName name, RecordType recordType = RecordType.A, RecordClass recordClass = RecordClass.INet)
            where T : DnsRecordBase
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name), "Name must be provided");
            }

            List <T> records;

            if (_cache.TryGetRecords(name, recordType, recordClass, out records))
            {
                return(records);
            }

            DnsMessage msg = _dnsClient.Resolve(name, recordType, recordClass);

            if ((msg == null) || ((msg.ReturnCode != ReturnCode.NoError) && (msg.ReturnCode != ReturnCode.NxDomain)))
            {
                throw new Exception("DNS request failed");
            }

            CNameRecord cName = msg.AnswerRecords.Where(x => (x.RecordType == RecordType.CName) && (x.RecordClass == recordClass) && x.Name.Equals(name)).OfType <CNameRecord>().FirstOrDefault();

            if (cName != null)
            {
                records = msg.AnswerRecords.Where(x => x.Name.Equals(cName.CanonicalName)).OfType <T>().ToList();
                if (records.Count > 0)
                {
                    _cache.Add(name, recordType, recordClass, records, DnsSecValidationResult.Indeterminate, records.Min(x => x.TimeToLive));
                    return(records);
                }

                records = Resolve <T>(cName.CanonicalName, recordType, recordClass);

                if (records.Count > 0)
                {
                    _cache.Add(name, recordType, recordClass, records, DnsSecValidationResult.Indeterminate, records.Min(x => x.TimeToLive));
                }

                return(records);
            }

            records = msg.AnswerRecords.Where(x => x.Name.Equals(name)).OfType <T>().ToList();

            if (records.Count > 0)
            {
                _cache.Add(name, recordType, recordClass, records, DnsSecValidationResult.Indeterminate, records.Min(x => x.TimeToLive));
            }

            return(records);
        }
Beispiel #3
0
 private DnsEntry ForwardRequestToServer(DnsRequest dnsRequest, ForwardingServer forwardingServer, RecordType recordType)
 {
     var client = new DnsClient(IPAddress.Parse(forwardingServer.IpV4), 2000);
     var answer = client.Resolve(dnsRequest.Name, recordType);
     if (answer != null && answer.AnswerRecords.Any())
     {
         var record = answer.AnswerRecords.FirstOrDefault(r => r.RecordType == recordType);
         //if (record.RecordType != RecordType.A)
         //    return null;
         if (record == null)
             return null;
         if (record.RecordType != RecordType.A)
             return null;
         var dnsEntry = new DnsEntry() { Name = record.Name, IpV4 = ((ARecord)record).Address.ToString() };
         return dnsEntry;
     }
     return null;
 }
            public void Execute(IJobExecutionContext context)
            {
                var dnsbls = JsonConvert.DeserializeObject<List<Dnsbl>>(File.ReadAllText("data/dnsbl.js"));

                var reverseIp = string.Join(".", _droneSettings.Ip.Split('.').Reverse());
                var results = dnsbls.AsParallel().SelectMany(x =>
                    {
                        var name = reverseIp + "." + x.Dns;
                        Console.WriteLine(name);

                        var client = new DnsClient(IPAddress.Parse("8.8.8.8"), 1);
                        var records = client.Resolve(name, RecordType.A);
                        return records.AnswerRecords.OfType<ARecord>().Select(p => new BlacklistingRecord { Result = p.Address.ToString(), Service = x.Dns });
                    }).ToList();

                _omniRecordManager.UpdateOrInsert(new BlacklistingIpInformation
                    {
                        Answers = results
                    });
            }
Beispiel #5
0
 public void GetAddresses()
 {
     DnsClient dnsClient = DnsClient.Default;
     dnsClient = new DnsClient(IPAddress.Parse("192.168.2.254"), 2000);
     DnsMessage dnsMessage = dnsClient.Resolve("www.google.com", RecordType.A);
     if ((dnsMessage == null) || ((dnsMessage.ReturnCode != ReturnCode.NoError) && (dnsMessage.ReturnCode != ReturnCode.NxDomain)))
     {
         throw new Exception("DNS request failed");
     }
     else
     {
         foreach (DnsRecordBase dnsRecord in dnsMessage.AnswerRecords)
         {
             ARecord aRecord = dnsRecord as ARecord;
             if (aRecord != null)
             {
                 Console.WriteLine(aRecord.Address.ToString());
             }
         }
     }
 }
Beispiel #6
0
 public void Launch()
 {
     // Kolo.Service.Program.Main(new string[0]);
     ARecord aRecord=null;
     var client = new DnsClient(IPAddress.Loopback, (int)TimeSpan.FromSeconds(2).TotalMilliseconds);
     DnsMessage dnsMessage = client.Resolve("test.com", RecordType.A);
     if ((dnsMessage == null) || ((dnsMessage.ReturnCode != ReturnCode.NoError) && (dnsMessage.ReturnCode != ReturnCode.NxDomain)))
     {
         throw new Exception("DNS request failed");
     }
     else
     {
         foreach (DnsRecordBase dnsRecord in dnsMessage.AnswerRecords)
         {
             aRecord = dnsRecord as ARecord;
             if (aRecord != null)
             {
                 Console.WriteLine(aRecord.Address.ToString());
             }
         }
     }
     aRecord.Should().NotBeNull();
 }
Beispiel #7
0
        private static void CheckDns(IEnumerable<string> domains, RayCommandOptions rayCommandOptions)
        {
            var st = new Stopwatch();
            st.Start();
            var version = Guid.NewGuid().ToString().Substring(0, 6);

            var error = new List<string>();
            var mx = new List<string>();

            var badDomain = domains
                .Distinct()
                .AsParallel()
                .Where(domain =>
                    {
                        if (!domain.HasValue())
                            return true;

                        var client = new DnsClient(IPAddress.Parse("8.8.8.8"), 10000);

                        var mxRecords = client.Resolve(domain, RecordType.Mx);
                        if (mxRecords != null && (mxRecords.ReturnCode == ReturnCode.NoError || mxRecords.AnswerRecords.OfType<MxRecord>().Any()))
                        {
                            if (mxRecords.AnswerRecords.OfType<MxRecord>().Any())
                                mx.Add("The domain: " + domain + " has mx records: " + mxRecords.AnswerRecords.OfType<MxRecord>().Select(x => x.ExchangeDomainName).Commafy());

                            return false;
                        }

                        var retryCount = 0;

                        while (retryCount < 2)
                        {

                            var aRecord = client.Resolve(domain, RecordType.A);

                            if (aRecord == null)
                            {
                                error.Add("this domain produce null: " + domain);
                                return true;
                            }

                            if (aRecord.ReturnCode == ReturnCode.ServerFailure)
                            {
                                retryCount++;
                                continue;
                            }

                            if (aRecord.ReturnCode != ReturnCode.NoError)
                            {
                                error.Add(aRecord.ReturnCode + " dns error for: " + domain);
                                return true;
                            }

                            if (aRecord.ReturnCode == ReturnCode.NoError)
                                return false;

                            return CanConnect(aRecord.AnswerRecords.OfType<ARecord>().First().Address, domain);
                        }

                        return true;

                    }).ToList();

            st.Stop();

            WriteToConsole("Total shabank took: " + st.ElapsedMilliseconds);

            File.WriteAllLines(rayCommandOptions.OutputFile, badDomain.OrderBy(x => x));
            File.WriteAllLines(rayCommandOptions.OutputFile + "." + version + ".clean.txt", domains.Except(badDomain).OrderBy(x => x));
            File.WriteAllLines(rayCommandOptions.OutputFile + ".error.log." + version + ".txt", error.OrderBy(x => x).ToList());
            File.WriteAllLines(rayCommandOptions.OutputFile + ".mx.txt", mx);
        }
        private DnsMessage GetDotBitAnswerForName(DnsQuestion question, string name)
        {
            try
            {
                recursionLevel++;

                if (recursionLevel > maxRecursion)
                {
                    ConsoleUtils.WriteWarning("Max recursion reached");
                    return null;
                }

                DomainValue value = GetDomainValue(name);
                if (value == null)
                    return null;

                value.ImportDefaultMap();

                DnsMessage answer = null;

                //TODO: delegate not implemented
                if (!string.IsNullOrWhiteSpace(value.@Delegate))
                    ConsoleUtils.WriteWarning("delegate setting not implemented: {0}", value.Import);

                //TODO: import not implemented
                if (!string.IsNullOrWhiteSpace(value.Import))
                    ConsoleUtils.WriteWarning("import setting not implemented: {0}", value.Import);

                if (value.Alias != null)
                {
                    string newLookup;
                    if (value.Alias.EndsWith(".")) // absolute
                    {
                        newLookup = value.Alias;
                    }
                    else // sub domain
                    {
                        newLookup = value.Alias + '.';
                    }
                    DnsQuestion newQuestion = new DnsQuestion(value.Alias, question.RecordType, question.RecordClass);
                    return InternalGetAnswer(newQuestion);
                }

                answer = new DnsMessage()
                {
                    Questions = new List<DnsQuestion>() { question }
                };

                bool any = question.RecordType == RecordType.Any;

                var nsnames = value.Ns;
                if (nsnames != null && nsnames.Count() > 0) // NS overrides all
                {
                    List<IPAddress> nameservers = GetDotBitNameservers(nsnames);
                    if (nameservers.Count() > 0)
                    {
                        var client = new DnsClient(nameservers, 2000);
                        if (!string.IsNullOrWhiteSpace(value.Translate))
                            name = value.Translate;
                        answer = client.Resolve(name, question.RecordType, question.RecordClass);
                    }
                }
                else
                {
                    if (any || question.RecordType == RecordType.A)
                    {
                        var addresses = value.Ips;
                        if (addresses.Count() > 0)
                            foreach (var address in addresses)
                                answer.AnswerRecords.Add(new ARecord(name, 60, address));
                    }
                    if (any || question.RecordType == RecordType.Aaaa)
                    {
                        var addresses = value.Ip6s;
                        if (addresses.Count() > 0)
                            foreach (var address in addresses)
                                answer.AnswerRecords.Add(new AaaaRecord(name, 60, address));
                    }
                }

                return answer;
            }
            finally
            {
                recursionLevel--;
            }
        }
Beispiel #9
0
        private async Task Server_QueryReceived(object sender, ARSoft.Tools.Net.Dns.QueryReceivedEventArgs e)
        {
            bool foundQuery = false;

            DnsMessage query = e.Query as DnsMessage;

            if (query == null)
            {
                return;
            }

            DnsMessage response = query.CreateResponseInstance();

            try {
                C.WriteLine($"DnsServer: Questions: {query.Questions.Count}", true, "DNS");

                for (int idx = 0; idx < query.Questions.Count; idx++)
                {
                    var question = query.Questions[idx];

                    using (var connection = db.Connection()) {
                        using (var command = new SqliteCommand(
                                   "SELECT * FROM DnsEntries WHERE RecordType = @RecordType AND RecordClass = @RecordClass AND DomainName = @DomainName;", connection)) {
                            command.Parameters.AddWithValue("@RecordType", question.RecordType.ToString());
                            command.Parameters.AddWithValue("@RecordClass", question.RecordClass.ToString());
                            command.Parameters.AddWithValue("@DomainName", question.Name.ToString());

                            using (var reader = command.ExecuteReader()) {
                                C.WriteLine($"  Questions [{idx:000}] RES({reader.HasRows}): Type({question.RecordType}), Class({question.RecordClass}), {question.Name}", true, "DNS");

                                //Every new row will create a new dictionary that holds the columns
                                while (reader.Read())
                                {
                                    try {
                                        var dnStr = reader["DomainName"] as string;
                                        var dn    = DomainName.Parse(dnStr);
                                        if (dn == null)
                                        {
                                            continue;
                                        }

                                        var ttl = (System.Int64)reader["TTL"];
                                        var rt  = (RecordType)Enum.Parse(typeof(RecordType), reader["RecordType"] as string);
                                        var rc  = (RecordClass)Enum.Parse(typeof(RecordClass), reader["RecordClass"] as string);

                                        if (rt == RecordType.A)
                                        {
                                            if (reader["Address"] == null)
                                            {
                                                continue;
                                            }
                                            var addr = reader["Address"] as string;

                                            var aRec = new ARecord(dn, Convert.ToInt32(ttl), IPAddress.Parse(addr));
                                            response.AnswerRecords.Add(aRec);

                                            foundQuery = true;
                                        }
                                    } catch (Exception ex) {
                                        C.WriteLine($"  Questions [{idx:000}]: {C.Red}Exception: {ex.ToString()}", true, "DNS:ERROR");
                                    }
                                }
                            }
                        }
                    }
                }

                // Fallback
                if (dnsFallback != null && !foundQuery)
                {
                    DnsQuestion question = query.Questions[0];
                    var         resolve  = dnsFallback.Resolve(question.Name);

                    DnsMessage upstreamResponse = await dnsFallback.ResolveAsync(
                        question.Name, question.RecordType, question.RecordClass);

                    e.Response = upstreamResponse;
                    return;
                }

                response.ReturnCode = ReturnCode.NoError;
            } catch (Exception ex) {
                response.ReturnCode = ReturnCode.ServerFailure;
                C.WriteLine($"{C.Red}{ex.ToString()}", true, "DNS:ERROR");
            }

            // set the response
            e.Response = response;
        }