Ejemplo n.º 1
0
        public async Task <bool> ZoneIsUpToDate(string Hostname, RecordType recordType, string zoneAddress)
        {
            RecordSet recordSet = await RecordSet(Hostname, recordType);

            if (recordType == RecordType.A)
            {
                ARecord aRecord = new ARecord(zoneAddress);
                foreach (ARecord rec in recordSet.ARecords)
                {
                    string CurrentAddress = rec.Ipv4Address;
                    if (CurrentAddress.Equals(zoneAddress))
                    {
                        return(true);
                    }
                }
                return(false);
            }
            if (recordType == RecordType.AAAA)
            {
                AaaaRecord aaaaRecord = new AaaaRecord(zoneAddress);
                foreach (AaaaRecord rec in recordSet.AaaaRecords)
                {
                    string CurrentAddress = rec.Ipv6Address;
                    if (CurrentAddress.Equals(zoneAddress))
                    {
                        return(true);
                    }
                }
                return(false);
            }
            return(false);
        }
Ejemplo n.º 2
0
        public void ResolveMapOnlyArrayTest()
        {
            var q = new DnsQuestion("maponlyarray.bit", RecordType.Any, RecordClass.Any);

            string expectedA1 = "1.2.3.4";
            string expectedA2 = "4.3.2.1";

            string expectedAAAA = "2400:cb00:2049:1::adf5:3b6b";

            var answer = resolver.GetAnswer(q);

            var Aanswers    = answer.AnswerRecords.Where(m => m.RecordType == RecordType.A);
            var AAAAanswers = answer.AnswerRecords.Where(m => m.RecordType == RecordType.Aaaa);

            Assert.IsInstanceOfType(Aanswers.First(), typeof(ARecord));

            ARecord a1 = Aanswers.First() as ARecord;
            ARecord a2 = Aanswers.Last() as ARecord;

            AaaaRecord aaaa = AAAAanswers.First() as AaaaRecord;

            Assert.AreEqual(expectedA1, a1.Address.ToString());
            Assert.AreEqual(expectedA2, a2.Address.ToString());

            Assert.AreEqual(expectedAAAA, aaaa.Address.ToString());
        }
Ejemplo n.º 3
0
        public void TestAaaaRecord()
        {
            var record = new AaaaRecord(
                "f00.Test", "2001:0Db8:85A3:0000:0000:8a2e:0370:7334");

            Assert.AreEqual("f00.Test", record.Name);
            Assert.AreEqual("2001:0db8:85a3:0000:0000:8a2e:0370:7334", record.IPv6);
        }
Ejemplo n.º 4
0
        private static IRecord ReadRecord(ByteReader byteReader)
        {
            var name   = DnsUtils.ReadName(byteReader);
            var rtype  = byteReader.GetUshort();
            var rclass = byteReader.GetUshort();
            var ttl    = byteReader.GetUint();

            if ((RecordType)rtype == RecordType.NS)
            {
                var record = new NSRecord()
                {
                    Name   = name,
                    RClass = rclass,
                    Ttl    = ttl,
                };
                var rdlength = byteReader.GetUshort();
                record.Host = ReadName(byteReader);
                return(record);
            }
            else if ((RecordType)rtype == RecordType.A)
            {
                var rdlength = byteReader.GetUshort();
                var ipv4     = ReadIpv4(byteReader);
                var record   = new ARecord(name, ipv4)
                {
                    RClass = rclass,
                    Ttl    = ttl,
                };
                return(record);
            }
            else if ((RecordType)rtype == RecordType.AAAA)
            {
                var rdlength = byteReader.GetUshort();
                var ipv6     = ReadIpv6(byteReader);
                var record   = new AaaaRecord(name, ipv6)
                {
                    RClass = rclass,
                    Ttl    = ttl,
                };
                return(record);
            }
            else
            {
                var record = new Record()
                {
                    Name   = name,
                    RType  = rtype,
                    RClass = (ushort)rclass,
                    Ttl    = ttl,
                };
                var rdlength = byteReader.GetUshort();
                record.RData = byteReader.GetBytes(rdlength);
                return(record);
            }
        }
