private List <string> GetHostsFromResponse(IDnsQueryResponse response)
        {
            var hosts = new List <string>();

            foreach (var srvRecord in response.Answers.SrvRecords())
            {
                var h = srvRecord.Target.ToString();
                if (h.EndsWith(".", StringComparison.Ordinal))
                {
                    h = h.Substring(0, h.Length - 1);
                }
                hosts.Add(h + ":" + srvRecord.Port);
            }

            return(hosts);
        }
        private async Task <List <string> > GetARecords(string domain, string host)
        {
            List <string> ipAddresses = new List <string>();

            IDnsQueryResponse response = await _lookupClient.QueryAsync(host, QueryType.A);

            if (!response.HasError)
            {
                ipAddresses.AddRange(response.Answers
                                     .OfType <ARecord>()
                                     .Select(_ => _.Address.ToString().Escape())
                                     .ToList());
            }

            return(ipAddresses);
        }
        private async Task <IDnsQueryResponse> RecursivelyFollowCnames(IDnsQueryResponse result, int attempt)
        {
            if (result.Answers.CnameRecords().Any())
            {
                var cname            = result.Answers.CnameRecords().First();
                var recursiveClients = await _provider.GetClients(cname.CanonicalName, attempt);

                var index           = attempt % recursiveClients.Count();
                var recursiveClient = recursiveClients.ElementAt(index);
                var txtResponse     = await recursiveClient.LookupClient.QueryAsync(cname.CanonicalName, QueryType.TXT);

                _log.Debug("Name server {NameServerIpAddress} selected", txtResponse.NameServer.Endpoint.Address.ToString());
                return(await recursiveClient.RecursivelyFollowCnames(txtResponse, attempt));
            }
            return(result);
        }
Beispiel #4
0
        public Domain SetARecords(IDnsQueryResponse result)
        {
            if (result == null)
            {
                throw new ArgumentException("ARecord é nulo");
            }

            var record  = result.Answers.ARecords().FirstOrDefault();
            var address = record?.Address;
            var ip      = address?.ToString();

            Ip  = ip;
            Ttl = record?.TimeToLive ?? 0;

            return(this);
        }
Beispiel #5
0
        private async Task ExcecuteRun()
        {
            //var swatch = Stopwatch.StartNew();
            while (_running)
            {
                var query = NextDomainName();

                try
                {
                    IDnsQueryResponse response = null;
                    _spinner.Message = query;

                    if (!_runSync)
                    {
                        response = await _lookup.QueryAsync(query, QueryType.A);
                    }
                    else
                    {
                        response = await Task.Run(() => _lookup.Query(query, QueryType.A));
                    }

                    Interlocked.Increment(ref _allExcecutions);
                    Interlocked.Increment(ref _reportExcecutions);
                    if (response.HasError)
                    {
                        _errorsPerCode.AddOrUpdate(response.Header.ResponseCode.ToString(), 1, (c, v) => v + 1);
                        _failByServer.AddOrUpdate(response.NameServer, 1, (n, v) => v + 1);
                        Interlocked.Increment(ref _errors);
                    }
                    else
                    {
                        _successByServer.AddOrUpdate(response.NameServer, 1, (n, v) => v + 1);
                        Interlocked.Increment(ref _success);
                    }
                }
                catch (DnsResponseException ex)
                {
                    _errorsPerCode.AddOrUpdate(ex.Code.ToString(), 1, (c, v) => v + 1);
                    Interlocked.Increment(ref _errors);
                }
                catch (Exception ex)
                {
                    _errorsPerCode.AddOrUpdate(ex.GetType().Name, 1, (c, v) => v + 1);
                    Interlocked.Increment(ref _errors);
                }
            }
        }
Beispiel #6
0
        public async Task <IPAddress> QueryIp(string domain, CancellationToken token)
        {
            IDnsQueryResponse response = await _lookup.QueryAsync(domain, QueryType.A, QueryClass.IN, token);

            ARecord aRecord = response.Answers.ARecords().FirstOrDefault();

            if (aRecord != null)
            {
                return(aRecord.Address);
            }

            response = await _lookup.QueryAsync(domain, QueryType.AAAA, QueryClass.IN, token);

            AaaaRecord aaaaRecord = response.Answers.AaaaRecords().FirstOrDefault();

            return(aaaaRecord?.Address);
        }
