} // 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
Example #2
0
        private static void OnQueryReceived(object sender, QueryReceivedEventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                DnsMessage message = e.Query as DnsMessage;

                message.IsQuery = false;

                if (message == null || message.Questions.Count == 0)
                {
                    e.Response = message;
                    message.ReturnCode = ReturnCode.ServerFailure;
                    e.Response = message;
                    Console.WriteLine(sb);
                    return;
                }

                //Log DNS query
                sb.AppendFormat("* {0}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                for (int i = 0; i < message.Questions.Count; i++)
                {
                    sb.AppendFormat("[{0}]\t{1}\t{2}\r\n",
                        i, message.Questions[i].RecordType.ToString(), message.Questions[i].Name);
                }

                if (message.Questions.Count > 1)
                {
                    sb.AppendFormat("Response: (x) ServerFailure -- Multiple questions\r\n");
                    e.Response = message;
                    message.ReturnCode = ReturnCode.ServerFailure;
                    e.Response = message;
                    Console.WriteLine(sb);
                    return;
                }

                DnsQuestion question = message.Questions[0];

                if (!question.Name.Equals(domain, StringComparison.CurrentCultureIgnoreCase)
                    && !question.Name.EndsWith(string.Concat(".", domain), StringComparison.CurrentCultureIgnoreCase))
                {
                    e.Response = message;
                    message.ReturnCode = ReturnCode.ServerFailure;
                    e.Response = message;
                    sb.AppendFormat("Response: (x) ServerFailure -- Domain \"{0}\" is invalid\r\n", question.Name);
                    Console.WriteLine(sb);
                    return;
                }

                if (question.RecordType == RecordType.Txt)
                {
                    //MX
                    message.ReturnCode = ReturnCode.NoError;
                    message.AnswerRecords.Add(new TxtRecord(domain, ttlSeconds, "Hello world"));
                    message.ReturnCode = ReturnCode.NoError;
                    e.Response = message;
                    sb.AppendFormat("Response: OK!\r\n", question.Name);
                    Console.WriteLine(sb);
                    return;
                }
                else if (question.RecordType == RecordType.A)
                {
                    //A

                    string subdomain = question.Name.Substring(0, question.Name.LastIndexOf(domain));
                    if (subdomain.Length > 0)
                        subdomain = subdomain.Substring(0, subdomain.Length - 1); //remove o ponto

                    if (subdomain.Length == 0)
                    {
                        //raiz do domínio
                        var record = new ARecord(question.Name, ttlSeconds, System.Net.IPAddress.Parse("192.168.1.1"));
                        message.AnswerRecords.Add(record);
                        message.ReturnCode = ReturnCode.NoError;
                        e.Response = message;
                        sb.AppendFormat("Response: OK!\r\n", question.Name);
                        return;
                    }
                    else
                    {
                        //subdomínios

                        if (subdomain.Length > 0 && subdomain.StartsWith("local_", StringComparison.CurrentCultureIgnoreCase))
                        {
                            //recebe: local_192-168-10-10.[domain]  e retorna: "192.168.10.10"

                            string ipString = subdomain.Substring("local_".Length);
                            ipString = ipString.Replace("-", ".");

                            System.Net.IPAddress ipAddress;
                            if (System.Net.IPAddress.TryParse(ipString, out ipAddress))
                            {
                                var record = new ARecord(question.Name, ttlSeconds, ipAddress);
                                message.AnswerRecords.Add(record);
                                message.ReturnCode = ReturnCode.NoError;
                                e.Response = message;
                                sb.AppendFormat("Response: OK!\r\n", question.Name);
                                Console.WriteLine(sb);
                                return;
                            }
                            else
                            {
                                sb.AppendFormat("Response: (x) ServerFailure -- Invalid IP \"{0}\" invalid. Example of subdomain valid: \"local_192-168-10-10\"\r\n", ipString);
                                message.ReturnCode = ReturnCode.ServerFailure;
                                e.Response = message;
                                Console.WriteLine(sb);
                                return;
                            }
                        }
                        else
                        {
                            sb.AppendFormat("Response: (x) ServerFailure -- Subdomain \"{0}\" invalid. Example of subdomain valid: \"local_192-168-10-10\"\r\n", subdomain);
                            message.ReturnCode = ReturnCode.ServerFailure;
                            e.Response = message;
                            Console.WriteLine(sb);
                            return;
                        }
                    }
                }

                sb.AppendFormat("Response: (x) ServerFailure --  Record Type \"{0}\" invalid\r\n", question.RecordType.ToString());
                message.ReturnCode = ReturnCode.ServerFailure;
                e.Response = message;
            }
            catch (System.Exception ex)
            {
                sb.AppendFormat("{0} EXCEPTION: {1}\r\n{2}\r\n\r\n",
                        DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
                        ex.Message,
                        ex.StackTrace);
            }

            Console.WriteLine(sb.ToString());
        }