public async Task <ReverseDnsQueryResponse> QueryPtrAsync(IPAddress originalAddress)
        {
            IDnsQueryResponse response = await _lookupClient.QueryAsync(originalAddress.GetArpaName(), QueryType.PTR);

            return(new ReverseDnsQueryResponse(response.HasError, response.ErrorMessage,
                                               response.HasError
                    ? null
                    : response.Answers.OfType <PtrRecord>().Select(_ => _.PtrDomainName.Original).Distinct().ToList()));
        }
コード例 #2
0
        public async Task Ipv4LookupQueryIsCorrectlyFormed()
        {
            await _blocklistSourceProcessor.ProcessSource(new List <string> {
                "192.168.0.1"
            });

            A.CallTo(() => _lookupClient.QueryAsync("1.0.168.192.testSuffix", QueryType.A, QueryClass.IN, A <CancellationToken> ._))
            .MustHaveHappenedOnceExactly();
        }
コード例 #3
0
        public async Task CorrecltlyObtainsTlsRptRecord()
        {
            IDnsQueryResponse response = CreateResponse(new List <string> {
                TlsRptRecord
            });

            A.CallTo(() => _lookupClient.QueryAsync(A <string> ._, QueryType.TXT, QueryClass.IN, CancellationToken.None)).Returns(response);

            TlsRptRecordInfos tlsRptRecordInfos = await _dnsClient.GetTlsRptRecords(string.Empty);

            Assert.That(tlsRptRecordInfos.RecordsInfos.Count, Is.EqualTo(1));
            Assert.That(tlsRptRecordInfos.RecordsInfos[0].Record, Is.EqualTo(TlsRptRecord));
        }
        private async Task <IDnsQueryResponse> TryLookup(string query)
        {
            IDnsQueryResponse result = null;

            int attempt     = 0;
            int maxAttempts = 5;

            while (attempt < maxAttempts)
            {
                await Task.Delay(attempt *attempt * 1000);

                attempt++;

                try
                {
                    result = await _lookupClient.QueryAsync(query, QueryType.A);

                    if (!result.HasError)
                    {
                        break;
                    }
                }
                catch (Exception e)
                {
                    _log.LogInformation(e, $"Unable to make request to {query}");
                }
            }

            return(result);
        }
コード例 #5
0
        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));
        }
コード例 #6
0
ファイル: MockQueryResponse.cs プロジェクト: umlspec/Catalyst
        /// <summary>
        ///     Method mocks the response from a DNS server when querying for TXT records.
        /// </summary>
        /// <param name="domainName"></param>
        /// <param name="value"></param>
        /// <param name="lookupClient"></param>
        public static void CreateFakeLookupResult(string domainName, string value, ILookupClient lookupClient)
        {
            var queryResponse = Substitute.For <IDnsQueryResponse>();
            var answers       = DevDnsQueryResponse.BuildDnsResourceRecords(domainName, value);

            queryResponse.Answers.Returns(answers);
            lookupClient.QueryAsync(Arg.Is(domainName), Arg.Any <QueryType>())
            .Returns(Task.FromResult(queryResponse));
        }
コード例 #7
0
        public async Task <IPAddress?> GetIpAddressAsync(string hostName,
                                                         CancellationToken cancellationToken = default)
        {
            var hostString = DnsString.FromResponseQueryString(hostName);

            var tasks = new List <Task <IDnsQueryResponse> >(2);

            if (IpAddressMode != IpAddressMode.ForceIpv6)
            {
                tasks.Add(_lookupClient.QueryAsync(hostString, QueryType.A, cancellationToken: cancellationToken));
            }

            if (IpAddressMode != IpAddressMode.ForceIpv4)
            {
                tasks.Add(_lookupClient.QueryAsync(hostString, QueryType.AAAA, cancellationToken: cancellationToken));
            }

            await Task.WhenAll(tasks).ConfigureAwait(false);

            var addresses = tasks
                            .Where(p => !p.Result.HasError)
                            .SelectMany(p => p.Result.Answers)
                            .OfType <AddressRecord>()
                            .Select(p => p.Address)
                            .ToList();

            var preferredAddresses = IpAddressMode switch
            {
                IpAddressMode.PreferIpv4 => addresses.Where(p => p.AddressFamily == AddressFamily.InterNetwork),
                IpAddressMode.PreferIpv6 => addresses.Where(p => p.AddressFamily == AddressFamily.InterNetworkV6),
                IpAddressMode.Default => addresses.Where(p => p.AddressFamily == AddressFamily.InterNetworkV6),
                _ => null
            };

            var preferredIpAddress = preferredAddresses?.FirstOrDefault();

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

            return(addresses.FirstOrDefault());
        }
コード例 #8
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));
        }