Beispiel #7
0
        public bool Add(string key, IDnsQueryResponse response)
        {
            if (key == null)
            {
                throw new ArgumentNullException(key);
            }

            if (Enabled && response != null && !response.HasError && response.Answers.Count > 0)
            {
                var all = response.AllRecords.Where(p => !(p is Protocol.Options.OptRecord));
                if (all.Any())
                {
                    // in millis
                    double minTtl = all.Min(p => p.InitialTimeToLive) * 1000d;

                    if (MinimumTimout == Timeout.InfiniteTimeSpan)
                    {
                        // TODO: Log warning once?
                        minTtl = s_maxTimeout.TotalMilliseconds;
                    }
                    else if (MinimumTimout.HasValue && minTtl < MinimumTimout.Value.TotalMilliseconds)
                    {
                        minTtl = MinimumTimout.Value.TotalMilliseconds;
                    }

                    // max ttl check which can limit the upper boundary
                    if (MaximumTimeout.HasValue && MaximumTimeout != Timeout.InfiniteTimeSpan && minTtl > MaximumTimeout.Value.TotalMilliseconds)
                    {
                        minTtl = MaximumTimeout.Value.TotalMilliseconds;
                    }

                    if (minTtl < 1d)
                    {
                        return(false);
                    }

                    var newEntry = new ResponseEntry(response, minTtl);

                    StartCleanup();
                    return(_cache.TryAdd(key, newEntry));
                }
            }

            StartCleanup();
            return(false);
        }
        private static string GetHostNameAsyncProcessResult(IDnsQueryResponse result)
        {
            if (result.HasError)
            {
                return(null);
            }

            var hostName = result.Answers.PtrRecords().FirstOrDefault()?.PtrDomainName;

            if (string.IsNullOrWhiteSpace(hostName))
            {
                return(null);
            }

            // removing the . at the end
            return(hostName.Value.Substring(0, hostName.Value.Length - 1));
        }
        public async Task <DnsResult <List <List <string> > > > GetSpfRecords(string domain)
        {
            IDnsQueryResponse response = await _lookupClient.QueryAsync(domain, QueryType.TXT);

            if (response.HasError)
            {
                return(new DnsResult <List <List <string> > >(response.ErrorMessage));
            }

            return(new DnsResult <List <List <string> > >(
                       response.Answers
                       .OfType <TxtRecord>()
                       .Where(_ => _.Text.FirstOrDefault()?.StartsWith("v=spf", StringComparison.OrdinalIgnoreCase) ??
                              false)
                       .Select(_ => _.Text.Select(r => r.Escape()).ToList())
                       .ToList(), response.MessageSize));
        }
 private IDnsQueryResponse RecursivelyFollowCnames(IDnsQueryResponse result)
 {
     if (result.Answers.CnameRecords().Any())
     {
         var cname     = result.Answers.CnameRecords().First();
         var nsChecker = this;
         if (_default != null)
         {
             nsChecker = _default;
         }
         var nameServerIpAddresses     = nsChecker.GetNameServerIpAddresses(cname.CanonicalName);
         var recursiveClient           = new LookupClientWrapper(_domainParser, _log, new LookupClient(nameServerIpAddresses.ToArray()), _default);
         IDnsQueryResponse txtResponse = recursiveClient.LookupClient.Query(cname.CanonicalName, QueryType.TXT);
         _log.Debug("Name server {NameServerIpAddress} selected", txtResponse.NameServer.Endpoint.Address.ToString());
         return(recursiveClient.RecursivelyFollowCnames(txtResponse));
     }
     return(result);
 }
Beispiel #11
0
        // private methods
        private List <SrvRecord> GetSrvRecords(IDnsQueryResponse response)
        {
            var wrappedSrvRecords = response.Answers.SrvRecords().ToList();
            var srvRecords        = new List <SrvRecord>();

            foreach (var wrappedSrvRecord in wrappedSrvRecords)
            {
                var host       = wrappedSrvRecord.Target.ToString();
                var port       = wrappedSrvRecord.Port;
                var endPoint   = new DnsEndPoint(host, port);
                var timeToLive = TimeSpan.FromSeconds(wrappedSrvRecord.InitialTimeToLive);
                var srvRecord  = new SrvRecord(endPoint, timeToLive);

                srvRecords.Add(srvRecord);
            }

            return(srvRecords);
        }