Ejemplo n.º 5
0
        public async Task <IPAddress> QueryIp(string domain, CancellationToken token)
        {
            IDnsQueryResponse response = await _lookup.QueryAsync(domain, QueryType.A, QueryClass.IN, token);

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

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

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

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

            return(aaaaRecord?.Address);
        }
Ejemplo n.º 6
0
        private static DnsMessage ReplaceARecords(DnsMessage response, DnsMessage dnsMessage)
        {
            var newRecords = new List <DnsRecordBase>();

            foreach (var answerRecord in response.AnswerRecords)
            {
                switch (answerRecord)
                {
                case ARecord _:
                    var newARecord = new ARecord(answerRecord.Name, answerRecord.TimeToLive, IPAddress.Loopback);
                    newRecords.Add(newARecord);
                    break;

                case AaaaRecord _:
                    var newAaaaRecord = new AaaaRecord(answerRecord.Name, answerRecord.TimeToLive, IPAddress.IPv6Loopback);
                    newRecords.Add(newAaaaRecord);
                    break;

                default:
                    newRecords.Add(answerRecord);
                    break;
                }
            }

            return(new DnsMessage
            {
                Questions = dnsMessage.Questions,
                IsQuery = false,
                AdditionalRecords = response.AdditionalRecords,
                AnswerRecords = newRecords,
                AuthorityRecords = response.AuthorityRecords,
                EDnsOptions = response.EDnsOptions,
                IsAuthenticData = response.IsAuthenticData,
                IsAuthoritiveAnswer = response.IsAuthoritiveAnswer,
                IsCheckingDisabled = response.IsCheckingDisabled,
                IsDnsSecOk = response.IsDnsSecOk,
                IsEDnsEnabled = response.IsAuthenticData,
                IsRecursionAllowed = response.IsRecursionAllowed,
                IsRecursionDesired = response.IsRecursionDesired,
                IsTruncated = response.IsTruncated,
                OperationCode = response.OperationCode,
                ReturnCode = response.ReturnCode,
                TSigOptions = response.TSigOptions,
                TransactionID = response.TransactionID
            });
        }
Ejemplo n.º 7
0
        private RecordSet GetUpdateRecordSet(IMode mode)
        {
            RecordSet updateRecordSet = new RecordSet();

            if (mode.Type == RecordType.A)
            {
                ARecord aRecord = new ARecord(mode.Address);
                updateRecordSet.ARecords = new List <ARecord>();
                updateRecordSet.ARecords.Add(aRecord);
            }
            if (mode.Type == RecordType.AAAA)
            {
                AaaaRecord aaaaRecord = new AaaaRecord(mode.Address);
                updateRecordSet.AaaaRecords = new List <AaaaRecord>();
                updateRecordSet.AaaaRecords.Add(aaaaRecord);
            }
            updateRecordSet.TTL = 3600;
            return(updateRecordSet);
        }
Ejemplo n.º 8
0
            private void _read()
            {
                _name        = new DomainName(m_io, this, m_root);
                _type        = ((DnsPacket.RecordType)m_io.ReadU2be());
                _answerClass = ((DnsPacket.ClassType)m_io.ReadU2be());
                _ttl         = m_io.ReadS4be();
                _rdlength    = m_io.ReadU2be();
                switch (Type)
                {
                case DnsPacket.RecordType.Aaaa: {
                    _rdata = new AaaaRecord(m_io, this, m_root);
                    break;
                }

                case DnsPacket.RecordType.A: {
                    _rdata = new ARecord(m_io, this, m_root);
                    break;
                }

                case DnsPacket.RecordType.Mx: {
                    _rdata = new MxRecord(m_io, this, m_root);
                    break;
                }

                case DnsPacket.RecordType.Cname: {
                    _rdata = new CnameRecord(m_io, this, m_root);
                    break;
                }

                case DnsPacket.RecordType.Ns: {
                    _rdata = new NsRecord(m_io, this, m_root);
                    break;
                }

                case DnsPacket.RecordType.Ptr: {
                    _rdata = new PtrRecord(m_io, this, m_root);
                    break;
                }
                }
            }