コード例 #9
0
ファイル: Utilitiess.cs プロジェクト: feryt20/PayDel-Server
        public async Task <string> GetDomainIpAsync(string domain)
        {
            domain = domain.Replace("https://", "").Replace("http://", "").Replace("www.", "").TrimEnd('/');

            var result = await _lookupClient.QueryAsync(domain, QueryType.A);

            var record = result.Answers.ARecords().FirstOrDefault();

            return(record != null?record.Address.ToString() : "");
        }
コード例 #10
0
        public async Task <List <DkimSelectorRecords> > FetchDkimRecords(string domain, List <string> selectors)
        {
            List <DkimSelectorRecords> txtRecords = new List <DkimSelectorRecords>();

            foreach (string selector in selectors)
            {
                string host = $"{selector.Trim().ToLower()}._domainkey.{domain.Trim().ToLower()}";

                DkimSelectorRecords record;

                try
                {
                    IDnsQueryResponse response = await _lookupClient.QueryAsync(host, QueryType.TXT);

                    if (response.HasError)
                    {
                        _log.LogInformation($"Host: {host}");

                        Guid Id1 = Guid.Parse("3956C316-5A86-47D3-B5DD-5F5418C0D5C8");

                        record = new DkimSelectorRecords(Id1, selector, null, null, response.MessageSize,
                                                         string.Format(DkimServiceResources.DnsLookupFailedErrorMessage, host, response.ErrorMessage),
                                                         string.Format(DkimServiceMarkdownResources.DnsLookupFailedErrorMessage, host, response.ErrorMessage));
                    }
                    else
                    {
                        Guid Id2 = Guid.Parse("FB710D51-5F2B-47EA-A836-FF4CCFDC30A2");

                        IEnumerable <CNameRecord> cnameRecords = response.Answers.OfType <CNameRecord>().ToList();

                        string dkimCNameRecords = cnameRecords.Any()
                            ? cnameRecords.First().CanonicalName
                            : null;

                        List <DkimTxtRecord> dkimTxtRecords = response.Answers.OfType <TxtRecord>().Select(_ => new DkimTxtRecord(_.Text.Select(r => r.Escape()).ToList())).ToList();

                        record = new DkimSelectorRecords(Id2, selector, dkimTxtRecords, dkimCNameRecords, response.MessageSize);
                    }
                }
                catch (Exception ex)
                {
                    Guid Id3 = Guid.Parse("8DE3D4F8-F1BD-45FF-B289-9A7D23FDC3F4");

                    record = new DkimSelectorRecords(Id3, selector, null, null, 0, ex.Message, DkimServiceMarkdownResources.UnknownErrorWhenPollingErrorMessage);

                    string formatString = $"{{ExceptionType}} occured when polling DKIM record for host {{Host}} {Environment.NewLine} {{StackTrace}}";

                    _log.LogWarning(formatString, host, ex.GetType().Name, ex.StackTrace);
                }

                txtRecords.Add(record);
            }

            return(txtRecords);
        }
コード例 #11
0
ファイル: DnsUnitTests.cs プロジェクト: umlspec/Catalyst
        Dns_GetTxtRecords_from_list_should_return_IDnsQueryResponse_for_valid_list_of_strings_param_even_when_one_lookup_is_null()
        {
            var urlList = new List <string>();
            var domain1 = "seed1.catalystnetwork.io";
            var domain2 = "seed2.catalystnetwork.io";

            urlList.Add(domain1);
            urlList.Add(domain2);

            MockQueryResponse.CreateFakeLookupResult(domain1, "value1", _lookupClient);

            _lookupClient.QueryAsync(Arg.Is(domain2), Arg.Any <QueryType>())
            .Throws(new InvalidOperationException("failed"));

            var responses = await _dns.GetTxtRecordsAsync(urlList);

            responses.Count.Should().Be(1);
            responses.Should().Contain(r => r.Answers[0].DomainName.Value.StartsWith(domain1));
            responses.Should().NotContainNulls();
        }
コード例 #12
0
        public async Task ItShouldContainTheRecordsWhenSuccessful()
        {
            string[] record1 = { "record1" };
            string[] record2 = { "record2-part1 ", "record2-part2" };
            A.CallTo(() => _dnsResponse.Answers)
            .Returns(CreateDnsResponse(record1, record2));

            A.CallTo(() => _lookupClient.QueryAsync(A <string> ._, QueryType.TXT, A <QueryClass> ._, A <CancellationToken> ._))
            .Returns(Task.FromResult(_dnsResponse));

            List <DkimSelectorRecords> response = await _client.FetchDkimRecords("ncsc.gov.uk", new List <string> {
                "selector1"
            });

            Assert.AreEqual(response[0].Records[0].Record, "record1");
            Assert.That(response[0].Records[0].RecordParts.SequenceEqual(record1), Is.True);
            Assert.AreEqual(response[0].Records[1].Record, "record2-part1 record2-part2");
            Assert.That(response[0].Records[1].RecordParts.SequenceEqual(record2), Is.True);
            Assert.That(response[0].Error, Is.Null);
        }