Beispiel #12
0
        public static void Main(string[] args)
        {
            if (args.Length > 2 || args.Length == 0 || args[0] == "-h" || args[0] == "/?" || args[0] == "/h" || args[0] == "--help")
            {
                Console.WriteLine("WinBinReplacements: nslookup.exe <hostname> [dns_server]");
                return;
            }
            LookupClient      client = new LookupClient();
            IDnsQueryResponse result = null;
            NameServer        ns     = null;

            if (args.Length == 2)
            {
                try
                {
                    ns     = new NameServer(IPAddress.Parse(args[1]));
                    client = new LookupClient(ns);
                }
                catch
                {
                    Console.WriteLine("[!] Error: nameserver is not an IP address: " + args[1]);
                    return;
                }
            }
            try
            {
                result = client.Query(args[0], QueryType.A);
            }
            catch (DnsResponseException)
            {
                Console.WriteLine("[!] Error: DNS server could not be contacted");
                return;
            }

            foreach (var answer in result.Answers)
            {
                Console.WriteLine(answer);
            }
            if (result.Answers.Count == 0)
            {
                Console.WriteLine("[!] Error: no matching records found for " + args[0]);
            }
        }
        public async Task <DnsResult <List <HostMxRecord> > > GetMxRecords(string domain)
        {
            _log.LogInformation($"Querying mx records for {domain}");

            IDnsQueryResponse response = await _lookupClient.QueryAsync(domain, QueryType.MX);

            if (response.HasError)
            {
                _log.LogInformation($"Error occured quering mx records for {domain}, error: {response.ErrorMessage}");
                return(new DnsResult <List <HostMxRecord> >(response.ErrorMessage));
            }

            List <HostMxRecord> records = await GetRecords(domain, response);

            _log.LogInformation($"MX records for {domain}, results: {JsonConvert.SerializeObject(records)}");


            return(new DnsResult <List <HostMxRecord> >(records, response.MessageSize));
        }
Beispiel #14
0
        public async Task <TlsRptRecordInfos> GetTlsRptRecords(string domain)
        {
            string    queryText = $"_smtp._tls.{domain}";
            QueryType queryType = QueryType.TXT;

            IDnsQueryResponse response = await _lookupClient.QueryAsync(queryText, queryType);

            List <TlsRptRecordInfo> tlsRptRecordInfos = response.Answers.OfType <TxtRecord>()
                                                        .Where(_ => _.Text.FirstOrDefault()?.StartsWith("v=TLSRPTv", StringComparison.OrdinalIgnoreCase) ?? false)
                                                        .Select(_ => new TlsRptRecordInfo(domain, _.Text.Select(r => r.Escape()).ToList()))
                                                        .ToList();

            if (response.HasError && response.ErrorMessage != NonExistentDomainError && response.ErrorMessage != SERV_FAILURE_ERROR)
            {
                return(new TlsRptRecordInfos(domain, new FailedPollError(response.ErrorMessage), response.MessageSize));
            }

            return(new TlsRptRecordInfos(domain, tlsRptRecordInfos, response.MessageSize));
        }
Beispiel #15
0
            public void AuditResponse(IDnsQueryResponse queryResponse)
            {
                if (queryResponse.Questions.Count > 0)
                {
                    _auditWriter.AppendLine(";; QUESTION SECTION:");
                    foreach (var question in queryResponse.Questions)
                    {
                        _auditWriter.AppendLine(question.ToString(s_printOffset));
                    }
                    _auditWriter.AppendLine();
                }

                if (queryResponse.Answers.Count > 0)
                {
                    _auditWriter.AppendLine(";; ANSWER SECTION:");
                    foreach (var answer in queryResponse.Answers)
                    {
                        _auditWriter.AppendLine(answer.ToString(s_printOffset));
                    }
                    _auditWriter.AppendLine();
                }

                if (queryResponse.Authorities.Count > 0)
                {
                    _auditWriter.AppendLine(";; AUTHORITIES SECTION:");
                    foreach (var auth in queryResponse.Authorities)
                    {
                        _auditWriter.AppendLine(auth.ToString(s_printOffset));
                    }
                    _auditWriter.AppendLine();
                }

                if (queryResponse.Additionals.Count > 0)
                {
                    _auditWriter.AppendLine(";; ADDITIONALS SECTION:");
                    foreach (var additional in queryResponse.Additionals)
                    {
                        _auditWriter.AppendLine(additional.ToString(s_printOffset));
                    }
                    _auditWriter.AppendLine();
                }
            }
        private async Task <bool> CheckDnsEntriesAsync(string domain)
        {
            try
            {
                LookupClient lookup = new LookupClient
                {
                    Timeout = TimeSpan.FromSeconds(5)
                };

                IDnsQueryResponse result = await lookup.QueryAsync(domain, QueryType.MX).ConfigureAwait(false);

                IEnumerable <DnsClient.Protocol.DnsResourceRecord> records = result.Answers.Where(record => record.RecordType == DnsClient.Protocol.ResourceRecordType.A ||
                                                                                                  record.RecordType == DnsClient.Protocol.ResourceRecordType.AAAA ||
                                                                                                  record.RecordType == DnsClient.Protocol.ResourceRecordType.MX);
                return(records.Any());
            }
            catch (DnsResponseException)
            {
                return(false);
            }
        }