Ejemplo n.º 9
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.º 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 (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);
        }
        protected void DeleteRecordEntry(object param)
        {
            List <object> objList = param as List <object>;
            RecordSet     rs      = objList?[0] as RecordSet;

            switch (GetRecordType(rs?.Type))
            {
            case RecordType.A:
            {
                ARecord record = objList?[1] as ARecord;
                if (record != null)
                {
                    rs.Properties.ARecords.Remove(record);
                }
            }
            break;

            case RecordType.AAAA:
            {
                AaaaRecord record = objList?[1] as AaaaRecord;
                if (record != null)
                {
                    rs.Properties.AaaaRecords.Remove(record);
                }
            }
            break;

            case RecordType.MX:
            {
                MxRecord record = objList?[1] as MxRecord;
                if (record != null)
                {
                    rs.Properties.MxRecords.Remove(record);
                }
            }
            break;

            case RecordType.SRV:
            {
                SrvRecord record = objList?[1] as SrvRecord;
                if (record != null)
                {
                    rs.Properties.SrvRecords.Remove(record);
                }
            }
            break;

            case RecordType.TXT:
            {
                TxtRecord record = objList?[1] as TxtRecord;
                if (record != null)
                {
                    rs.Properties.TxtRecords.Remove(record);
                }
            }
            break;
            }

            var r = new List <RecordSet>(Records);

            Records.Clear();
            Records = new System.Collections.ObjectModel.ObservableCollection <RecordSet>(r);
        }
