/// <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);
        }
        } // End Class DbDnsRecord


        static async Task <bool> ResolveMessage(DnsMessage query, QueryReceivedEventArgs e, DnsMessage response)
        {
            DbDnsRecord rec = null;

            using (System.Data.Common.DbCommand cmd = s_sql.CreateCommand(@"
-- DECLARE @in_recordType int 
-- DECLARE @in_recordName varchar(4000) 

-- SET @in_recordType = 1 -- A 
-- SET @in_recordName = 'vortex.data.microsoft.com' 


SELECT 
	 REC_Id
	--,T_Records.REC_DOM_Id
	,T_Records.REC_RT_Id
	,T_Records.REC_Name
	,T_Records.REC_Content
	,T_Records.REC_ResponsibleName
	,COALESCE(T_Records.REC_TTL, 100) AS REC_TTL 
	,T_Records.REC_Prio
	,T_Records.REC_Weight
	,T_Records.REC_Port
	,T_Records.REC_SerialNumber
	,T_Records.REC_RefreshInterval
	,T_Records.REC_RetryInterval
	,T_Records.REC_ExpireInterval
	,T_Records.REC_NegativeCachingTTL
	,T_Records.REC_AfsSubType
	,T_Records.REC_ChangeDate
FROM T_Records 
WHERE REC_RT_Id	= @in_recordType 
AND T_Records.REC_Name = @in_recordName 
;
"))
            {
                try
                {
                    string name = query.Questions[0].Name.ToString();

                    s_sql.AddParameter(cmd, "in_recordType", (int)query.Questions[0].RecordType);
                    s_sql.AddParameter(cmd, "in_recordName", name);

                    // TODO: Can return multiple records...
                    rec = s_sql.GetClass <DbDnsRecord>(cmd);
                }
                catch (System.Exception ex)
                {
                    System.Console.WriteLine(ex.Message);
                    System.Console.WriteLine(ex.StackTrace);
                }
            } // End Using cmd

            if (rec != null)
            {
                int ttl = 3600;

                DnsRecordBase record = null;

                // https://blog.dnsimple.com/2015/04/common-dns-records/
                // https://en.wikipedia.org/wiki/List_of_DNS_record_types
                switch ((RecordType)rec.REC_RT_Id)
                {
                case RecordType.Soa:
                    // SoaRecord(DomainName name, int timeToLive, DomainName masterName
                    //  , DomainName responsibleName, uint serialNumber, int refreshInterval
                    //  , int retryInterval, int expireInterval, int negativeCachingTTL)
                    record = new ARSoft.Tools.Net.Dns.SoaRecord(
                        DomainName.Parse(rec.REC_Name)
                        , rec.REC_TTL.Value
                        , DomainName.Parse(rec.REC_Content)
                        , DomainName.Parse(rec.REC_ResponsibleName)
                        , rec.REC_SerialNumber.Value
                        , rec.REC_RefreshInterval.Value
                        , rec.REC_RetryInterval.Value
                        , rec.REC_ExpireInterval.Value
                        , rec.REC_NegativeCachingTTL.Value
                        );
                    break;

                case RecordType.Ns:
                    record = new ARSoft.Tools.Net.Dns.NsRecord(DomainName.Parse(rec.REC_Name), ttl, DomainName.Parse(rec.REC_Content));
                    break;

                case RecordType.Srv:
                    // SrvRecord(DomainName name, int timeToLive, ushort priority, ushort weight, ushort port, DomainName target)
                    record = new ARSoft.Tools.Net.Dns.SrvRecord(DomainName.Parse(rec.REC_Name), rec.REC_TTL.Value, (ushort)rec.REC_Prio.Value, (ushort)rec.REC_Weight.Value, (ushort)rec.REC_Port.Value, DomainName.Parse(rec.REC_Content));
                    break;

                // https://www.openafs.org/
                // https://en.wikipedia.org/wiki/OpenAFS
                // http://www.rjsystems.nl/en/2100-dns-discovery-openafs.php
                // OpenAFS is an open source implementation of the Andrew distributed file system(AFS).
                case RecordType.Afsdb:
                    // http://www.rjsystems.nl/en/2100-dns-discovery-openafs.php

                    record = new ARSoft.Tools.Net.Dns.AfsdbRecord(DomainName.Parse(rec.REC_Name), rec.REC_TTL.Value, (AfsdbRecord.AfsSubType)(uint) rec.REC_AfsSubType.Value, DomainName.Parse(rec.REC_Content));
                    break;

                // A DNS-based Authentication of Named Entities (DANE) method
                // for publishing and locating OpenPGP public keys in DNS
                // for a specific email address using an OPENPGPKEY DNS resource record.
                case RecordType.OpenPGPKey:
                    byte[] publicKey = null;

                    // hexdump(sha256(truncate(utf8(ocalpart), 28)
                    // https://www.huque.com/bin/openpgpkey
                    // The OPENPGPKEY DNS record is specied in RFC 7929.
                    // The localpart of the uid is encoded as a DNS label
                    // containing the hexdump of the SHA-256 hash
                    // of the utf-8 encoded localpart, truncated to 28 octets.
                    // Normally the "Standard" output format should be used.
                    // The "Generic Encoding" output format is provided to help work
                    // with older DNS software that does not yet understand the OPENPGPKEY record type.
                    record = new ARSoft.Tools.Net.Dns.OpenPGPKeyRecord(DomainName.Parse(rec.REC_Name), ttl, publicKey);
                    break;

                // Canonical name records, or CNAME records, are often called alias records because they map an alias to the canonical name. When a name server finds a CNAME record, it replaces the name with the canonical name and looks up the new name.
                case RecordType.CName:
                    record = new ARSoft.Tools.Net.Dns.CNameRecord(DomainName.Parse(rec.REC_Name), rec.REC_TTL.Value, DomainName.Parse(rec.REC_Content));
                    break;

                case RecordType.Ptr:
                    record = new ARSoft.Tools.Net.Dns.PtrRecord(DomainName.Parse(rec.REC_Name), rec.REC_TTL.Value, DomainName.Parse(rec.REC_Content));
                    break;

                case RecordType.A:
                    record = new ARSoft.Tools.Net.Dns.ARecord(DomainName.Parse(rec.REC_Name), rec.REC_TTL.Value, System.Net.IPAddress.Parse(rec.REC_Content));
                    break;

                case RecordType.Aaaa:
                    record = new ARSoft.Tools.Net.Dns.AaaaRecord(DomainName.Parse(rec.REC_Name), rec.REC_TTL.Value, System.Net.IPAddress.Parse(rec.REC_Content));
                    break;

                case RecordType.Mx:
                    record = new ARSoft.Tools.Net.Dns.MxRecord(DomainName.Parse(rec.REC_Name), rec.REC_TTL.Value, 0, DomainName.Parse(rec.REC_Content));
                    break;

                case RecordType.Txt:
                    record = new ARSoft.Tools.Net.Dns.TxtRecord(DomainName.Parse(rec.REC_Name), rec.REC_TTL.Value, rec.REC_Content);
                    break;

                case RecordType.SshFp:
                    // https://unix.stackexchange.com/questions/121880/how-do-i-generate-sshfp-records

                    // SshFpRecord(DomainName name, int timeToLive, SshFpAlgorithm algorithm
                    //     , SshFpFingerPrintType fingerPrintType, byte[] fingerPrint)
                    ARSoft.Tools.Net.Dns.SshFpRecord.SshFpAlgorithm sfa = ARSoft.Tools.Net.Dns.SshFpRecord
                                                                          .SshFpAlgorithm.Rsa;

                    ARSoft.Tools.Net.Dns.SshFpRecord.SshFpFingerPrintType sfp = ARSoft.Tools.Net.Dns.SshFpRecord
                                                                                .SshFpFingerPrintType.Sha256;

                    byte[] fp = null;

                    record = new ARSoft.Tools.Net.Dns.SshFpRecord(DomainName.Parse(rec.REC_Name), rec.REC_TTL.Value, sfa, sfp, fp);
                    break;

                default:
                    break;
                } // End Switch

                if (record != null)
                {
                    response.AnswerRecords.Add(record);
                }

                response.ReturnCode = ReturnCode.NoError;
                e.Response          = response;
                return(await Task <bool> .FromResult(true));
            } // End if (rec != null)

            return(await Task <bool> .FromResult(false));
        } // End Function ResolveMessage
示例#3
0
        /// <summary>
        ///   Resolves specified records as an asynchronous operation.
        /// </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>
        /// <param name="token"> The token to monitor cancellation requests </param>
        /// <returns> A list of matching <see cref="DnsRecordBase">records</see> </returns>
        public async Task <DnsSecResult <T> > ResolveSecureAsync <T>(DomainName name, RecordType recordType = RecordType.A, RecordClass recordClass = RecordClass.INet, CancellationToken token = default(CancellationToken))
            where T : DnsRecordBase
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name), "Name must be provided");
            }

            DnsCacheRecordList <T> cacheResult;

            if (_cache.TryGetRecords(name, recordType, recordClass, out cacheResult))
            {
                return(new DnsSecResult <T>(cacheResult, cacheResult.ValidationResult));
            }

            DnsMessage msg = await _dnsClient.ResolveAsync(name, recordType, recordClass, new DnsQueryOptions()
            {
                IsEDnsEnabled      = true,
                IsDnsSecOk         = true,
                IsCheckingDisabled = true,
                IsRecursionDesired = true
            }, token).ConfigureAwait(false);

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

            DnsSecValidationResult validationResult;

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

            if (cName != null)
            {
                DnsSecValidationResult cNameValidationResult = await _validator.ValidateAsync(name, RecordType.CName, recordClass, msg, new List <CNameRecord>() { cName }, null, token).ConfigureAwait(false);

                if ((cNameValidationResult == DnsSecValidationResult.Bogus) || (cNameValidationResult == DnsSecValidationResult.Indeterminate))
                {
                    throw new DnsSecValidationException("CNAME record could not be validated");
                }

                var records = msg.AnswerRecords.Where(x => (x.RecordType == recordType) && (x.RecordClass == recordClass) && x.Name.Equals(cName.CanonicalName)).OfType <T>().ToList();
                if (records.Count > 0)
                {
                    DnsSecValidationResult recordsValidationResult = await _validator.ValidateAsync(cName.CanonicalName, recordType, recordClass, msg, records, null, token).ConfigureAwait(false);

                    if ((recordsValidationResult == DnsSecValidationResult.Bogus) || (recordsValidationResult == DnsSecValidationResult.Indeterminate))
                    {
                        throw new DnsSecValidationException("CNAME matching records could not be validated");
                    }

                    validationResult = cNameValidationResult == recordsValidationResult ? cNameValidationResult : DnsSecValidationResult.Unsigned;
                    _cache.Add(name, recordType, recordClass, records, validationResult, Math.Min(cName.TimeToLive, records.Min(x => x.TimeToLive)));

                    return(new DnsSecResult <T>(records, validationResult));
                }

                var cNameResults = await ResolveSecureAsync <T>(cName.CanonicalName, recordType, recordClass, token).ConfigureAwait(false);

                validationResult = cNameValidationResult == cNameResults.ValidationResult ? cNameValidationResult : DnsSecValidationResult.Unsigned;

                if (cNameResults.Records.Count > 0)
                {
                    _cache.Add(name, recordType, recordClass, cNameResults.Records, validationResult, Math.Min(cName.TimeToLive, cNameResults.Records.Min(x => x.TimeToLive)));
                }

                return(new DnsSecResult <T>(cNameResults.Records, validationResult));
            }

            List <T> res = msg.AnswerRecords.Where(x => (x.RecordType == recordType) && (x.RecordClass == recordClass) && x.Name.Equals(name)).OfType <T>().ToList();

            validationResult = await _validator.ValidateAsync(name, recordType, recordClass, msg, res, null, token).ConfigureAwait(false);

            if ((validationResult == DnsSecValidationResult.Bogus) || (validationResult == DnsSecValidationResult.Indeterminate))
            {
                throw new DnsSecValidationException("Response records could not be validated");
            }

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

            return(new DnsSecResult <T>(res, validationResult));
        }