Beispiel #17
0
        public bool Add(string key, IDnsQueryResponse response)
        {
            if (key == null)
            {
                throw new ArgumentNullException(key);
            }
            if (Enabled && response != null && !response.HasError)
            {
                var all = response.AllRecords;
                if (all.Any())
                {
                    // in millis
                    double minTtl = all.Min(p => p.TimeToLive) * 1000d;

                    if (MinimumTimout == Timeout.InfiniteTimeSpan)
                    {
                        minTtl = s_maxTimeout.TotalMilliseconds;
                    }
                    else if (MinimumTimout.HasValue && minTtl < MinimumTimout.Value.TotalMilliseconds)
                    {
                        minTtl = (long)MinimumTimout.Value.TotalMilliseconds;
                    }

                    if (minTtl < 1d)
                    {
                        return(false);
                    }

                    var newEntry = new ResponseEntry(response, minTtl);

                    StartCleanup();
                    return(_cache.TryAdd(key, newEntry));
                }
            }

            StartCleanup();
            return(false);
        }
        public void ResolveServiceProcessResultReturnAEntityList()
        {
            IDnsQueryResponse result         = null;
            var                mockResult    = new Mock <IDnsQueryResponse>();
            DnsString          canonicalName = DnsClient.DnsString.Parse("hostname.com");
            ResourceRecordInfo info          = new ResourceRecordInfo(canonicalName, DnsClient.Protocol.ResourceRecordType.SRV, DnsClient.QueryClass.IN, 10, 1);

            var record      = new SrvRecord(info, 1, 10, 443, canonicalName);
            var cNameRecord = new CNameRecord(info, canonicalName);

            List <SrvRecord> answers = new List <SrvRecord>()
            {
                record
            };

            mockResult.Setup(foo => foo.Answers).Returns(answers);
            mockResult.Setup(foo => foo.Additionals).Returns(new List <CNameRecord>()
            {
                cNameRecord
            });
            result = mockResult.Object;
            List <DnsSrvResultEntry> ret = ResolveServiceProcessResult(result);
        }
Beispiel #19
0
        /// <summary>
        /// Performs a DNS SRV lookup for the given host and returns a list of <see cref="SrvRecord"/> objects for the "xmpp-client" service.
        /// </summary>
        /// <param name="host">The host the lookup should be performed for.</param>
        /// <returns>A list of <see cref="SrvRecord"/> objects ordered by their priority or an empty list of an error occurred or no entries were found.</returns>
        public static async Task <List <SrvRecord> > DnsSrvLookupAsync(string host)
        {
            Logger.Info(LOGGER_TAG + "Performing DNS SRV lookup for: " + host);
            LookupClient lookup = new LookupClient();

            try
            {
                IDnsQueryResponse response = await lookup.QueryAsync("_xmpp-client._tcp." + host, QueryType.SRV);

                if (response is DnsQueryResponse dnsResponse)
                {
                    IEnumerable <SrvRecord> records = dnsResponse.AllRecords.Where((record) => record is SrvRecord).Select((record) => record as SrvRecord);
                    List <SrvRecord>        list    = records.ToList();
                    list.Sort((a, b) => a.Priority.CompareTo(b.Priority));
                    return(list);
                }
            }
            catch (Exception e)
            {
                Logger.Error(LOGGER_TAG + "Failed to look up DNS SRV record for: " + host, e);
            }
            return(new List <SrvRecord>());
        }