コード例 #13
0
ファイル: DnsClient.cs プロジェクト: umlspec/Catalyst
        private async Task <IDnsQueryResponse> QueryAsync(string hostname, QueryType type)
        {
            Guard.Argument(hostname, nameof(hostname))
            .NotNull()
            .NotEmpty()
            .NotWhiteSpace();

            try
            {
                return(await _client.QueryAsync(hostname, type));
            }
            catch (Exception)
            {
                return(null);
            }
        }
コード例 #14
0
ファイル: FixedDnsClient.cs プロジェクト: zhenguang/win-app
        public async Task <string> Resolve(string host, CancellationToken token)
        {
            if (IPAddress.TryParse(host, out _))
            {
                return(host);
            }

            var result = await _lookupClient.QueryAsync(host, QueryType.A, cancellationToken : token);

            if (result.HasError)
            {
                return(null);
            }

            var record = result.Answers.ARecords().FirstOrDefault();

            return(record?.Address.MapToIPv4().ToString());
        }
コード例 #15
0
        public override async Task OnConnectedAsync()
        {
            if (Context.GetHttpContext().Request.Headers.TryGetValue("Authorization", out var value))
            {
                var arr    = value.ToString().Replace("Bearer ", string.Empty).Split(':');
                var record = (await lookupClient.QueryAsync(arr[0], QueryType.A)).Answers.ARecords().FirstOrDefault();
                if (record != null)
                {
                    var target = new SocketConnect(logger, connectionFactory);
                    await target.ConnectAsync(record.Address, int.Parse(arr[1]));

                    logger.LogTrace($"成功连接到:{arr[0]} {record.Address}:{arr[1]}");
                    Tagets.TryAdd(Context.ConnectionId, target);
                }
            }

            await base.OnConnectedAsync();
        }
コード例 #16
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));
        }
コード例 #17
0
        private async IAsyncEnumerable <DnsString> FetchMxRecordsForDomain(MailboxAddress target)
        {
            _logger.LogInformation("Searching for target mail server");
            var host = target.Address.Split('@')[1];

            _logger.LogDebug("Extracted host from address ({host})", host);
            if (host.StartsWith("."))
            {
                _logger.LogTrace("Host had a leading period. Removing");
                host = host.Remove(0, 1);
            }
            _logger.LogDebug("Running DNS query");
            var result = await _lookupClient.QueryAsync(host, QueryType.MX);

            var mxRecords = result.Answers.MxRecords().OrderBy(x => x.Preference);

            foreach (var record in mxRecords)
            {
                yield return(record.Exchange);
            }
        }
コード例 #18
0
        public async Task <IEnumerable <HostEndpoint> > GetDnsSrvEntriesAsync(Uri bootstrapUri,
                                                                              CancellationToken cancellationToken = default)
        {
            if (!EnableDnsSrvResolution)
            {
                return(Enumerable.Empty <HostEndpoint>());
            }

            var query  = string.Concat(bootstrapUri.Scheme == "couchbases" ? TlsServicePrefix : DefaultServicePrefix, bootstrapUri.Host);
            var result = await _lookupClient.QueryAsync(query, QueryType.SRV,
                                                        cancellationToken : cancellationToken).ConfigureAwait(false);

            if (result.HasError)
            {
                _logger.LogInformation("There was an error attempting to resolve hosts using DNS-SRV - {errorMessage}", result.ErrorMessage);
                return(Enumerable.Empty <HostEndpoint>());
            }

            var records = result.Answers.SrvRecords().ToList();

            if (!records.Any())
            {
                _logger.LogInformation("No DNS SRV records found.");
                return(Enumerable.Empty <HostEndpoint>());
            }

            return(records
                   .OrderBy(record => record.Priority)
                   .Select(record =>
            {
                var host = record.Target.Value;
                if (host.EndsWith("."))
                {
                    var index = host.LastIndexOf(".", StringComparison.Ordinal);
                    host = host.Substring(0, index);
                }

                return new HostEndpoint(host, record.Port);
            }));
        }
