Ejemplo n.º 1
0
        /// <summary>
        /// Acts as a Factory which reads QType from Immutable IResource param to return concrete type which implements IResource.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="position"></param>
        /// <param name="resource"></param>
        /// <returns></returns>
        private static IResource ReadAnswer(ref byte[] data, int position, IResource resource)
        {
            switch (resource.Type)
            {
            case QType.TXT:
                return(TxtRecord.Parse(data, position, resource));

            case QType.MX:
                return(MxRecord.Parse(data, position, resource));

            case QType.A:
                return(ARecord.Parse(data, position, resource));

            case QType.SOA:
                return(SoaRecord.Parse(data, position, resource));

            case QType.NS:
                return(NsRecord.Parse(data, position, resource));

            case QType.CNAME:
                return(CNameRecord.Parse(data, position, resource));
            }

            return(null); //TODO: Thrown Exception Here
        }
Ejemplo n.º 2
0
        public DnsRecord ParseCNAME(string[] args)
        {
            string domainName = args.GetRequiredValue(0);
            string cname      = args.GetRequiredValue(1);
            int    ttl        = this.ValidateTTL(args.GetOptionalValue <int>(2, 0));
            string notes      = args.GetOptionalValue(3, string.Empty);

            CNameRecord cnameRecord = new CNameRecord(domainName, cname)
            {
                TTL = ttl
            };
            DnsRecord dnsRecord = new DnsRecord(domainName, DnsStandard.RecordType.CNAME, cnameRecord.Serialize(), notes);

            return(dnsRecord);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Tests equality between this CName record and the other <paramref name="record"/>.
        /// </summary>
        /// <param name="record">The other record.</param>
        /// <returns><c>true</c> if the RRs are equal, <c>false</c> otherwise.</returns>
        public override bool Equals(DnsResourceRecord record)
        {
            if (!base.Equals(record))
            {
                return(false);
            }

            CNameRecord cnameRecord = record as CNameRecord;

            if (cnameRecord == null)
            {
                return(false);
            }

            return(DnsStandard.Equals(m_name, cnameRecord.CName));
        }
Ejemplo n.º 4
0
        /// <summary>
        ///     Construct a resource record from a pointer to a byte array
        /// </summary>
        /// <param name="pointer">the position in the byte array of the record</param>
        internal ResourceRecord(Pointer pointer)
        {
            // extract the domain, question type, question class and Ttl
            Domain = pointer.ReadDomain();
            Type   = (DnsType)pointer.ReadShort();
            Class  = (DnsClass)pointer.ReadShort();
            Ttl    = pointer.ReadInt();

            // the next short is the record length, we only use it for unrecognized record types
            int recordLength = pointer.ReadShort();

            // and create the appropriate RDATA record based on the dnsType
            switch (Type)
            {
            case DnsType.NS:
                Record = new NSRecord(pointer);
                break;

            case DnsType.MX:
                Record = new MXRecord(pointer);
                break;

            case DnsType.ANAME:
                Record = new ANameRecord(pointer);
                break;

            case DnsType.CNAME:
                Record = new CNameRecord(pointer);
                break;

            case DnsType.SOA:
                Record = new SoaRecord(pointer);
                break;

            case DnsType.TXT:
                Record = new TXTRecord(pointer, recordLength);
                break;

            default:
            {
                // move the pointer over this unrecognized record
                pointer.Seek(recordLength);
                break;
            }
            }
        }
Ejemplo n.º 5
0
    /// <summary>
    /// Do DNS queries to get any CNAME records associated with the Traffic Manager URL the user has entered.
    /// This will get the currently available endpoint that's responding to the Traffic Manager.
    /// Puts the string output of all of the Traffic Manager CNAME records into the AppService argument so the list can be used later.
    /// </summary>
    /// <param name="appService">The object that holds all the information the user has given, including the Traffic Manager name.</param>
    public static void GetTrafficManagerCNameRecords(AppService appService, DNSCheckErrors dnsCheckErrors)
    {
        //IDnsResolver resolver = new DnsStubResolver();

        string fullTMURL         = appService.TmName + "." + appService.TrafficManagerURLEnding;
        string fullTMURLDNSStyle = fullTMURL + ".";

        try
        {
            //List<CNameRecord> trafficManagerCNameRecords = DnsResolverExtensions.Resolve<CNameRecord>(resolver, appService.TmName + "." + appService.TrafficManagerURLEnding, RecordType.CName, RecordClass.Any);

            List <string> trafficManagerCNames = new List <string>();

            DnsMessage dnsMessage = DnsClient.Default.Resolve(DomainName.Parse(fullTMURL), RecordType.CName);
            if ((dnsMessage == null) || ((dnsMessage.ReturnCode != ReturnCode.NoError) && (dnsMessage.ReturnCode != ReturnCode.NxDomain)))
            {
                throw new Exception("DNS request failed");
            }
            else
            {
                foreach (DnsRecordBase dnsRecord in dnsMessage.AnswerRecords)
                {
                    if (dnsRecord.RecordType == RecordType.CName && dnsRecord.Name.ToString() == fullTMURLDNSStyle)
                    {
                        CNameRecord trafficManagerCName = dnsRecord as CNameRecord;
                        if (trafficManagerCName != null)
                        {
                            trafficManagerCNames.Add(trafficManagerCName.CanonicalName.ToString());
                        }
                    }
                }
            }

            /*foreach (CNameRecord trafficManagerCName in trafficManagerCNameRecords)
             * {
             *  trafficManagerCNames.Add(trafficManagerCName.CanonicalName.ToString());
             * } */

            appService.TrafficManagerCNameRecords = trafficManagerCNames;
        }
        catch
        {
            dnsCheckErrors.trafficManagerCNameRecordLookupFailed = true;
            dnsCheckErrors.currentDNSFailures++;
        }
    }
Ejemplo n.º 6
0
    /// <summary>
    /// Do DNS queries to get any CNAME records associated with the custom hostname the user has entered.
    /// Puts the string output of all of the CNAME records into the AppService argument so the list can be used later.
    /// </summary>
    /// <param name="appService">The object that holds all of the information the user has given, including the custom hostname.</param>
    public static void GetHostnameCNameRecords(AppService appService, DNSCheckErrors dnsCheckErrors)
    {
        // IDnsResolver resolver = new DnsStubResolver();

        // This is moved into the AppService class itself to prevent making the string multiple times
        // string fullHostnameDNSStyle = appService.CustomHostname + ".";

        try
        {
            // List<CNameRecord> cNameRecords = DnsResolverExtensions.Resolve<CNameRecord>(resolver, appService.CustomHostname, RecordType.CName, RecordClass.Any);

            List <string> cNames = new List <string>();

            DnsMessage dnsMessage = DnsClient.Default.Resolve(DomainName.Parse(appService.CustomHostname), RecordType.CName);
            if ((dnsMessage == null) || ((dnsMessage.ReturnCode != ReturnCode.NoError) && (dnsMessage.ReturnCode != ReturnCode.NxDomain)))
            {
                throw new Exception("DNS request failed");
            }
            else
            {
                foreach (DnsRecordBase dnsRecord in dnsMessage.AnswerRecords)
                {
                    if (dnsRecord.RecordType == RecordType.CName && dnsRecord.Name.ToString() == appService.CustomHostnameDNSStyle)
                    {
                        CNameRecord cName = dnsRecord as CNameRecord;
                        if (cName != null)
                        {
                            cNames.Add(cName.CanonicalName.ToString());
                        }
                    }
                }
            }

            /*foreach (CNameRecord cName in cNameRecords)
             * {
             *  cNames.Add(cName.CanonicalName.ToString());
             * } */

            appService.HostnameCNameRecords = cNames;
        }
        catch
        {
            dnsCheckErrors.hostnameCNameRecordLookupFailed = true;
            dnsCheckErrors.currentDNSFailures++;
        }
    }
Ejemplo n.º 7
0
        public void ImportToMapTest()
        {
            var qFtp = new DnsQuestion("ftp.import_www.bit", RecordType.Any, RecordClass.Any);
            var qWww = new DnsQuestion("www.import_www.bit", RecordType.Any, RecordClass.Any);

            var answerFtp = resolver.GetAnswer(qFtp);
            var answerWww = resolver.GetAnswer(qWww);

            ARecord     aFtp = answerFtp.AnswerRecords.FirstOrDefault() as ARecord;
            CNameRecord cWww = answerWww.AnswerRecords.FirstOrDefault() as CNameRecord;
            ARecord     aWww = answerWww.AdditionalRecords.FirstOrDefault() as ARecord;

            Assert.AreEqual("10.0.1.2", aFtp.Address.ToString());

            Assert.AreEqual("www.import_www.bit", cWww.Name);
            Assert.AreEqual("import_www.bit", cWww.CanonicalName);
            Assert.AreEqual("10.2.3.4", aWww.Address.ToString());
        }
Ejemplo n.º 8
0
        public void SerializeCNameRecord()
        {
            var serializer = GetRrSerializer();
            var cname      = new CNameRecord()
            {
                Name       = "www.",
                TimeToLive = 343,
                CName      = "aaa.",
            };

            byte[] expected = { 0x03, 0x77, 0x77, 0x77, 0x00,
                                0x00, 0x05,
                                0x00, 0x01,
                                0x00, 0x00, 0x01, 0x57,
                                0x00, 0x05,
                                0x03, 0x61, 0x61, 0x61, 0x00 };

            var serialized = cname.ToByteArray();

            Assert.AreEqual(expected, serialized);
        }
        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);
        }