Beispiel #20
0
 public CaaReponse(IDnsQueryResponse dnsReponse)
 {
     this._Response = dnsReponse;
 }
		public static void Main(string[] args)
		{
			Console.ForegroundColor = ConsoleColor.White;
			Console.WriteLine("Server: ");
			var input = Console.ReadLine();
			var server = string.IsNullOrWhiteSpace(input) ? "jean-pierre-bachmann.de" : input;
			Console.Title = server;

			Console.WriteLine("Find TXT Record:");
			input = Console.ReadLine();

			input = string.IsNullOrWhiteSpace(input) ? "SpEsZQ0YgIvvSFx3Vcd6Ssli7fYW0jtmTMcL829da3o" : input;

			var dnsServer = new List<DomainLookup>
			{
				new DomainLookup(IPAddress.Parse("8.8.8.8")),
				new DomainLookup(IPAddress.Parse("208.67.222.222")),
				new DomainLookup(IPAddress.Parse("208.67.222.123")),
				new DomainLookup(IPAddress.Parse("209.244.0.3")),
				new DomainLookup(IPAddress.Parse("216.146.35.35")),
				new DomainLookup(IPAddress.Parse("195.46.39.39")),
				new DomainLookup(IPAddress.Parse("8.26.56.26")),
				new DomainLookup(IPAddress.Parse("84.200.69.80")),
				new DomainLookup(IPAddress.Parse("81.169.163.106")),
				new DomainLookup(IPAddress.Parse("81.169.148.38")),
			};

			var dnsDomains = new[]
			{
				"ns1-06.azure-dns.com",
				"ns2-06.azure-dns.net",
				"ns3-06.azure-dns.org",
				"ns4-06.azure-dns.info",
				"ns1-08.azure-dns.com",
				"ns2-08.azure-dns.net",
				"ns3-08.azure-dns.org",
				"ns4-08.azure-dns.info",

				"a.root-servers.net",
			};

			foreach (var dnsDomain in dnsDomains)
			{
				foreach (var hostAddress in Dns.GetHostAddresses(dnsDomain).Where(e => e.AddressFamily == AddressFamily.InterNetwork))
				{
					dnsServer.Add(new DomainLookup(hostAddress));
				}
			}

			Console.Clear();
			Console.WriteLine("Check Dns:");
			var client = new LookupClient();
			client.UseCache = true;
			
			while (true)
			{
				foreach (var lookupClient in dnsServer)
				{
					if (lookupClient.ReverseLookup == null)
					{
						var dnsQueryResponse = client.GetHostName(lookupClient.Address);
						lookupClient.ReverseLookup = dnsQueryResponse;
					}
					Console.Write($"Check: {lookupClient.Address} - {lookupClient.ReverseLookup}");
					if (lookupClient.ErrorCounter > 10)
					{
						Console.WriteLine("Skipped");
					}

					var stopWaiter = false;
					var stoppedWaiter = new ManualResetEventSlim();
					Task.Run(async () =>
					{
						var waiterArray = new[] { '|', '/', '-', '\\', '-' };
						var index = 0;
						while (!stopWaiter)
						{
							if (index == waiterArray.Length)
							{
								index = 0;
							}
							Console.Write(waiterArray[index++]);
							await Task.Delay(140);
							Console.CursorLeft--;
						}
						stoppedWaiter.Set();
					});

					IDnsQueryResponse txtQuery = null;
					IDnsQueryResponse nsQuery = null;
					string errorText = null;
					try
					{
						txtQuery = client.QueryServer(new[] {lookupClient.Address}, server, QueryType.TXT);
						errorText = txtQuery.HasError ? txtQuery.ErrorMessage : null;
						
						nsQuery = client.QueryServer(new[] {lookupClient.Address}, server, QueryType.NS);
						errorText = txtQuery.HasError ? txtQuery.ErrorMessage : null;
					}
					catch (Exception e)
					{
						errorText = e.Message;
					}
					finally
					{
						stopWaiter = true;
						stoppedWaiter.Wait();
					}
					Console.Write("   ");
					Console.CursorLeft -= "   ".Length;
					if (errorText != null)
					{
						lookupClient.ErrorCounter++;
						Console.WriteLine("...Error: " + errorText);
						continue;
					}

					Console.WriteLine();

					var txtRecords = txtQuery.Answers.TxtRecords().ToArray();
					var firstOrDefault = txtRecords.FirstOrDefault(e =>
						e.Text.Any(f => f.Equals(input)));
					var nsRecords = nsQuery.Answers.NsRecords();
					foreach (var nsRecord in nsRecords)
					{
						Console.ForegroundColor = ConsoleColor.Magenta;
						Console.WriteLine(nsRecord );
					}
					if (firstOrDefault != null)
					{
						Console.ForegroundColor = ConsoleColor.Green;
						Console.WriteLine("FOUND!");
					}
					else
					{
						Console.ForegroundColor = ConsoleColor.Red;
						Console.WriteLine("not found: ");
						foreach (var txtRecord in txtRecords)
						{
							Console.WriteLine(txtRecord);
						}
					}
					Console.ForegroundColor = ConsoleColor.White;
				}

				var nextUpdate = DateTime.Now.AddSeconds(150);
				var waitMessage = "Wait for next call: ";
				Console.Write(waitMessage);
				while (nextUpdate > DateTime.Now)
				{
					Console.CursorLeft = waitMessage.Length;
					Console.Write("                 ");
					Console.CursorLeft = waitMessage.Length;

					var at = nextUpdate - DateTime.Now;
					Console.Write($"{at.Hours}H {at.Minutes}M {at.Seconds}S");

					Thread.Sleep(1000);
				}

				Console.Clear();
			}
		}
 public TestResponse(TestClient testClient, IDnsQueryResponse response)
 {
     TestClient = testClient;
     Response   = response;
 }
