/// <summary> /// Creates a new instance of DnsResolver that resolves against specified DNS servers. /// </summary> /// <param name="remoteDnsServerAddress">Array of server addresses to use for resolving.</param> public DnsResolver(params IPAddress[] remoteDnsServerAddress) { if (remoteDnsServerAddress == null) throw new ArgumentNullException("remoteDnsServerAddress"); _client = new DnsClient(remoteDnsServerAddress.ToList(), QueryTimeout); }
public static DnsMessage DnsQuery(IPAddress ipAddress, DnsMessage dnsMessage, int port = 53, int timeout = 1500) { if (port == 0) { port = 53; } var client = new DnsClient(ipAddress, timeout) { IsUdpEnabled = !Config.OnlyTcpEnable, IsTcpEnabled = true }; for (var i = 0; i < Config.Retries; i++) { var aMessage = client.SendMessage(dnsMessage); if (aMessage != null) { return(aMessage); } } return(new DnsClient(ipAddress, timeout, port) { IsTcpEnabled = true, IsUdpEnabled = false }.SendMessage(dnsMessage)); }
private static DnsClient GetNonDefaultDnsClient() { var servers = WindowsNameServicesManager.GetCachedDnsServers(); if (!servers.Any()) servers.Add(defaultDnsServer); var client = new DnsClient(servers, 2000); return client; }
static SpecificForwaringServer() { s_dnsClient = CreateDnsClient(); s_sql = Data.AnySQL.CreateInstance(); string sqlc = s_sql.GetConnectionString(); System.Console.WriteLine(sqlc); } // End Constructo
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; }
public DnsServer(Database.Database db, int udpPort = 53, int tcpPort = 53, List <IPAddress> fallbackIpAddress = null) { this.db = db; if (fallbackIpAddress != null) { dnsFallback = new DnsClient(fallbackIpAddress, 2000); } dnsServer = new ARSoft.Tools.Net.Dns.DnsServer(udpPort, tcpPort); dnsServer.QueryReceived += Server_QueryReceived; }
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 }); }
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()); } } } }
public static ARSoft.Tools.Net.Dns.DnsClient CreateDnsClient() { // return DnsClient.Default; // https://medium.com/@nykolas.z/dns-resolvers-performance-compared-cloudflare-x-google-x-quad9-x-opendns-149e803734e5 System.Net.IPAddress googlePrimary = System.Net.IPAddress.Parse("8.8.8.8"); System.Net.IPAddress googleSecondary = System.Net.IPAddress.Parse("8.8.4.4"); System.Net.IPAddress openDnsPrimary = System.Net.IPAddress.Parse("208.67.222.222"); System.Net.IPAddress openDnsSecondary = System.Net.IPAddress.Parse("208.67.220.220"); System.Net.IPAddress cloudflarePrimary = System.Net.IPAddress.Parse("1.1.1.1"); System.Net.IPAddress cloudflareSecondary = System.Net.IPAddress.Parse("1.0.0.1"); System.Net.IPAddress quad9Primary = System.Net.IPAddress.Parse("9.9.9.9"); System.Net.IPAddress quad9Secondary = System.Net.IPAddress.Parse("149.112.112.112"); System.Net.IPAddress cleanBrowsingPrimary = System.Net.IPAddress.Parse("185.228.168.168"); System.Net.IPAddress cleanBrowsingSecondary = System.Net.IPAddress.Parse("185.228.168.169"); // Norton, policy 1,2 & 3 System.Net.IPAddress nortonSecurityPrimary = System.Net.IPAddress.Parse("199.85.126.10"); System.Net.IPAddress nortonSecuritySecondary = System.Net.IPAddress.Parse("199.85.127.10"); System.Net.IPAddress nortonSecPronPrimary = System.Net.IPAddress.Parse("199.85.126.20"); System.Net.IPAddress nortonSecPronSecondary = System.Net.IPAddress.Parse("199.85.127.20"); System.Net.IPAddress nortonSecPronMorePrimary = System.Net.IPAddress.Parse("199.85.126.30"); System.Net.IPAddress nortonSecPronMoreSecondary = System.Net.IPAddress.Parse("199.85.127.30"); System.Collections.Generic.List <System.Net.IPAddress> ls = new System.Collections.Generic.List <System.Net.IPAddress>(); // ls.Add(cloudflarePrimary); ls.Add(cloudflareSecondary); int timeout = 500; ARSoft.Tools.Net.Dns.DnsClient client = new ARSoft.Tools.Net.Dns.DnsClient(ls, timeout); return(client); } // ENd Function CreateDnsClient
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(); }
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} served from cache.", message.TransactionID, cachedMessage.TransactionID); 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)) { 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 { 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); } }); }
static DnsClient() { Default = new DnsClient(GetDnsServers(), 10000); }
public AdvDnsClient(IPAddress ip, int timeout) { dns_ = new DnsClient(ip, timeout); }
public AdvDnsClient(DnsClient dns) { dns_ = dns; }
static DnsClient() { Default = new DnsClient(GetLocalConfiguredDnsServers(), 10000) { IsResponseValidationEnabled = true }; }
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); }
/// <summary> /// Creates a new instance of DnsResolver that resolves against the local DNS servers. /// </summary> public DnsResolver() { _client = DnsClient.Default; }
public DnsClient() { _dnsClient = new ARSoft.Tools.Net.Dns.DnsClient(ARSoft.Tools.Net.Dns.DnsClient.GetLocalConfiguredDnsServers(), 10000); }
static DnsClient() { Default = new DnsClient(GetLocalConfiguredDnsServers(), 10000) { IsResponseValidationEnabled = true }; }
public DnsClient() { _dnsClient = new ARSoft.Tools.Net.Dns.DnsClient(ARSoft.Tools.Net.Dns.DnsClient.GetLocalConfiguredDnsServers(), 10000); }
/// <summary> /// Provides a new instance using a custom <see cref="DnsClient">DNS client</see> /// </summary> /// <param name="dnsClient"> The <see cref="DnsClient">DNS client</see> to use </param> public DnsStubResolver(DnsClient dnsClient) { _dnsClient = dnsClient; }
static DnsClient() { Default = new DnsClient(GetDnsServers(), 10000); }
/// <summary> /// Provides a new instance using a custom <see cref="DnsClient">DNS client</see> /// </summary> /// <param name="dnsClient"> The <see cref="DnsClient">DNS client</see> to use </param> /// <param name="resolverHintStore"> The resolver hint store with the root DnsKey hints</param> public SelfValidatingInternalDnsSecStubResolver(DnsClient dnsClient = null, IResolverHintStore resolverHintStore = null) { _dnsClient = dnsClient ?? DnsClient.Default; _cache = new DnsCache(); _validator = new DnsSecValidator <object>(this, resolverHintStore ?? new StaticResolverHintStore()); }
public void RefreshConfiguration(bool skipServerCheck) { _dnsClient = new DnsClient(Configuration.DnsDirect.ToList(), Configuration.DnsDirectTimeout); _dnsSocksClient = !Configuration.SocksEnabled ? null : new DnsSocksClient(Configuration.SocksIP, Configuration.SocksPort, Configuration.DnsProxy.ToList(), Configuration.DnsProxyTimeout); if (!skipServerCheck) { if (Configuration.ServerEnabled && !IsRunning) { Start(); } if (!Configuration.ServerEnabled && IsRunning) { Stop(); } } }
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--; } }