Ejemplo n.º 10
0
        public static (List <DnsRecordBase> list, ReturnCode statusCode) ResolveOverHttpsByDnsJson(string clientIpAddress,
                                                                                                   string domainName, string dohUrl,
                                                                                                   bool proxyEnable = false, IWebProxy wProxy = null, RecordType type = RecordType.A)
        {
            string dnsStr;
            List <DnsRecordBase> recordList = new List <DnsRecordBase>();

            try
            {
                dnsStr = MyCurl.GetString(dohUrl + @"?ct=application/dns-json&" +
                                          $"name={domainName}&type={type.ToString().ToUpper()}&edns_client_subnet={clientIpAddress}",
                                          DnsSettings.Http2Enable, proxyEnable, wProxy, DnsSettings.AllowAutoRedirect);
            }
            catch (WebException e)
            {
                HttpWebResponse response = (HttpWebResponse)e.Response;
                try
                {
                    BackgroundLog($@"| - Catch WebException : {Convert.ToInt32(response.StatusCode)} {response.StatusCode} | {e.Status} | {domainName} | {response.ResponseUri}");
                    if (DnsSettings.HTTPStatusNotify)
                    {
                        MainWindow.NotifyIcon.ShowBalloonTip(360, "AuroraDNS - 错误",
                                                             $"异常 :{Convert.ToInt32(response.StatusCode)} {response.StatusCode} {Environment.NewLine} {domainName}", ToolTipIcon.Warning);
                    }
                    if (response.StatusCode == HttpStatusCode.BadRequest)
                    {
                        DnsSettings.DnsMsgEnable = true;
                    }
                }
                catch (Exception exception)
                {
                    BackgroundLog($@"| - Catch WebException : {exception.Message} | {e.Status} | {domainName} | {dohUrl}" + @"?ct=application/dns-json&" +
                                  $"name={domainName}&type={type.ToString().ToUpper()}&edns_client_subnet={clientIpAddress}");
                    if (DnsSettings.HTTPStatusNotify)
                    {
                        MainWindow.NotifyIcon.ShowBalloonTip(360, "AuroraDNS - 错误",
                                                             $"异常 : {exception.Message} {Environment.NewLine} {domainName}", ToolTipIcon.Warning);
                    }
                }

                if (dohUrl != DnsSettings.HttpsDnsUrl)
                {
                    return(new List <DnsRecordBase>(), ReturnCode.ServerFailure);
                }
                BackgroundLog($@"| -- SecondDoH : {DnsSettings.SecondHttpsDnsUrl}");
                return(ResolveOverHttpsByDnsJson(clientIpAddress, domainName, DnsSettings.SecondHttpsDnsUrl,
                                                 proxyEnable, wProxy, type));
            }

            JsonValue dnsJsonValue = Json.Parse(dnsStr);

            int statusCode = dnsJsonValue.AsObjectGetInt("Status");

            if (statusCode != 0)
            {
                return(new List <DnsRecordBase>(), (ReturnCode)statusCode);
            }

            if (dnsStr.Contains("\"Answer\""))
            {
                var dnsAnswerJsonList = dnsJsonValue.AsObjectGetArray("Answer");

                foreach (var itemJsonValue in dnsAnswerJsonList)
                {
                    string answerAddr       = itemJsonValue.AsObjectGetString("data");
                    string answerDomainName = itemJsonValue.AsObjectGetString("name");
                    int    answerType       = itemJsonValue.AsObjectGetInt("type");
                    int    ttl = itemJsonValue.AsObjectGetInt("TTL");

                    switch (type)
                    {
                    case RecordType.A when Convert.ToInt32(RecordType.A) == answerType && !DnsSettings.Ipv4Disable:
                    {
                        ARecord aRecord = new ARecord(
                            DomainName.Parse(answerDomainName), ttl, IPAddress.Parse(answerAddr));

                        recordList.Add(aRecord);
                        break;
                    }

                    case RecordType.A:
                    {
                        if (Convert.ToInt32(RecordType.CName) == answerType)
                        {
                            CNameRecord cRecord = new CNameRecord(
                                DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));

                            recordList.Add(cRecord);

                            //recordList.AddRange(ResolveOverHttps(clientIpAddress,answerAddr));
                            //return recordList;
                        }

                        break;
                    }

                    case RecordType.Aaaa when Convert.ToInt32(RecordType.Aaaa) == answerType && !DnsSettings.Ipv6Disable:
                    {
                        AaaaRecord aaaaRecord = new AaaaRecord(
                            DomainName.Parse(answerDomainName), ttl, IPAddress.Parse(answerAddr));
                        recordList.Add(aaaaRecord);
                        break;
                    }

                    case RecordType.Aaaa:
                    {
                        if (Convert.ToInt32(RecordType.CName) == answerType)
                        {
                            CNameRecord cRecord = new CNameRecord(
                                DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                            recordList.Add(cRecord);
                        }

                        break;
                    }

                    case RecordType.CName when answerType == Convert.ToInt32(RecordType.CName):
                    {
                        CNameRecord cRecord = new CNameRecord(
                            DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                        recordList.Add(cRecord);
                        break;
                    }

                    case RecordType.Ns when answerType == Convert.ToInt32(RecordType.Ns):
                    {
                        NsRecord nsRecord = new NsRecord(
                            DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                        recordList.Add(nsRecord);
                        break;
                    }

                    case RecordType.Mx when answerType == Convert.ToInt32(RecordType.Mx):
                    {
                        MxRecord mxRecord = new MxRecord(
                            DomainName.Parse(answerDomainName), ttl,
                            ushort.Parse(answerAddr.Split(' ')[0]),
                            DomainName.Parse(answerAddr.Split(' ')[1]));
                        recordList.Add(mxRecord);
                        break;
                    }

                    case RecordType.Txt when answerType == Convert.ToInt32(RecordType.Txt):
                    {
                        TxtRecord txtRecord = new TxtRecord(DomainName.Parse(answerDomainName), ttl, answerAddr);
                        recordList.Add(txtRecord);
                        break;
                    }

                    case RecordType.Ptr when answerType == Convert.ToInt32(RecordType.Ptr):
                    {
                        PtrRecord ptrRecord = new PtrRecord(
                            DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                        recordList.Add(ptrRecord);
                        break;
                    }

                    default:
                        statusCode = Convert.ToInt32(ReturnCode.ServerFailure);
                        break;
                    }
                }
            }

            return(recordList, (ReturnCode)statusCode);
        }
Ejemplo n.º 11
0
    private static IDictionary <string, object> Run()
    {
        var resourceGroup = new ResourceGroup("emoos-dev", new ResourceGroupArgs {
            Location = "WestEurope"
        });
        Output <string> resourceGroupName = resourceGroup.Name;

        var planSkuArgs = new PlanSkuArgs {
            Tier = "Basic", Size = "B1"
        };
        var plan = new Plan("DevAppServicePlan",
                            new PlanArgs {
            ResourceGroupName = resourceGroupName, Kind = "Linux", Sku = planSkuArgs, Reserved = true
        });

        var appSettings = new InputMap <string> {
            { "WEBSITES_ENABLE_APP_SERVICE_STORAGE", "false" }
        };

        var image      = "sqeezy/emoos.solutions:latest";
        var siteConfig = new AppServiceSiteConfigArgs {
            AlwaysOn = false, LinuxFxVersion = $"DOCKER|{image}"
        };
        var appService = new AppService("DevAppService",
                                        new AppServiceArgs
        {
            ResourceGroupName = resourceGroupName,
            AppServicePlanId  = plan.Id,
            AppSettings       = appSettings,
            HttpsOnly         = false,
            SiteConfig        = siteConfig
        });

        var emoosDns = new Zone("emoos.solutions",
                                new ZoneArgs {
            ResourceGroupName = "emoos", Name = "emoos.solutions"
        },
                                new CustomResourceOptions {
            ImportId = DnsId, Protect = true
        });

        var txtRecord = new TxtRecord("@",
                                      new TxtRecordArgs
        {
            Name = "@",
            ResourceGroupName = emoosDns.ResourceGroupName,
            Ttl      = 60,
            ZoneName = emoosDns.Name,
            Records  = new InputList <TxtRecordRecordsArgs>
            {
                new TxtRecordRecordsArgs {
                    Value = appService.DefaultSiteHostname
                }
            }
        });

        var cname = new CNameRecord("dev",
                                    new CNameRecordArgs
        {
            Name = "dev",
            ResourceGroupName = emoosDns.ResourceGroupName,
            Ttl      = 60,
            ZoneName = emoosDns.Name,
            Record   = appService.DefaultSiteHostname
        });

        var hostNameBinding = new CustomHostnameBinding("dev.emoos.solutions",
                                                        new CustomHostnameBindingArgs
        {
            AppServiceName    = appService.Name,
            Hostname          = "dev.emoos.solutions",
            ResourceGroupName = resourceGroupName
                                // SslState = "SniEnabled",
                                // Thumbprint = "19A0220DE45552EE931E0959B10F6DDDAD5F946B"
        });

        return(new Dictionary <string, object?>
        {
            { "default route", appService.DefaultSiteHostname }, { "resource group", resourceGroup.Name }
            // {"domain binding", hostNameBinding.Hostname}
        });
    }
Ejemplo n.º 12
0
        private static (List <dynamic> list, ReturnCode statusCode) ResolveOverHttps(string clientIpAddress, string domainName,
                                                                                     bool proxyEnable = false, IWebProxy wProxy = null, RecordType type = RecordType.A)
        {
            string         dnsStr;
            List <dynamic> recordList = new List <dynamic>();

            using (MWebClient webClient = new MWebClient())
            {
                webClient.Headers["User-Agent"] = "AuroraDNSC/0.1";

//                webClient.AllowAutoRedirect = false;

                if (proxyEnable)
                {
                    webClient.Proxy = wProxy;
                }

                try
                {
                    dnsStr = webClient.DownloadString(
                        DnsSettings.HttpsDnsUrl +
                        @"?ct=application/dns-json&" +
                        $"name={domainName}&type={type.ToString().ToUpper()}&edns_client_subnet={clientIpAddress}");
                }
                catch (WebException e)
                {
                    HttpWebResponse response = (HttpWebResponse)e.Response;
                    try
                    {
                        BgwLog($@"| - Catch WebException : {Convert.ToInt32(response.StatusCode)} {response.StatusCode} | {domainName}");
                    }
                    catch (Exception exception)
                    {
                        BgwLog($@"| - Catch WebException : {exception.Message} | {domainName}");

                        //MainWindow.NotifyIcon.ShowBalloonTip(360, "AuroraDNS - 错误",
                        //    $"异常 : {exception.Message} {Environment.NewLine} {domainName}", ToolTipIcon.Warning);
                    }
                    return(new List <dynamic>(), ReturnCode.ServerFailure);
                }
            }

            JsonValue dnsJsonValue = Json.Parse(dnsStr);

            int statusCode = dnsJsonValue.AsObjectGetInt("Status");

            if (statusCode != 0)
            {
                return(new List <dynamic>(), (ReturnCode)statusCode);
            }

            if (dnsStr.Contains("\"Answer\""))
            {
                var dnsAnswerJsonList = dnsJsonValue.AsObjectGetArray("Answer");

                foreach (var itemJsonValue in dnsAnswerJsonList)
                {
                    string answerAddr       = itemJsonValue.AsObjectGetString("data");
                    string answerDomainName = itemJsonValue.AsObjectGetString("name");
                    int    answerType       = itemJsonValue.AsObjectGetInt("type");
                    int    ttl = itemJsonValue.AsObjectGetInt("TTL");

                    switch (type)
                    {
                    case RecordType.A:
                    {
                        if (Convert.ToInt32(RecordType.A) == answerType)
                        {
                            ARecord aRecord = new ARecord(
                                DomainName.Parse(answerDomainName), ttl, IPAddress.Parse(answerAddr));

                            recordList.Add(aRecord);
                        }
                        else if (Convert.ToInt32(RecordType.CName) == answerType)
                        {
                            CNameRecord cRecord = new CNameRecord(
                                DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));

                            recordList.Add(cRecord);

                            //recordList.AddRange(ResolveOverHttps(clientIpAddress,answerAddr));
                            //return recordList;
                        }

                        break;
                    }

                    case RecordType.Aaaa:
                    {
                        if (Convert.ToInt32(RecordType.Aaaa) == answerType)
                        {
                            AaaaRecord aaaaRecord = new AaaaRecord(
                                DomainName.Parse(answerDomainName), ttl, IPAddress.Parse(answerAddr));
                            recordList.Add(aaaaRecord);
                        }
                        else if (Convert.ToInt32(RecordType.CName) == answerType)
                        {
                            CNameRecord cRecord = new CNameRecord(
                                DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                            recordList.Add(cRecord);
                        }
                        break;
                    }

                    case RecordType.CName when answerType == Convert.ToInt32(RecordType.CName):
                    {
                        CNameRecord cRecord = new CNameRecord(
                            DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                        recordList.Add(cRecord);
                        break;
                    }

                    case RecordType.Ns when answerType == Convert.ToInt32(RecordType.Ns):
                    {
                        NsRecord nsRecord = new NsRecord(
                            DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                        recordList.Add(nsRecord);
                        break;
                    }

                    case RecordType.Mx when answerType == Convert.ToInt32(RecordType.Mx):
                    {
                        MxRecord mxRecord = new MxRecord(
                            DomainName.Parse(answerDomainName), ttl,
                            ushort.Parse(answerAddr.Split(' ')[0]),
                            DomainName.Parse(answerAddr.Split(' ')[1]));
                        recordList.Add(mxRecord);
                        break;
                    }

                    case RecordType.Txt when answerType == Convert.ToInt32(RecordType.Txt):
                    {
                        TxtRecord txtRecord = new TxtRecord(DomainName.Parse(answerDomainName), ttl, answerAddr);
                        recordList.Add(txtRecord);
                        break;
                    }

                    case RecordType.Ptr when answerType == Convert.ToInt32(RecordType.Ptr):
                    {
                        PtrRecord ptrRecord = new PtrRecord(
                            DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                        recordList.Add(ptrRecord);
                        break;
                    }

                    default:
                    {
                        statusCode = Convert.ToInt32(ReturnCode.ServerFailure);
                        break;
                    }
                    }
                }
            }

            return(recordList, (ReturnCode)statusCode);
        }
Ejemplo n.º 13
0
        public DnsResourceRecord GetRecord(ResourceRecordInfo info)
        {
            if (info == null)
            {
                throw new ArgumentNullException(nameof(info));
            }

            var oldIndex = _reader.Index;
            DnsResourceRecord result;

            switch (info.RecordType)
            {
            case ResourceRecordType.A:
                result = new ARecord(info, _reader.ReadIPAddress());
                break;

            case ResourceRecordType.NS:
                result = new NsRecord(info, _reader.ReadDnsName());
                break;

            case ResourceRecordType.CNAME:
                result = new CNameRecord(info, _reader.ReadDnsName());
                break;

            case ResourceRecordType.SOA:
                result = ResolveSoaRecord(info);
                break;

            case ResourceRecordType.MB:
                result = new MbRecord(info, _reader.ReadDnsName());
                break;

            case ResourceRecordType.MG:
                result = new MgRecord(info, _reader.ReadDnsName());
                break;

            case ResourceRecordType.MR:
                result = new MrRecord(info, _reader.ReadDnsName());
                break;

            case ResourceRecordType.NULL:
                result = new NullRecord(info, _reader.ReadBytes(info.RawDataLength).ToArray());
                break;

            case ResourceRecordType.WKS:
                result = ResolveWksRecord(info);
                break;

            case ResourceRecordType.PTR:
                result = new PtrRecord(info, _reader.ReadDnsName());
                break;

            case ResourceRecordType.HINFO:
                result = new HInfoRecord(info, _reader.ReadStringWithLengthPrefix(), _reader.ReadStringWithLengthPrefix());
                break;

            case ResourceRecordType.MINFO:
                result = new MInfoRecord(info, _reader.ReadDnsName(), _reader.ReadDnsName());
                break;

            case ResourceRecordType.MX:
                result = ResolveMXRecord(info);
                break;

            case ResourceRecordType.TXT:
                result = ResolveTXTRecord(info);
                break;

            case ResourceRecordType.RP:
                result = new RpRecord(info, _reader.ReadDnsName(), _reader.ReadDnsName());
                break;

            case ResourceRecordType.AFSDB:
                result = new AfsDbRecord(info, (AfsType)_reader.ReadUInt16NetworkOrder(), _reader.ReadDnsName());
                break;

            case ResourceRecordType.AAAA:
                result = new AaaaRecord(info, _reader.ReadIPv6Address());
                break;

            case ResourceRecordType.SRV:
                result = ResolveSrvRecord(info);
                break;

            case ResourceRecordType.OPT:
                result = ResolveOptRecord(info);
                break;

            case ResourceRecordType.URI:
                result = ResolveUriRecord(info);
                break;

            case ResourceRecordType.CAA:
                result = ResolveCaaRecord(info);
                break;

            case ResourceRecordType.SSHFP:
                result = ResolveSshfpRecord(info);
                break;

            default:
                result = new UnknownRecord(info, _reader.ReadBytes(info.RawDataLength).ToArray());
                break;
            }

            // sanity check
            _reader.SanitizeResult(oldIndex + info.RawDataLength, info.RawDataLength);

            return(result);
        }
Ejemplo n.º 14
0
        private static (List <dynamic> list, int statusCode) ResolveOverHttps(string clientIpAddress, string domainName,
                                                                              bool proxyEnable = false, IWebProxy wProxy = null, RecordType type = RecordType.A)
        {
            string         dnsStr;
            List <dynamic> recordList = new List <dynamic>();

            using (WebClient webClient = new WebClient())
            {
                webClient.Headers["User-Agent"] = "AuroraDNSC/0.1";

                if (proxyEnable)
                {
                    webClient.Proxy = wProxy;
                }

                dnsStr = webClient.DownloadString(
                    ADnsSetting.HttpsDnsUrl +
                    @"?ct=application/dns-json&" +
                    $"name={domainName}&type={type.ToString().ToUpper()}&edns_client_subnet={clientIpAddress}");
            }

            JsonValue dnsJsonValue = Json.Parse(dnsStr);

            int statusCode = dnsJsonValue.AsObjectGetInt("Status");

            if (statusCode != 0)
            {
                return(new List <dynamic>(), statusCode);
            }

            if (dnsStr.Contains("\"Answer\""))
            {
                var dnsAnswerJsonList = dnsJsonValue.AsObjectGetArray("Answer");

                foreach (var itemJsonValue in dnsAnswerJsonList)
                {
                    string answerAddr       = itemJsonValue.AsObjectGetString("data");
                    string answerDomainName = itemJsonValue.AsObjectGetString("name");
                    int    answerType       = itemJsonValue.AsObjectGetInt("type");
                    int    ttl = itemJsonValue.AsObjectGetInt("TTL");

                    if (type == RecordType.A)
                    {
                        if (Convert.ToInt32(RecordType.A) == answerType)
                        {
                            ARecord aRecord = new ARecord(
                                DomainName.Parse(answerDomainName), ttl, IPAddress.Parse(answerAddr));

                            recordList.Add(aRecord);
                        }
                        else if (Convert.ToInt32(RecordType.CName) == answerType)
                        {
                            CNameRecord cRecord = new CNameRecord(
                                DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));

                            recordList.Add(cRecord);

                            //recordList.AddRange(ResolveOverHttps(clientIpAddress,answerAddr));
                            //return recordList;
                        }
                    }
                    else if (type == RecordType.Aaaa && ADnsSetting.IPv6Enable)
                    {
                        if (Convert.ToInt32(RecordType.Aaaa) == answerType)
                        {
                            AaaaRecord aaaaRecord = new AaaaRecord(
                                DomainName.Parse(answerDomainName), ttl, IPAddress.Parse(answerAddr));
                            recordList.Add(aaaaRecord);
                        }
                        else if (Convert.ToInt32(RecordType.CName) == answerType)
                        {
                            CNameRecord cRecord = new CNameRecord(
                                DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                            recordList.Add(cRecord);
                        }
                    }
                    else if (type == RecordType.CName && answerType == Convert.ToInt32(RecordType.CName))
                    {
                        CNameRecord cRecord = new CNameRecord(
                            DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                        recordList.Add(cRecord);
                    }
                    else if (type == RecordType.Ns && answerType == Convert.ToInt32(RecordType.Ns))
                    {
                        NsRecord nsRecord = new NsRecord(
                            DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                        recordList.Add(nsRecord);
                    }
                    else if (type == RecordType.Mx && answerType == Convert.ToInt32(RecordType.Mx))
                    {
                        MxRecord mxRecord = new MxRecord(
                            DomainName.Parse(answerDomainName), ttl,
                            ushort.Parse(answerAddr.Split(' ')[0]),
                            DomainName.Parse(answerAddr.Split(' ')[1]));
                        recordList.Add(mxRecord);
                    }
                    else if (type == RecordType.Txt && answerType == Convert.ToInt32(RecordType.Txt))
                    {
                        TxtRecord txtRecord = new TxtRecord(DomainName.Parse(answerDomainName), ttl, answerAddr);
                        recordList.Add(txtRecord);
                    }
                    else if (type == RecordType.Ptr && answerType == Convert.ToInt32(RecordType.Ptr))
                    {
                        PtrRecord ptrRecord = new PtrRecord(
                            DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                        recordList.Add(ptrRecord);
                    }
                }
            }

            return(recordList, statusCode);
        }
Ejemplo n.º 15
0
 internal virtual void AssertEquality(CNameRecord expected, CNameRecord actual)
 {
     Assert.AreEqual(expected.CName, actual.CName, "Should be equal");
 }
Ejemplo n.º 16
0
    /// <summary>
    /// Do DNS queries to get any CNAME records associated with awverify.{custom hostname}.
    /// AWVerify records are the old method that accompanied A records for hostname validation. They can currently be used to preemptively add a hostname to an App Service without adjusting the existing record.
    /// For example, if the user has "www.contoso.com" configured on another server or service but wants to add it to the App Service without disrupting the hostname, they will configure a CNAME record from "awverify.www.contoso.com" to point towards the URL of the App Service to host "www.contoso.com" in the future.
    /// Puts the string output of all of the awverify records into the AppService argument so the list can be used later.
    /// </summary>
    /// <param name="appService"></param>
    public static void GetHostnameAwverifyRecords(AppService appService, DNSCheckErrors dnsCheckErrors)
    {
        //IDnsResolver resolver = new DnsStubResolver();

        string awverifyRecordURL   = "awverify." + appService.CustomHostname;
        string awverifyURLDNSStyle = awverifyRecordURL + ".";

        try
        {
            // List<CNameRecord> awverifyCNameRecords = DnsResolverExtensions.Resolve<CNameRecord>(resolver, awverifyRecordURL, RecordType.CName, RecordClass.Any);

            List <string> awverifyCNameRecords = new List <string>();

            DnsMessage dnsMessage1 = DnsClient.Default.Resolve(DomainName.Parse(awverifyRecordURL), RecordType.CName);
            if ((dnsMessage1 == null) || ((dnsMessage1.ReturnCode != ReturnCode.NoError) && (dnsMessage1.ReturnCode != ReturnCode.NxDomain)))
            {
                throw new Exception("DNS request failed");
            }
            else
            {
                foreach (DnsRecordBase dnsRecord in dnsMessage1.AnswerRecords)
                {
                    if (dnsRecord.RecordType == RecordType.CName && dnsRecord.Name.ToString() == awverifyURLDNSStyle)
                    {
                        CNameRecord awverifyCNameRecord = dnsRecord as CNameRecord;
                        if (awverifyCNameRecord != null)
                        {
                            awverifyCNameRecords.Add(awverifyCNameRecord.CanonicalName.ToString());
                        }
                    }
                }
            }

            List <string> awverifyTxtRecords = new List <string>();

            DnsMessage dnsMessage2 = DnsClient.Default.Resolve(DomainName.Parse(awverifyRecordURL), RecordType.Txt);
            if ((dnsMessage2 == null) || ((dnsMessage2.ReturnCode != ReturnCode.NoError) && (dnsMessage2.ReturnCode != ReturnCode.NxDomain)))
            {
                throw new Exception("DNS request failed");
            }
            else
            {
                foreach (DnsRecordBase dnsRecord in dnsMessage2.AnswerRecords)
                {
                    if (dnsRecord.RecordType == RecordType.Txt && dnsRecord.Name.ToString() == awverifyURLDNSStyle)
                    {
                        TxtRecord awverifyTxtRecord = dnsRecord as TxtRecord;
                        if (awverifyTxtRecord != null)
                        {
                            awverifyTxtRecords.Add(awverifyTxtRecord.TextData.ToString());
                        }
                    }
                }
            }

            /* List<string> awverifyRecords = new List<string>();
             * foreach (CNameRecord awverifyCName in awverifyCNameRecords)
             * {
             *  awverifyRecords.Add(awverifyCName.CanonicalName.ToString());
             * } */

            appService.HostnameAwverifyCNameRecords = awverifyCNameRecords;
            appService.HostnameAwverifyTxtRecords   = awverifyTxtRecords;
        }
        catch
        {
            dnsCheckErrors.hostnameAwverifyRecordLookupFailed = true;
            dnsCheckErrors.currentDNSFailures++;
        }
    }
Ejemplo n.º 17
0
        public DnsResourceRecord GetRecord(ResourceRecordInfo info)
        {
            if (info == null)
            {
                throw new ArgumentNullException(nameof(info));
            }

            var oldIndex = _reader.Index;
            DnsResourceRecord result;

            switch (info.RecordType)
            {
            case ResourceRecordType.A:
                result = new ARecord(info, _reader.ReadIPAddress());
                break;

            case ResourceRecordType.NS:
                result = new NsRecord(info, _reader.ReadDnsName());
                break;

            case ResourceRecordType.CNAME:
                result = new CNameRecord(info, _reader.ReadDnsName());
                break;

            case ResourceRecordType.SOA:
                result = ResolveSoaRecord(info);
                break;

            case ResourceRecordType.MB:
                result = new MbRecord(info, _reader.ReadDnsName());
                break;

            case ResourceRecordType.MG:
                result = new MgRecord(info, _reader.ReadDnsName());
                break;

            case ResourceRecordType.MR:
                result = new MrRecord(info, _reader.ReadDnsName());
                break;

            case ResourceRecordType.NULL:
                result = new NullRecord(info, _reader.ReadBytes(info.RawDataLength).ToArray());
                break;

            case ResourceRecordType.WKS:
                result = ResolveWksRecord(info);
                break;

            case ResourceRecordType.PTR:
                result = new PtrRecord(info, _reader.ReadDnsName());
                break;

            case ResourceRecordType.HINFO:
                result = new HInfoRecord(info, _reader.ReadString(), _reader.ReadString());
                break;

            case ResourceRecordType.MINFO:
                result = new MInfoRecord(info, _reader.ReadDnsName(), _reader.ReadDnsName());
                break;

            case ResourceRecordType.MX:
                result = ResolveMXRecord(info);
                break;

            case ResourceRecordType.TXT:
                result = ResolveTXTRecord(info);
                break;

            case ResourceRecordType.RP:
                result = new RpRecord(info, _reader.ReadDnsName(), _reader.ReadDnsName());
                break;

            case ResourceRecordType.AFSDB:
                result = new AfsDbRecord(info, (AfsType)_reader.ReadUInt16NetworkOrder(), _reader.ReadDnsName());
                break;

            case ResourceRecordType.AAAA:
                result = new AaaaRecord(info, _reader.ReadIPv6Address());
                break;

            case ResourceRecordType.SRV:
                result = ResolveSrvRecord(info);
                break;

            case ResourceRecordType.OPT:
                result = ResolveOptRecord(info);
                break;

            case ResourceRecordType.URI:
                result = ResolveUriRecord(info);
                break;

            case ResourceRecordType.CAA:
                result = ResolveCaaRecord(info);
                break;

            default:
                // update reader index because we don't read full data for the empty record
                _reader.Index += info.RawDataLength;
                result         = new EmptyRecord(info);
                break;
            }

            // sanity check
            if (_reader.Index != oldIndex + info.RawDataLength)
            {
                throw new InvalidOperationException("Record reader index out of sync.");
            }

            return(result);
        }
Ejemplo n.º 18
0
            public static List <Record> FromArray(byte[] array, int count, int offset, out int offsetOut)
            {
                List <Record> records = new List <Record>(count);

                for (int i = 0; i < count; i++)
                {
                    string        hostname = Hostname.FromArray(array, offset, out offset);
                    DnsRecordType recordType;
                    Record        record;
                    ushort        dataLength;

                    if (BitConverter.IsLittleEndian)
                    {
                        recordType = (DnsRecordType)(array[offset++] << 8 | array[offset++]);
                    }
                    else
                    {
                        recordType = (DnsRecordType)(array[offset++] | array[offset++] << 8);
                    }

                    switch (recordType)
                    {
                    case DnsRecordType.A:
                    case DnsRecordType.AAAA:
                        record = new IPRecord();
                        break;

                    case  DnsRecordType.CNAME:
                        record = new CNameRecord();
                        break;

                    default:
                        record = new Record();
                        break;
                    }

                    record.hostname   = hostname;
                    record.recordType = recordType;

                    if (BitConverter.IsLittleEndian)
                    {
                        record.recordClass = (DnsRecordClass)(array[offset++] << 8 | array[offset++]);
                        record.ttl         = (uint)(array[offset++] << 24 | array[offset++] << 16 | array[offset++] << 8 | array[offset++]);
                        dataLength         = (ushort)(array[offset++] << 8 | array[offset++]);
                    }
                    else
                    {
                        record.recordClass = (DnsRecordClass)(array[offset++] | array[offset++] << 8);
                        record.ttl         = (uint)(array[offset++] | array[offset++] << 8 | array[offset++] << 16 | array[offset++] << 24);
                        dataLength         = (ushort)(array[offset++] | array[offset++] << 8);
                    }

                    record.data = new byte[dataLength];
                    Array.Copy(array, offset, record.data, 0, record.data.Length);

                    records.Add(record);

                    offset += dataLength;
                }

                offsetOut = offset;
                return(records);
            }