Beispiel #23
0
 public SpfResponse(IDnsQueryResponse dnsReponse, IDnsQueryResponse spfDnsResponse)
 {
     this._TxtReponse = dnsReponse;
     this._SpfReponse = spfDnsResponse;
 }
Beispiel #24
0
        static void Main(string[] args)
        {
            // 1.sending to one
            MailAddress to   = new MailAddress("*****@*****.**");
            MailAddress from = new MailAddress("*****@*****.**");

            MailMessage message = new MailMessage(from, to);

            message.Subject = "Good morning";
            message.Body    = "Elizabeth, Harry, There are a few unpaid invoices for the Royal Wedding. Let's talk this over on Monday.;";
            message.CC.Add(new MailAddress("*****@*****.**"));
            message.Bcc.Add(new MailAddress("*****@*****.**"));

            //2. sending with images
            String         imagePath   = "bestpictureever.png";
            LinkedResource LinkedImage = new LinkedResource(@imagePath);

            LinkedImage.ContentId = "Wedding";

            AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
                $"{message} <br> <img src=cid:Wedding>", null, "text/html"
                );

            htmlView.LinkedResources.Add(LinkedImage);
            message.AlternateViews.Add(htmlView);

            //3.sending to mulltiple clients
            SmtpClient client = new SmtpClient("smtp.server.address", 2525)
            {
                Credentials = new NetworkCredential("smtp_username", "smtp_password"),
                EnableSsl   = true
            };

            // code in brackets above needed if authentication required

            try
            {
                client.Send(message);
            }
            catch (SmtpException ex)
            {
                Console.WriteLine(ex.ToString());
            }


            //4. Sending without your own smtp/ using DNS client

            LookupClient      lookup   = new LookupClient();
            IDnsQueryResponse response = lookup.Query("westminster.co.uk", QueryType.MX);


            foreach (DnsClient.Protocol.MxRecord record in response.Answers)
            {
                Console.WriteLine(ObjectDumper.Dump(record.Exchange));

                SmtpClient client = new SmtpClient(record.Exchange, 25);

                try
                {
                    client.Send(message);
                    // if we reached this point, our email was sent and we can break the loop
                    break;
                }
                catch (SmtpException ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
 public DmarcResponse(IDnsQueryResponse dnsReponse)
 {
     this._Reponse = dnsReponse;
 }
Beispiel #26
0
        public static string GetTTL(string host)
        {
            IDnsQueryResponse dnsQueryResponse = client.Query(host, QueryType.ANY);

            return("");
        }
Beispiel #27
0
        static string ParseRecord(IDnsQueryResponse dnsQueryResponse, bool isA = false, bool isMx = false)
        {
            string output = "";
            string value  = "";
            string ttl    = "";
            string mxp    = "";

            foreach (DnsResourceRecord record in dnsQueryResponse.Answers)
            {
                switch (record.RecordType)
                {
                case ResourceRecordType.MX:
                {
                    MxRecord mxRecord = record as MxRecord;
                    if (mxRecord != null)
                    {
                        value += mxRecord.Exchange + "\n";
                        ttl   += mxRecord.InitialTimeToLive + "\n";
                        mxp   += mxRecord.Preference + "\n";
                        // output += $"{mxRecord.Exchange} | TTL {mxRecord.InitialTimeToLive}\n";
                    }
                    break;
                }

                case ResourceRecordType.SOA:
                {
                    SoaRecord soaRecord = record as SoaRecord;
                    if (soaRecord != null)
                    {
                        value += soaRecord.ToString() + "\n";
                        ttl   += soaRecord.Minimum + "\n";
                        // output += $"SOA TTL {soaRecord.Minimum}\n";
                    }
                    break;
                }

                case ResourceRecordType.NS:
                {
                    NsRecord nsRecord = record as NsRecord;
                    if (nsRecord != null)
                    {
                        value += nsRecord.NSDName + "\n";
                        ttl   += nsRecord.InitialTimeToLive + "\n";
                        // output += $"{nsRecord.NSDName} | TTL {nsRecord.InitialTimeToLive}\n";
                    }
                    break;
                }

                case ResourceRecordType.A:
                {
                    ARecord nsRecord = record as ARecord;
                    if (nsRecord != null)
                    {
                        return($"{nsRecord.InitialTimeToLive}");
                    }
                    return("No record");
                }

                case ResourceRecordType.TXT:
                {
                    TxtRecord txtRecord = record as TxtRecord;
                    if (txtRecord != null)
                    {
                        foreach (string txt in txtRecord.Text)
                        {
                            value += "\"\"" + txt + "\"\"\n";
                            ttl   += txtRecord.InitialTimeToLive + "\n";
                            // output += $"\"{txt}\" | TTL {txtRecord.InitialTimeToLive}\n";
                        }
                    }
                    break;
                }
                }
            }

            if (!string.IsNullOrEmpty(value) && !string.IsNullOrEmpty(ttl))
            {
                if (string.IsNullOrEmpty(mxp))
                {
                    output = $"\"{value.Trim()}\",\"{ttl.Trim()}\"";
                }
                else
                {
                    output = $"\"{value.Trim()}\",\"{mxp.Trim()}\",\"{ttl.Trim()}\"";
                }
            }
            else
            {
                if (isA)
                {
                    output = "No record";
                }
                else if (isMx)
                {
                    output = "No record,No record,No record";
                }
                else
                {
                    output = "No record,No record";
                }
            }

            if (string.IsNullOrEmpty(output))
            {
                return("No record\n");
            }
            return(output);
        }
Beispiel #28
0
        /// <inheritdoc />
        public async Task SendMailAsync(string toDomain, IAsyncEnumerable <MailToSend> messages)
        {
            using SmtpClient client = new SmtpClient()
                  {
                      ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) =>
                      {
                          return(sslPolicyErrors == SslPolicyErrors.None ||
                                 ignoreCertificateErrorsRegex.TryGetValue("*", out _) ||
                                 (ignoreCertificateErrorsRegex.TryGetValue(toDomain, out Regex regex)) && regex.IsMatch(certificate.Subject));
                      }
                  };
            IPHostEntry  ip     = null;
            LookupClient lookup = new LookupClient();

            MailDemonLog.Debug("QueryAsync mx for domain {0}", toDomain);
            IDnsQueryResponse result = await lookup.QueryAsync(toDomain, QueryType.MX, cancellationToken : cancelToken);

            bool connected = false;

            foreach (DnsClient.Protocol.MxRecord record in result.AllRecords)
            {
                // attempt to send, if fail, try next address
                try
                {
                    MailDemonLog.Debug("GetHostEntryAsync for exchange {0}", record.Exchange);
                    ip = await Dns.GetHostEntryAsync(record.Exchange);

                    foreach (IPAddress ipAddress in ip.AddressList)
                    {
                        string host = ip.HostName;
                        try
                        {
                            if (!DisableSending)
                            {
                                await client.ConnectAsync(host, options : MailKit.Security.SecureSocketOptions.Auto, cancellationToken : cancelToken).TimeoutAfter(30000);
                            }
                            connected = true;
                            await foreach (MailToSend message in messages)
                            {
                                if (dkimSigner != null)
                                {
                                    message.Message.Prepare(EncodingConstraint.SevenBit);
                                    dkimSigner.Sign(message.Message, headersToSign);
                                }
                                try
                                {
                                    if (!DisableSending)
                                    {
                                        MailDemonLog.Debug("Sending message to host {0}, from {1}, to {2}", host, message.Message.From, message.Message.To);
                                        await client.SendAsync(message.Message, cancelToken).TimeoutAfter(30000);

                                        MailDemonLog.Debug("Success message to host {0}, from {1}, to {2}", host, message.Message.From, message.Message.To);
                                    }

                                    // callback success
                                    message.Callback?.Invoke(message.Subscription, string.Empty);
                                }
                                catch (Exception exInner)
                                {
                                    MailDemonLog.Debug("Fail message to host {0}, from {1}, to {2} {3}", host, message.Message.From, message.Message.To, exInner);

                                    // TODO: Handle SmtpCommandException: Greylisted, please try again in 180 seconds
                                    // callback error
                                    message.Callback?.Invoke(message.Subscription, exInner.Message);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            // all messages fail for this domain
                            MailDemonLog.Error(host + " (" + toDomain + ")", ex);
                            await foreach (MailToSend message in messages)
                            {
                                message.Callback?.Invoke(message.Subscription, ex.Message);
                            }
                        }
                        finally
                        {
                            try
                            {
                                await client.DisconnectAsync(true, cancelToken);
                            }
                            catch
                            {
                            }
                        }
                        if (connected)
                        {
                            // we successfuly got a mail server, don't loop more ips
                            break;
                        }
                    }
                }
                catch (InvalidOperationException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    // dns error, move on to next mail server
                    MailDemonLog.Error(toDomain, ex);
                }
                if (connected)
                {
                    // we successfuly got a mail server, don't loop more dns entries
                    break;
                }
            }
        }
Beispiel #29
0
 public MxResponse(IDnsQueryResponse dnssecRecords)
 {
     this._Reponse = dnssecRecords;
 }
Beispiel #30
0
        public EtcdClient(string connectionString, int port         = 2379,
                          HttpClientHandler handler                 = null, bool ssl = false,
                          bool useLegacyRpcExceptionForCancellation = false)
        {
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new Exception("etcd connection string is empty.");
            }

            string[] hosts;

            if (connectionString.ToLowerInvariant().StartsWith("discovery-srv://"))
            {
                // Expecting it to be discovery-srv://{domain}/{name}
                // Examples:
                // discovery-srv://my-domain.local/ would expect entries for either _etcd-client-ssl._tcp.my-domain.local or _etcd-client._tcp.my-domain.local
                // discovery-srv://my-domain.local/project1 would expect entries for either _etcd-client-ssl-project1._tcp.my-domain.local or _etcd-client-project1._tcp.my-domain.local
                Uri          discoverySrv = new Uri(connectionString);
                LookupClient client       = new LookupClient(new LookupClientOptions
                {
                    UseCache = true
                });

                // SSL first ...
                string serviceName = "/".Equals(discoverySrv.AbsolutePath)
                    ? ""
                    : $"-{discoverySrv.AbsolutePath.Substring(startIndex: 1, length: discoverySrv.AbsolutePath.Length - 1)}";
                IDnsQueryResponse result = client.Query($"_etcd-client-ssl{serviceName}._tcp.{discoverySrv.Host}", QueryType.SRV);
                string            scheme = "https";
                if (result.HasError)
                {
                    scheme = "http";
                    // No SSL ...
                    result = client.Query($"_etcd-client{serviceName}._tcp.{discoverySrv.Host}", QueryType.SRV);
                    if (result.HasError)
                    {
                        throw new InvalidOperationException(result.ErrorMessage);
                    }
                }

                List <SrvRecord> results = result.Answers.OfType <SrvRecord>().OrderBy(a => a.Priority)
                                           .ThenByDescending(a => a.Weight).ToList();
                hosts = new string[results.Count];
                for (int index = 0; index < results.Count; index++)
                {
                    SrvRecord         srvRecord        = results[index];
                    DnsResourceRecord additionalRecord =
                        result.Additionals.FirstOrDefault(p => p.DomainName.Equals(srvRecord.Target));
                    string host = srvRecord.Target.Value;

                    if (additionalRecord is ARecord aRecord)
                    {
                        host = aRecord.Address.ToString();
                    }
                    else if (additionalRecord is CNameRecord cname)
                    {
                        host = cname.CanonicalName;
                    }

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

                    hosts[index] = $"{scheme}://{host}:{srvRecord.Port}";
                }
            }
            else
            {
                hosts = connectionString.Split(',');
            }

            List <Uri> nodes = new List <Uri>();

            for (int i = 0; i < hosts.Length; i++)
            {
                string host = hosts[i];
                if (host.Split(':').Length < 3)
                {
                    host += $":{Convert.ToString(port)}";
                }

                if (!(host.StartsWith(InsecurePrefix) || host.StartsWith(SecurePrefix)))
                {
                    if (ssl)
                    {
                        host = $"{SecurePrefix}{host}";
                    }
                    else
                    {
                        host = $"{InsecurePrefix}{host}";
                    }
                }

                nodes.Add(new Uri(host));
            }

            _balancer = new Balancer(nodes, handler, ssl, useLegacyRpcExceptionForCancellation);
        }