Ejemplo n.º 13
0
        internal static RecordSetData DeserializeRecordSetData(JsonElement element)
        {
            Optional <string>  etag       = default;
            ResourceIdentifier id         = default;
            string             name       = default;
            ResourceType       type       = default;
            SystemData         systemData = default;
            Optional <IDictionary <string, string> > metadata = default;
            Optional <long>   ttl  = default;
            Optional <string> fqdn = default;
            Optional <string> provisioningState           = default;
            Optional <WritableSubResource> targetResource = default;
            Optional <IList <ARecord> >    aRecords       = default;
            Optional <IList <AaaaRecord> > aaaaRecords    = default;
            Optional <IList <MxRecord> >   mxRecords      = default;
            Optional <IList <NsRecord> >   nsRecords      = default;
            Optional <IList <PtrRecord> >  ptrRecords     = default;
            Optional <IList <SrvRecord> >  srvRecords     = default;
            Optional <IList <TxtRecord> >  txtRecords     = default;
            Optional <CnameRecord>         cnameRecord    = default;
            Optional <SoaRecord>           soaRecord      = default;
            Optional <IList <CaaRecord> >  caaRecords     = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("etag"))
                {
                    etag = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = new ResourceType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("systemData"))
                {
                    systemData = JsonSerializer.Deserialize <SystemData>(property.Value.ToString());
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("metadata"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            Dictionary <string, string> dictionary = new Dictionary <string, string>();
                            foreach (var property1 in property0.Value.EnumerateObject())
                            {
                                dictionary.Add(property1.Name, property1.Value.GetString());
                            }
                            metadata = dictionary;
                            continue;
                        }
                        if (property0.NameEquals("TTL"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            ttl = property0.Value.GetInt64();
                            continue;
                        }
                        if (property0.NameEquals("fqdn"))
                        {
                            fqdn = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("provisioningState"))
                        {
                            provisioningState = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("targetResource"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            targetResource = JsonSerializer.Deserialize <WritableSubResource>(property0.Value.ToString());
                            continue;
                        }
                        if (property0.NameEquals("ARecords"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <ARecord> array = new List <ARecord>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(ARecord.DeserializeARecord(item));
                            }
                            aRecords = array;
                            continue;
                        }
                        if (property0.NameEquals("AAAARecords"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <AaaaRecord> array = new List <AaaaRecord>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(AaaaRecord.DeserializeAaaaRecord(item));
                            }
                            aaaaRecords = array;
                            continue;
                        }
                        if (property0.NameEquals("MXRecords"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <MxRecord> array = new List <MxRecord>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(MxRecord.DeserializeMxRecord(item));
                            }
                            mxRecords = array;
                            continue;
                        }
                        if (property0.NameEquals("NSRecords"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <NsRecord> array = new List <NsRecord>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(NsRecord.DeserializeNsRecord(item));
                            }
                            nsRecords = array;
                            continue;
                        }
                        if (property0.NameEquals("PTRRecords"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <PtrRecord> array = new List <PtrRecord>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(PtrRecord.DeserializePtrRecord(item));
                            }
                            ptrRecords = array;
                            continue;
                        }
                        if (property0.NameEquals("SRVRecords"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <SrvRecord> array = new List <SrvRecord>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(SrvRecord.DeserializeSrvRecord(item));
                            }
                            srvRecords = array;
                            continue;
                        }
                        if (property0.NameEquals("TXTRecords"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <TxtRecord> array = new List <TxtRecord>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(TxtRecord.DeserializeTxtRecord(item));
                            }
                            txtRecords = array;
                            continue;
                        }
                        if (property0.NameEquals("CNAMERecord"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            cnameRecord = CnameRecord.DeserializeCnameRecord(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("SOARecord"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            soaRecord = SoaRecord.DeserializeSoaRecord(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("caaRecords"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <CaaRecord> array = new List <CaaRecord>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(CaaRecord.DeserializeCaaRecord(item));
                            }
                            caaRecords = array;
                            continue;
                        }
                    }
                    continue;
                }
            }
            return(new RecordSetData(id, name, type, systemData, etag.Value, Optional.ToDictionary(metadata), Optional.ToNullable(ttl), fqdn.Value, provisioningState.Value, targetResource, Optional.ToList(aRecords), Optional.ToList(aaaaRecords), Optional.ToList(mxRecords), Optional.ToList(nsRecords), Optional.ToList(ptrRecords), Optional.ToList(srvRecords), Optional.ToList(txtRecords), cnameRecord.Value, soaRecord.Value, Optional.ToList(caaRecords)));
        }
Ejemplo n.º 14
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);
        }
        public override void ExecuteCmdlet()
        {
            DnsRecordBase result = null;
            switch (this.ParameterSetName)
            {
                case ParameterSetA:
                    {
                        result = new ARecord { Ipv4Address = this.Ipv4Address };
                        break;
                    }

                case ParameterSetAaaa:
                    {
                        result = new AaaaRecord { Ipv6Address = this.Ipv6Address };
                        break;
                    }

                case ParameterSetMx:
                    {
                        result = new MxRecord { Preference = this.Preference, Exchange = this.Exchange };
                        break;
                    }

                case ParameterSetNs:
                    {
                        result = new NsRecord { Nsdname = this.Nsdname };
                        break;
                    }
                case ParameterSetSrv:
                    {
                        result = new SrvRecord { Priority = this.Priority, Port = this.Port, Target = this.Target, Weight = this.Weight };
                        break;
                    }
                case ParameterSetTxt:
                    {
                        result = new TxtRecord { Value = this.Value };
                        break;
                    }
                case ParameterSetCName:
                    {
                        result = new CnameRecord { Cname = this.Cname };
                        break;
                    }
                case ParameterSetPtr:
                    {
                        result = new PtrRecord {Ptrdname = this.Ptrdname};
                        break;
                    }
                default:
                    {
                        throw new PSArgumentException(string.Format(ProjectResources.Error_UnknownParameterSetName, this.ParameterSetName));
                    }
            }

            WriteObject(result);
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            // PrintAlgorithms();
            // EqualityCheck();
            // TestKeyPair();

            // https://www.cloudflare.com/dns/dnssec/how-dnssec-works/
            // RRSIG - Contains a cryptographic signature
            // DNSKEY - Contains a public signing key
            // DS - Contains the hash of a DNSKEY record
            // NSEC and NSEC3 - For explicit denial-of-existence of a DNS record
            // CDNSKEY and CDS - For a child zone requesting updates to DS record(s) in the parent zone.


            // The first step towards securing a zone with DNSSEC
            // is to group all the records (on the same label?) with the same type into a resource record set(RRset).
            // It’s actually this full RRset that gets digitally signed, opposed to individual DNS records.
            // Of course, this also means that you must request and validate all of the AAAA records
            // from a zone with the same label instead of validating only one of them.


            // zone-signing key (ZSK)pair:
            // the private portion of the key digitally signs each RRset in the zone,
            // while the public portion verifies the signature.
            // a zone operator creates digital signatures for each RRset using the private ZSK
            // and stores them in their name server as RRSIG records.

            // The zone operator also needs to make their public ZSK available by adding it to their name server in a DNSKEY record.

            // the name server also returns the corresponding RRSIG.
            // The resolver can then pull the DNSKEY record containing the public ZSK from the name server.
            // Together, the RRset, RRSIG, and public ZSK can validate the response.

            // If we trust the zone - signing key in the DNSKEY record, we can trust all the records in the zone.
            // But, what if the zone - signing key was compromised? We need a way to validate the public ZSK.

            // Key-Signing Keys (KSK):
            // The KSK validates the DNSKEY record in exactly the same way as our ZSK secured the rest of our RRsets.
            // It signs the public ZSK (which is stored in a DNSKEY record), creating an RRSIG for the DNSKEY.

            // Just like the public ZSK, the name server publishes the public KSK in another DNSKEY record,
            // which gives us the DNSKEY RRset shown above.
            // Both the public KSK and public ZSK are signed by the private KSK.
            // Resolvers can then use the public KSK to validate the public ZSK.

            // Complicating things further, the key-signing key is signed by itself, which doesn’t provide any additional trust.
            // We need a way to connect the trust in our zone with its parent zone.


            // Delegation Signer Records
            // DNSSEC introduces a delegation signer(DS) record to allow the transfer of trust
            // from a parent zone to a child zone. A zone operator hashes the DNSKEY record
            // containing the public KSK and gives it to the parent zone to publish as a DS record.

            // This DS record is how resolvers know that the child zone is DNSSEC - enabled.
            // To check the validity of the child zone’s public KSK,
            // the resolver hashes it and compares it to the DS record from the parent.
            // If they match, the resolver can assume that the public KSK hasn’t been tampered with,
            // which means it can trust all of the records in the child zone.
            // This is how a chain of trust is established in DNSSEC.


            // System.Security.Cryptography.X509Certificates.X509Certificate2 cert2 = new System.Security.Cryptography.X509Certificates.X509Certificate2(byte[] rawData);
            // System.Security.Cryptography.X509Certificates.X509Certificate2 cert2 = DotNetUtilities.CreateX509Cert2("mycert");
            // SecurityKey secKey = new X509SecurityKey(cert2);

            // https://tools.ietf.org/html/rfc4034
            // https://www.dynu.com/Resources/DNS-Records/DNSKEY-Record


            AaaaRecord aaa    = new AaaaRecord(ARSoft.Tools.Net.DomainName.Parse("example.com"), 0, System.Net.IPAddress.Parse("127.0.0.1"));
            string     straaa = aaa.ToString();

            System.Console.WriteLine(straaa);


            // DnsRecordBase drb = null;
            // DnsMessage msg = DnsMessage.Parse(new byte[] { });
            // DnsKeyFlags flags = DnsKeyFlags.SecureEntryPoint;

            KeyPairRecord ZSK_key = CreateSigningKey(DnsSecAlgorithm.EccGost, DnsKeyFlags.Zone, 512);
            KeyPairRecord keyPair = CreateSigningKey(DnsSecAlgorithm.EccGost, DnsKeyFlags.SecureEntryPoint, 512);


            byte[] zsPub  = Org.BouncyCastle.X509.SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(ZSK_key.KeyPair.Public).GetDerEncoded();
            byte[] zsPriv = Org.BouncyCastle.Pkcs.PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.KeyPair.Private).GetDerEncoded();

            bool bPub  = System.Linq.Enumerable.SequenceEqual(ZSK_key.PublicKey, zsPub);
            bool bPriv = System.Linq.Enumerable.SequenceEqual(ZSK_key.PrivateKey, zsPriv);

            System.Console.WriteLine("Pub; {0}\t Priv: {1}", bPub, bPriv);


            // Private key only necessary when signing, now when publishing...
            DnsKeyRecord dnsKey = new DnsKeyRecord(
                ARSoft.Tools.Net.DomainName.Parse("example.com") // Name: It defines the hostname of a record and whether the hostname will be appended to the label.
                // Fully qualified hostnames terminated by a period will not append the origin.
                , RecordClass.Any
                , 60 // ttl The time-to-live in seconds. It specifies how long a resolver is supposed to cache or remember the DNS query
                     // before the query expires and a new one needs to be done.
                , keyPair.Flags
                , 3                 // Fixed value of 3 (for backwards compatibility)
                , keyPair.Algorithm // The public key's cryptographic algorithm.
                , keyPair.PublicKey //  new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 } // Public key data.
                , keyPair.PrivateKey
                );



            string strDNSKey = dnsKey.ToString();

            // dnsKey.CalculateKeyTag()
            System.Console.WriteLine(strDNSKey);
            // example.com. 60 * DNSKEY 256 3 8 AQIDBAUGBwgJ



            System.Collections.Generic.List <DnsRecordBase> records = new System.Collections.Generic.List <DnsRecordBase>();
            records.Add(aaa);



            RrSigRecord rrsig1   = RrSigRecord.SignRecord(records, dnsKey, System.DateTime.UtcNow, System.DateTime.UtcNow.AddDays(30));
            string      strRRsig = rrsig1.ToString();

            // rrsig1.Signature
            System.Console.WriteLine(strRRsig);

            // example.com. 0 IN RRSIG AAAA 12 2 0 20200122193048 20191223193048 46296 example.com. 9aCosjMmgc1iL4jNavgPAA5NXRp5jukyKxb9vCA8PNoz1d4LjaTjfURxnKhX97KkkTdSW0tUoeYgBK7t/qjOFg==

            RrSigRecord rrsig = new RrSigRecord(
                ARSoft.Tools.Net.DomainName.Parse("example.com")   // Name of the digitally signed RRs
                , RecordClass.Any
                , 60                                               // ttl The time-to-live in seconds. It specifies how long a resolver is supposed to cache or remember the DNS query
                                                                   // before the query expires and a new one needs to be done.
                , RecordType.A                                     // Type Covered: DNS record type that this signature covers.
                , DnsSecAlgorithm.EccGost                          // Cryptographic algorithm used to create the signature.
                , 4                                                // Labels: Number of labels in the original RRSIG-record name (used to validate wildcards).
                , 0                                                // Original TTL: TTL value of the covered record set.
                , System.DateTime.Now.AddMinutes(1)                // Signature Expiration: When the signature expires.
                , System.DateTime.Now                              // Signature Inception: When the signature was created.
                , 0                                                // Key Tag: A short numeric value which can help quickly identify the DNSKEY-record which can be used to validate this signature.
                                                                   // identifiziert den unterzeichnenden DNSKEY, um zwischen mehreren Signaturen zu unterscheiden (engl. key tag)
                , ARSoft.Tools.Net.DomainName.Parse("example.com") // Signer's Name: Name of the DNSKEY-record which can be used to validate this signature.
                , new byte[] { 1, 2, 3 }                           // Signature: Cryptographic signature.  (Base64)
                );



            DsRecord signedDsRec    = new DsRecord(dnsKey, 0, keyPair.Digest);
            string   strSignedDsRec = signedDsRec.ToString();

            System.Console.WriteLine(strSignedDsRec);
            // signedDsRec.Digest
            // example.com. 0 * DS 24280 12 3 C453FBE75917C8A07BB767230463FA6C271E21D3D92F1ACCC538A194A7C41CC8


            DsRecord dsRec = new DsRecord(
                ARSoft.Tools.Net.DomainName.Parse("example.com")   // Name: It defines the hostname of a record and whether the hostname will be appended to the label.
                // Fully qualified hostnames terminated by a period will not append the origin.
                , RecordClass.Any
                , 60                        // ttl The time-to-live in seconds. It specifies how long a resolver is supposed to cache or remember the DNS query
                     // before the query expires and a new one needs to be done.
                , 0                         // Key Tag: A short numeric value which can help quickly identify the referenced DNSKEY-record.
                , DnsSecAlgorithm.RsaSha256 // The algorithm of the referenced DNSKEY-record.
                , DnsSecDigestType.Sha256   // Digest Type: Cryptographic hash algorithm used to create the Digest value.
                , new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0xFF } // A cryptographic hash value of the referenced DNSKEY-record.
                );

            // dsRec.Digest
            string strDsRec = dsRec.ToString();

            System.Console.WriteLine(strDsRec);
            // example.com. 60 * DS 0 8 2 0102030405060708090AFF


            string strDS = dsRec.ToString();

            System.Console.WriteLine(strDS);
            // . 0 IN AAAA 127.0.0.1 // aaa
            // example.com. 0 IN AAAA 127.0.0.1
            // ds:
            // example.com. 60 * DS 0 8 2 010203
            // example.com. 60 * DS 0 8 2 010203040506070809
            // example.com. 60 * DS 0 8 2 0102030405060708090AFF



            // rec.Algorithm

            string key = @"AQPSKmynfzW4kyBv015MUG2DeIQ3
              Cbl+BBZH4b/0PY1kxkmvHjcZc8no
              kfzj31GajIQKY+5CptLr3buXA10h
              WqTkF7H6RfoRqXQeogmMHfpftf6z
              Mv1LyBUgia7za6ZEzOJBOztyvhjL
              742iU/TpPSEDhm2SNKLijfUppn1U
              aNvv4w== ";


            byte[] keyBytes = Base64ToByteArray(key);



            string signature = @"2BB183AF5F22588179A53B0A98631FAD1A292118";


            // ArsoftTestServer.KeyConversion.fromPublicKey()
            PublicKey pk = ArsoftTestServer.KeyConversionTo.toPublicKey(keyBytes, DnsSecAlgorithm.RsaSha1);

            System.Console.WriteLine(pk);

            byte[] generatedKeyBytes = ArsoftTestServer.KeyConversion.fromPublicKey(pk, DnsSecAlgorithm.RsaSha1);

            // ArsoftTestServer.Resolvers.Test4();
            // ArsoftTestServer.SimpleServer.Test();

            System.Console.WriteLine(System.Environment.NewLine);
            System.Console.WriteLine(" --- Press any key to continue --- ");
            System.Console.ReadKey();
        }