コード例 #19
0
        public async Task <IEnumerable <Uri> > GetDnsSrvEntriesAsync(Uri bootstrapUri)
        {
            var query  = string.Concat(DefaultServicePrefix, bootstrapUri.Host);
            var result = await LookupClient.QueryAsync(query, QueryType.SRV);

            if (result.HasError)
            {
                Logger.LogInformation($"There was an error attempting to resolve hosts using DNS-SRV - {result.ErrorMessage}");
                return(EmptyList);
            }

            var records = result.Answers.SrvRecords();

            if (!records.Any())
            {
                Logger.LogInformation($"No DNS SRV records found.");
                return(EmptyList);
            }

            return(records
                   .OrderBy(record => record.Priority)
                   .Select(record =>
            {
                var host = record.Target.Value;
                if (host.EndsWith("."))
                {
                    var index = host.LastIndexOf(".");
                    host = host.Substring(0, index);
                }
                return new UriBuilder
                {
                    Scheme = bootstrapUri.Scheme,
                    Host = host,
                    Port = record.Port
                }.Uri;
            }));
        }
コード例 #20
0
        private async Task <Domain> GetDomain(string nameDomain)
        {
            var response = await WhoisClient.QueryAsync(nameDomain);

            var result = await _lookupClient.QueryAsync(nameDomain, QueryType.ANY);

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

            var hostResponse = await WhoisClient.QueryAsync(ip);

            Domain domain = new Domain
            {
                Name      = nameDomain,
                Ip        = ip,
                UpdatedAt = DateTime.Now,
                WhoIs     = response.Raw,
                Ttl       = record?.TimeToLive ?? 0,
                HostedAt  = hostResponse.OrganizationName
            };

            return(domain);
        }
コード例 #21
0
        /// <summary>
        /// Attempts a lookup from DNS.
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="startQuery"></param>
        /// <param name="preferIPv6"></param>
        /// <param name="ct"></param>
        /// <returns></returns>
        private static async Task <SIPEndPoint> SIPLookupAsync(
            SIPURI uri,
            QueryType startQuery,
            bool preferIPv6,
            CancellationToken ct)
        {
            SIPEndPoint result    = null;
            QueryType   queryType = startQuery;

            string host = uri.MAddrOrHostAddress;
            int    port = SIPConstants.GetDefaultPort(uri.Protocol);

            if (ushort.TryParse(uri.HostPort, out var uriPort))
            {
                port = uriPort;
            }

            bool isDone = false;

            while (!isDone && !ct.IsCancellationRequested)
            {
                switch (queryType)
                {
                case QueryType.SRV:

                    try
                    {
                        var srvProtocol = SIPServices.GetSRVProtocolForSIPURI(uri);
                        var srvResult   = await _lookupClient.ResolveServiceAsync(uri.MAddrOrHostAddress, uri.Scheme.ToString(), srvProtocol.ToString()).ConfigureAwait(false);

                        (var srvHost, var srvPort) = GetHostAndPortFromSrvResult(srvResult);
                        if (srvHost != null)
                        {
                            host = srvHost;
                            port = srvPort != 0 ? srvPort : port;

                            logger.LogDebug($"SIP DNS SRV for {uri} resolved to {host} and port {port}.");
                        }
                    }
                    catch (Exception srvExcp)
                    {
                        logger.LogWarning(srvExcp, $"SIPDNS exception on SRV lookup. {srvExcp.Message}.");
                    }
                    queryType = preferIPv6 ? QueryType.AAAA : QueryType.A;

                    break;

                case QueryType.AAAA:

                    try
                    {
                        var aaaaResult = await _lookupClient.QueryAsync(host, UseANYLookups?QueryType.ANY : QueryType.AAAA, QueryClass.IN, ct).ConfigureAwait(false);

                        if (aaaaResult?.Answers?.Count > 0)
                        {
                            result = GetFromLookupResult(uri.Protocol, aaaaResult.Answers.AddressRecords().OrderByDescending(x => x.RecordType).First(), port);
                            isDone = true;
                        }
                        else
                        {
                            queryType = QueryType.A;
                        }
                    }
                    catch (Exception srvExcp)
                    {
                        logger.LogWarning(srvExcp, $"SIPDNS exception on AAAA lookup. {srvExcp.Message}.");
                        queryType = QueryType.A;
                    }

                    break;

                default:
                    // A record lookup.
                    try
                    {
                        var aResult = await _lookupClient.QueryAsync(host, QueryType.A, QueryClass.IN, ct).ConfigureAwait(false);

                        if (aResult != null)
                        {
                            if (aResult.Answers?.Count > 0)
                            {
                                result = GetFromLookupResult(uri.Protocol, aResult.Answers.AddressRecords().First(), port);
                            }
                            else
                            {
                                // We got a result back but it was empty indicating an unresolvable host or
                                // some other DNS error condition.
                                result = SIPEndPoint.Empty;
                            }
                        }
                    }
                    catch (Exception srvExcp)
                    {
                        logger.LogWarning(srvExcp, $"SIPDNS exception on A lookup. {srvExcp.Message}.");
                        result = SIPEndPoint.Empty;
                    }

                    isDone = true;
                    break;
                }
            }

            return(result);
        }