Ejemplo n.º 17
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.º 18
0
 internal virtual void AssertEquality(AaaaRecord expected, AaaaRecord actual)
 {
     Assert.AreEqual(expected.Address, actual.Address, "Should be equal");
 }
Ejemplo n.º 19
0
        private async Task <DnsMessage> umleitung_process_request(DnsMessage query)
        {
            DnsMessage upstreamResponse;
            DnsMessage response  = query.CreateResponseInstance();
            DomainName queryhost = DomainName.Parse(query.Questions[0].Name.ToString());

            if ((query.Questions.Count == 1))
            {
                m_log.WriteLine("[+] Processing " + query.Questions[0].RecordType + " query for " + queryhost);

                Boolean   match = false;
                IPAddress ip4   = null;
                IPAddress ip6   = null;

                // handle masqueraded entries first
                m_masq_config.DNSMasqEntries.ForEach(h =>
                {
                    if (queryhost.ToString().StartsWith(h.name))
                    {
                        match = true;

                        m_log.WriteLine(2, "[d] Using masquerading rules.");

                        response.ReturnCode = ReturnCode.NoError;

                        if (query.Questions[0].RecordType == RecordType.A)
                        {
                            ip4           = IPAddress.Parse(h.a);
                            ARecord new_a = new ARecord(query.Questions[0].Name, 666, ip4);
                            response.AnswerRecords.Add(new_a);
                        }
                        else if (query.Questions[0].RecordType == RecordType.Aaaa)
                        {
                            ip6 = IPAddress.Parse(h.aaaa);
                            AaaaRecord new_aaaa = new AaaaRecord(query.Questions[0].Name, 666, ip6);
                            response.AnswerRecords.Add(new_aaaa);
                        }
                    }
                });

                if (match)
                {
                    return(response);
                }

                // send query to upstream server
                DnsQuestion question = query.Questions[0];

                if (!m_props.UseCustomDns)
                {
                    m_log.WriteLine(2, "[d] Using system's DNS servers");
                    upstreamResponse = await DnsClient.Default.ResolveAsync(
                        question.Name, question.RecordType, question.RecordClass);
                }
                else
                {
                    m_props.CustomDnsServers.ForEach(d =>
                    {
                        m_log.WriteLine(2, "[d] Using custom DNS servers: " + d.ToString());
                    });

                    DnsClient dnsc = new DnsClient(m_props.CustomDnsServers, 10000);
                    upstreamResponse = await dnsc.ResolveAsync(
                        question.Name, question.RecordType, question.RecordClass);
                }

                // if we got an answer, copy it to the message sent to the client
                if (upstreamResponse != null && upstreamResponse.AnswerRecords.Count > 0)
                {
                    foreach (DnsRecordBase record in (upstreamResponse.AnswerRecords))
                    {
                        response.AnswerRecords.Add(record);
                    }

                    foreach (DnsRecordBase record in (upstreamResponse.AdditionalRecords))
                    {
                        response.AdditionalRecords.Add(record);
                    }
                }
                else
                {
                    // no dns record for queried host
                    if (upstreamResponse == null)
                    {
                        m_log.WriteLine(2, "upstreamResponse == null (timeout?)");
                    }
                }
                response.ReturnCode = ReturnCode.NoError;
            }
            return(response);
        }
Ejemplo n.º 20
0
        internal static AaaaRecordSetData DeserializeAaaaRecordSetData(JsonElement element)
        {
            Optional <string>  etag       = default;
            ResourceIdentifier id         = default;
            string             name       = default;
            ResourceType       type       = default;
            SystemData         systemData = default;
            Optional <IDictionary <string, string> > metadata = default;
            Optional <long>   ttl  = default;
            Optional <string> fqdn = default;
            Optional <string> provisioningState           = default;
            Optional <WritableSubResource> targetResource = default;
            Optional <IList <AaaaRecord> > aaaaRecords    = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("etag"))
                {
                    etag = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("systemData"))
                {
                    systemData = JsonSerializer.Deserialize <SystemData>(property.Value.ToString());
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("metadata"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            Dictionary <string, string> dictionary = new Dictionary <string, string>();
                            foreach (var property1 in property0.Value.EnumerateObject())
                            {
                                dictionary.Add(property1.Name, property1.Value.GetString());
                            }
                            metadata = dictionary;
                            continue;
                        }
                        if (property0.NameEquals("TTL"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            ttl = property0.Value.GetInt64();
                            continue;
                        }
                        if (property0.NameEquals("fqdn"))
                        {
                            fqdn = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("provisioningState"))
                        {
                            provisioningState = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("targetResource"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            targetResource = JsonSerializer.Deserialize <WritableSubResource>(property0.Value.ToString());
                            continue;
                        }
                        if (property0.NameEquals("AAAARecords"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <AaaaRecord> array = new List <AaaaRecord>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(AaaaRecord.DeserializeAaaaRecord(item));
                            }
                            aaaaRecords = array;
                            continue;
                        }
                    }
                    continue;
                }
            }
            return(new AaaaRecordSetData(id, name, type, systemData, etag.Value, Optional.ToDictionary(metadata), Optional.ToNullable(ttl), fqdn.Value, provisioningState.Value, targetResource, Optional.ToList(aaaaRecords)));
        }