public void CreateWithMailAddressRequestReturnsCorrectResultUsingLocalPartAndDomainNameFromContext()
 {
     // Fixture setup
     var request = typeof(MailAddress);
     var expectedLocalPart = new EmailAddressLocalPart(Guid.NewGuid().ToString());
     var expectedDomainName = new DomainName(Guid.NewGuid().ToString());
     var context = new DelegatingSpecimenContext()
     {
         OnResolve = r =>
        {
            Assert.True(typeof(EmailAddressLocalPart).Equals(r) || typeof(DomainName).Equals(r));
            if (typeof(EmailAddressLocalPart).Equals(r))
            {
                return expectedLocalPart;
            }
            else
            {
                return expectedDomainName;
            }
        }
     };
     var sut = new MailAddressGenerator();
     // Exercise system
     var result = (MailAddress)sut.Create(request, context);
     // Verify outcome
     Assert.Equal(expectedLocalPart.LocalPart, result.User);
     Assert.Equal(expectedDomainName.Domain, result.Host);
     // Teardown
 }
Example #2
0
 public bool Aktivasyon_Kontrol(string DomainNames)
 {
     bool Deger = false;
     DomainName D = new DomainName();
     Deger = D.Domainler().Where(x => x == DomainNames).Count() > 0 ? true : false;
     return Deger;
 }
Example #3
0
 public void ToStringReturnsCorrectResult()
 {
     // Fixture setup
     var expected = Guid.NewGuid().ToString();
     var sut = new DomainName(expected);
     // Exercise system
     var result = sut.ToString();
     // Verify outcome
     Assert.Equal(expected, result);
     // Teardown
 }
Example #4
0
 public void SutDoesNotEqualAnonymousObject()
 {
     // Fixture setup
     var sut = new DomainName(Guid.NewGuid().ToString());
     var anonymousObject = new object();
     // Exercise system
     bool result = sut.Equals(anonymousObject);
     // Verify outcome
     Assert.False(result);
     // Teardown
 }
Example #5
0
 public void SutDoesNotEqualOtherObjectWhenDomainNamesDiffer()
 {
     // Fixture setup
     var sut = new DomainName(Guid.NewGuid().ToString());
     object other = new DomainName(Guid.NewGuid().ToString());
     // Exercise system
     bool result = sut.Equals(other);
     // Verify outcome
     Assert.False(result);
     // Teardown
 }
Example #6
0
        public void SutEqualsOtherSutWhenDomainNamesAreEqual()
        {
            // Fixture setup
            var domainName = Guid.NewGuid().ToString();

            var sut = new DomainName(domainName);
            var other = new DomainName(domainName);
            // Exercise system
            bool result = sut.Equals(other);
            // Verify outcome
            Assert.True(result);
            // Teardown
        }
        public static DomainName Parse(string domainNameString)
        {
            if(string.IsNullOrWhiteSpace(domainNameString))
            {
                throw new ArgumentException("domainName cannot be null or empty.");
            }

            domainNameString = domainNameString.TrimEnd('.');

            var segments = domainNameString.Count(character => character == '.') + 1;

            var domainName = new DomainName();

            //What about domain names such as .co.uk?
            if(segments == 1)
            {
                domainName.Tld = domainNameString;
            }
            else if(segments == 2)
            {
                //Domain + TLD
                domainName.Domain = domainNameString;
                domainName.Tld = domainNameString.Substring(domainNameString.LastIndexOf('.') + 1);
            }
            else if(segments == 3)
            {
                domainName.Host = domainNameString.Substring(0,domainNameString.IndexOf('.'));
                domainName.Domain = domainNameString.Substring(domainNameString.IndexOf('.') + 1);
                domainName.Tld = domainNameString.Substring(domainNameString.LastIndexOf('.') + 1);
            }
            else
            {
                //TODO: Support domain names with more segments.
                throw new ArgumentException("Invalid domain name");
            }

            return domainName;
        }
Example #8
0
        /// <summary>
        /// Converts the string representation of a domain to its DomainName equivalent.  A return value
        /// indicates whether the operation succeeded.
        /// </summary>
        /// <param name="domainString"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public static bool TryParse(string domainString, out DomainName result)
        {
            bool retval = false;

            //  Our temporary domain parts:
            string _tld = string.Empty;
            string _sld = string.Empty;
            string _subdomain = string.Empty;
            TLDRule _tldrule = default(TLDRule);
            result = null;

            try
            {
                //  Try parsing the domain name ... this might throw formatting exceptions
                ParseDomainName(domainString, out _tld, out _sld, out _subdomain, out _tldrule);

                //  Construct a new DomainName object and return it
                result = new DomainName(_tld, _sld, _subdomain, _tldrule);

                //  Return 'true'
                retval = true;
            }
            catch
            {
                //  Looks like something bad happened -- return 'false'
                retval = false;
            }

            return retval;
        }
Example #9
0
 /// <summary>
 ///   Creates a new instance of the UnknownRecord class
 /// </summary>
 /// <param name="name"> Domain name of the record </param>
 /// <param name="recordType"> Record type </param>
 /// <param name="recordClass"> Record class </param>
 /// <param name="timeToLive"> Seconds the record should be cached at most </param>
 /// <param name="recordData"> Binary data of the RDATA section of the record </param>
 public UnknownRecord(DomainName name, RecordType recordType, RecordClass recordClass, int timeToLive, byte[] recordData)
     : base(name, recordType, recordClass, timeToLive)
 {
     RecordData = recordData ?? new byte[] { };
 }
 public Site GetSiteByDomain(DomainName name)
 {
     return repo.GetByDomain(name);
 }
Example #11
0
 public override int GetHashCode()
 {
     return(DomainName.GetHashCode());
 }
Example #12
0
 /// <summary>
 ///   Queries a dns resolver for specified records as an asynchronous operation.
 /// </summary>
 /// <typeparam name="T"> Type of records, that should be returned </typeparam>
 /// <param name="resolver"> The resolver instance, that should be used for queries </param>
 /// <param name="name"> Domain, that should be queried </param>
 /// <param name="recordType"> Type the should be queried </param>
 /// <param name="recordClass"> Class the should be queried </param>
 /// <param name="token"> The token to monitor cancellation requests </param>
 /// <returns> A list of matching <see cref="DnsRecordBase">records</see> </returns>
 public static Task <DnsSecResult <T> > ResolveSecureAsync <T>(this IDnsSecResolver resolver, string name, RecordType recordType = RecordType.A, RecordClass recordClass = RecordClass.INet, CancellationToken token = default(CancellationToken))
     where T : DnsRecordBase
 {
     return(resolver.ResolveSecureAsync <T>(DomainName.Parse(name), recordType, recordClass, token));
 }
Example #13
0
 Task <DnsSecResult <TRecord> > IInternalDnsSecResolver <State> .ResolveSecureAsync <TRecord>(DomainName name, RecordType recordType, RecordClass recordClass, State state, CancellationToken token)
 {
     return(ResolveAsyncInternal <TRecord>(name, recordType, recordClass, state, token));
 }
Example #14
0
        private async Task <DnsSecValidationResult> ValidateNSec3Async(DomainName name, RecordType recordType, RecordClass recordClass, List <RrSigRecord> rrSigRecords, bool checkWildcard, DomainName zoneApex, DnsMessageBase msg, TState state, CancellationToken token)
        {
            List <NSec3Record> nsecRecords = msg.AuthorityRecords.OfType <NSec3Record>().ToList();

            if (nsecRecords.Count == 0)
            {
                return(DnsSecValidationResult.Indeterminate);
            }

            foreach (var nsecGroup in nsecRecords.GroupBy(x => x.Name))
            {
                DnsSecValidationResult validationResult = await ValidateRrSigAsync(nsecGroup.Key, RecordType.NSec3, recordClass, nsecGroup.ToList(), rrSigRecords, zoneApex, msg, state, token).ConfigureAwait(false);

                if (validationResult != DnsSecValidationResult.Signed)
                {
                    return(validationResult);
                }
            }

            var nsec3Parameter = nsecRecords.Where(x => x.Name.GetParentName().Equals(zoneApex)).Where(x => x.HashAlgorithm.IsSupported()).Select(x => new { x.HashAlgorithm, x.Iterations, x.Salt }).OrderBy(x => x.HashAlgorithm.GetPriority()).First();

            DomainName hashedName = name.GetNsec3HashName(nsec3Parameter.HashAlgorithm, nsec3Parameter.Iterations, nsec3Parameter.Salt, zoneApex);

            if (recordType == RecordType.Ds && nsecRecords.Any(x => (x.Flags == 1) && (x.IsCovering(hashedName))))
            {
                return(DnsSecValidationResult.Unsigned);
            }

            var directMatch = nsecRecords.FirstOrDefault(x => x.Name.Equals(hashedName));

            if (directMatch != null)
            {
                return(directMatch.Types.Contains(recordType) ? DnsSecValidationResult.Bogus : DnsSecValidationResult.Signed);
            }

            // find closest encloser
            DomainName current            = name;
            DomainName previousHashedName = hashedName;

            while (true)
            {
                if (nsecRecords.Any(x => x.Name == hashedName))
                {
                    break;
                }

                if (current == zoneApex)
                {
                    return(DnsSecValidationResult.Bogus); // closest encloser could not be found, but at least the zone apex must be found as
                }
                current            = current.GetParentName();
                previousHashedName = hashedName;
                hashedName         = current.GetNsec3HashName(nsec3Parameter.HashAlgorithm, nsec3Parameter.Iterations, nsec3Parameter.Salt, zoneApex);
            }

            if (!nsecRecords.Any(x => x.IsCovering(previousHashedName)))
            {
                return(DnsSecValidationResult.Bogus);
            }

            if (checkWildcard)
            {
                DomainName wildcardHashName = (DomainName.Asterisk + current).GetNsec3HashName(nsec3Parameter.HashAlgorithm, nsec3Parameter.Iterations, nsec3Parameter.Salt, zoneApex);

                var wildcardDirectMatch = nsecRecords.FirstOrDefault(x => x.Name.Equals(wildcardHashName));
                if ((wildcardDirectMatch != null) && (!wildcardDirectMatch.Types.Contains(recordType)))
                {
                    return(wildcardDirectMatch.Types.Contains(recordType) ? DnsSecValidationResult.Bogus : DnsSecValidationResult.Signed);
                }

                var wildcardCoveringMatch = nsecRecords.FirstOrDefault(x => x.IsCovering(wildcardHashName));
                return((wildcardCoveringMatch != null) ? DnsSecValidationResult.Signed : DnsSecValidationResult.Bogus);
            }
            else
            {
                return(DnsSecValidationResult.Signed);
            }
        }
Example #15
0
 /// <summary>
 ///   Creates a new instance of the PxRecord class
 /// </summary>
 /// <param name="name"> Name of the record </param>
 /// <param name="timeToLive"> Seconds the record should be cached at most </param>
 /// <param name="preference"> Preference of the record </param>
 /// <param name="map822"> Domain name containing the RFC822 domain </param>
 /// <param name="mapX400"> Domain name containing the X.400 part </param>
 public PxRecord(DomainName name, int timeToLive, ushort preference, DomainName map822, DomainName mapX400)
     : base(name, RecordType.Px, RecordClass.INet, timeToLive)
 {
     Preference = preference;
     Map822     = map822 ?? DomainName.Root;
     MapX400    = mapX400 ?? DomainName.Root;
 }
 protected TextRecordBase(DomainName name, RecordType recordType, int timeToLive, IEnumerable <string> textParts)
     : base(name, recordType, RecordClass.INet, timeToLive)
 {
     TextParts = new List <string>(textParts);
 }
 protected TextRecordBase(DomainName name, RecordType recordType, int timeToLive, string textData)
     : this(name, recordType, timeToLive, new List <string> {
     textData ?? String.Empty
 })
 {
 }
Example #18
0
 /// <summary>
 ///   Creates a new instance of the IpSecKeyRecord class
 /// </summary>
 /// <param name="name"> Name of the record </param>
 /// <param name="timeToLive"> Seconds the record should be cached at most </param>
 /// <param name="precedence"> Precedence of the record </param>
 /// <param name="algorithm"> Algorithm of the key </param>
 /// <param name="gateway"> Address of the gateway </param>
 /// <param name="publicKey"> Binary data of the public key </param>
 public IpSecKeyRecord(DomainName name, int timeToLive, byte precedence, IpSecAlgorithm algorithm, DomainName gateway, byte[] publicKey)
     : base(name, RecordType.IpSecKey, RecordClass.INet, timeToLive)
 {
     Precedence  = precedence;
     GatewayType = IpSecGatewayType.Domain;
     Algorithm   = algorithm;
     Gateway     = (gateway ?? DomainName.Root).ToString();
     PublicKey   = publicKey ?? Array.Empty <byte>();
 }
Example #19
0
        /// <summary>
        ///   Creates a new signing key pair
        /// </summary>
        /// <param name="name">The name of the key or zone</param>
        /// <param name="recordClass">The record class of the DnsKeyRecord</param>
        /// <param name="timeToLive">The TTL in seconds to the DnsKeyRecord</param>
        /// <param name="flags">The Flags of the DnsKeyRecord</param>
        /// <param name="protocol">The protocol version</param>
        /// <param name="algorithm">The key algorithm</param>
        /// <param name="keyStrength">The key strength or 0 for default strength</param>
        /// <returns></returns>
        public static DnsKeyRecord CreateSigningKey(DomainName name, RecordClass recordClass, int timeToLive, DnsKeyFlags flags, byte protocol, DnsSecAlgorithm algorithm, int keyStrength = 0)
        {
            byte[] privateKey;
            byte[] publicKey;

            switch (algorithm)
            {
            case DnsSecAlgorithm.RsaSha1:
            case DnsSecAlgorithm.RsaSha1Nsec3Sha1:
            case DnsSecAlgorithm.RsaSha256:
            case DnsSecAlgorithm.RsaSha512:
                if (keyStrength == 0)
                {
                    keyStrength = (flags == (DnsKeyFlags.Zone | DnsKeyFlags.SecureEntryPoint)) ? 2048 : 1024;
                }

                RsaKeyPairGenerator rsaKeyGen = new RsaKeyPairGenerator();
                rsaKeyGen.Init(new KeyGenerationParameters(_secureRandom, keyStrength));
                var rsaKey = rsaKeyGen.GenerateKeyPair();
                privateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(rsaKey.Private).GetDerEncoded();
                var rsaPublicKey = (RsaKeyParameters)rsaKey.Public;
                var rsaExponent  = rsaPublicKey.Exponent.ToByteArrayUnsigned();
                var rsaModulus   = rsaPublicKey.Modulus.ToByteArrayUnsigned();

                int offset = 1;
                if (rsaExponent.Length > 255)
                {
                    publicKey = new byte[3 + rsaExponent.Length + rsaModulus.Length];
                    DnsMessageBase.EncodeUShort(publicKey, ref offset, (ushort)publicKey.Length);
                }
                else
                {
                    publicKey    = new byte[1 + rsaExponent.Length + rsaModulus.Length];
                    publicKey[0] = (byte)rsaExponent.Length;
                }
                DnsMessageBase.EncodeByteArray(publicKey, ref offset, rsaExponent);
                DnsMessageBase.EncodeByteArray(publicKey, ref offset, rsaModulus);
                break;

            case DnsSecAlgorithm.Dsa:
            case DnsSecAlgorithm.DsaNsec3Sha1:
                if (keyStrength == 0)
                {
                    keyStrength = 1024;
                }

                DsaParametersGenerator dsaParamsGen = new DsaParametersGenerator();
                dsaParamsGen.Init(keyStrength, 12, _secureRandom);
                DsaKeyPairGenerator dsaKeyGen = new DsaKeyPairGenerator();
                dsaKeyGen.Init(new DsaKeyGenerationParameters(_secureRandom, dsaParamsGen.GenerateParameters()));
                var dsaKey = dsaKeyGen.GenerateKeyPair();
                privateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(dsaKey.Private).GetDerEncoded();
                var dsaPublicKey = (DsaPublicKeyParameters)dsaKey.Public;

                var dsaY = dsaPublicKey.Y.ToByteArrayUnsigned();
                var dsaP = dsaPublicKey.Parameters.P.ToByteArrayUnsigned();
                var dsaQ = dsaPublicKey.Parameters.Q.ToByteArrayUnsigned();
                var dsaG = dsaPublicKey.Parameters.G.ToByteArrayUnsigned();
                var dsaT = (byte)((dsaY.Length - 64) / 8);

                publicKey    = new byte[21 + 3 * dsaY.Length];
                publicKey[0] = dsaT;
                dsaQ.CopyTo(publicKey, 1);
                dsaP.CopyTo(publicKey, 21);
                dsaG.CopyTo(publicKey, 21 + dsaY.Length);
                dsaY.CopyTo(publicKey, 21 + 2 * dsaY.Length);
                break;

            case DnsSecAlgorithm.EccGost:
                ECDomainParameters gostEcDomainParameters = ECGost3410NamedCurves.GetByOid(CryptoProObjectIdentifiers.GostR3410x2001CryptoProA);

                var gostKeyGen = new ECKeyPairGenerator();
                gostKeyGen.Init(new ECKeyGenerationParameters(gostEcDomainParameters, _secureRandom));

                var gostKey = gostKeyGen.GenerateKeyPair();
                privateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(gostKey.Private).GetDerEncoded();
                var gostPublicKey = (ECPublicKeyParameters)gostKey.Public;

                publicKey = new byte[64];

                gostPublicKey.Q.AffineXCoord.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, 32);
                gostPublicKey.Q.AffineYCoord.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, 0);

                publicKey = publicKey.Reverse().ToArray();
                break;

            case DnsSecAlgorithm.EcDsaP256Sha256:
            case DnsSecAlgorithm.EcDsaP384Sha384:
                int            ecDsaDigestSize;
                X9ECParameters ecDsaCurveParameter;

                if (algorithm == DnsSecAlgorithm.EcDsaP256Sha256)
                {
                    ecDsaDigestSize     = new Sha256Digest().GetDigestSize();
                    ecDsaCurveParameter = NistNamedCurves.GetByOid(SecObjectIdentifiers.SecP256r1);
                }
                else
                {
                    ecDsaDigestSize     = new Sha384Digest().GetDigestSize();
                    ecDsaCurveParameter = NistNamedCurves.GetByOid(SecObjectIdentifiers.SecP384r1);
                }

                ECDomainParameters ecDsaP384EcDomainParameters = new ECDomainParameters(
                    ecDsaCurveParameter.Curve,
                    ecDsaCurveParameter.G,
                    ecDsaCurveParameter.N,
                    ecDsaCurveParameter.H,
                    ecDsaCurveParameter.GetSeed());

                var ecDsaKeyGen = new ECKeyPairGenerator();
                ecDsaKeyGen.Init(new ECKeyGenerationParameters(ecDsaP384EcDomainParameters, _secureRandom));

                var ecDsaKey = ecDsaKeyGen.GenerateKeyPair();
                privateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(ecDsaKey.Private).GetDerEncoded();
                var ecDsaPublicKey = (ECPublicKeyParameters)ecDsaKey.Public;

                publicKey = new byte[ecDsaDigestSize * 2];

                ecDsaPublicKey.Q.AffineXCoord.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, 0);
                ecDsaPublicKey.Q.AffineYCoord.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, ecDsaDigestSize);
                break;

            default:
                throw new NotSupportedException();
            }

            return(new DnsKeyRecord(name, recordClass, timeToLive, flags, protocol, algorithm, publicKey, privateKey));
        }
Example #20
0
 /// <summary>
 ///   Creates a new instance of the DnsKeyRecord class
 /// </summary>
 /// <param name="name"> Name of the record </param>
 /// <param name="recordClass"> Class of the record </param>
 /// <param name="timeToLive"> Seconds the record should be cached at most </param>
 /// <param name="flags"> Flags of the key </param>
 /// <param name="protocol"> Protocol field </param>
 /// <param name="algorithm"> Algorithm of the key </param>
 /// <param name="publicKey"> Binary data of the public key </param>
 public DnsKeyRecord(DomainName name, RecordClass recordClass, int timeToLive, DnsKeyFlags flags, byte protocol, DnsSecAlgorithm algorithm, byte[] publicKey)
     : this(name, recordClass, timeToLive, flags, protocol, algorithm, publicKey, null)
 {
 }
Example #21
0
        public async Task <IconResult> GetIconAsync(string domain)
        {
            if (_ipRegex.IsMatch(domain))
            {
                _logger.LogWarning("IP address: {0}.", domain);
                return(null);
            }

            if (!Uri.TryCreate($"https://{domain}", UriKind.Absolute, out var parsedHttpsUri))
            {
                _logger.LogWarning("Bad domain: {0}.", domain);
                return(null);
            }

            var uri      = parsedHttpsUri;
            var response = await GetAndFollowAsync(uri, 2);

            if ((response == null || !response.IsSuccessStatusCode) &&
                Uri.TryCreate($"http://{parsedHttpsUri.Host}", UriKind.Absolute, out var parsedHttpUri))
            {
                Cleanup(response);
                uri      = parsedHttpUri;
                response = await GetAndFollowAsync(uri, 2);

                if (response == null || !response.IsSuccessStatusCode)
                {
                    var dotCount = domain.Count(c => c == '.');
                    if (dotCount > 1 && DomainName.TryParseBaseDomain(domain, out var baseDomain) &&
                        Uri.TryCreate($"https://{baseDomain}", UriKind.Absolute, out var parsedBaseUri))
                    {
                        Cleanup(response);
                        uri      = parsedBaseUri;
                        response = await GetAndFollowAsync(uri, 2);
                    }
                    else if (dotCount < 2 &&
                             Uri.TryCreate($"https://www.{parsedHttpsUri.Host}", UriKind.Absolute, out var parsedWwwUri))
                    {
                        Cleanup(response);
                        uri      = parsedWwwUri;
                        response = await GetAndFollowAsync(uri, 2);
                    }
                }
            }

            if (response?.Content == null || !response.IsSuccessStatusCode)
            {
                _logger.LogWarning("Couldn't load a website for {0}: {1}.", domain,
                                   response?.StatusCode.ToString() ?? "null");
                Cleanup(response);
                return(null);
            }

            var parser = new HtmlParser();

            using (response)
                using (var htmlStream = await response.Content.ReadAsStreamAsync())
                    using (var document = await parser.ParseDocumentAsync(htmlStream))
                    {
                        uri = response.RequestMessage.RequestUri;
                        if (document.DocumentElement == null)
                        {
                            _logger.LogWarning("No DocumentElement for {0}.", domain);
                            return(null);
                        }

                        var baseUrl     = "/";
                        var baseUrlNode = document.QuerySelector("head base[href]");
                        if (baseUrlNode != null)
                        {
                            var hrefAttr = baseUrlNode.Attributes["href"];
                            if (!string.IsNullOrWhiteSpace(hrefAttr?.Value))
                            {
                                baseUrl = hrefAttr.Value;
                            }

                            baseUrlNode = null;
                            hrefAttr    = null;
                        }

                        var icons = new List <IconResult>();
                        var links = document.QuerySelectorAll("head link[href]");
                        if (links != null)
                        {
                            foreach (var link in links.Take(200))
                            {
                                var hrefAttr = link.Attributes["href"];
                                if (string.IsNullOrWhiteSpace(hrefAttr?.Value))
                                {
                                    continue;
                                }

                                var relAttr   = link.Attributes["rel"];
                                var sizesAttr = link.Attributes["sizes"];
                                if (relAttr != null && _iconRels.Contains(relAttr.Value.ToLower()))
                                {
                                    icons.Add(new IconResult(hrefAttr.Value, sizesAttr?.Value));
                                }
                                else if (relAttr == null || !_blacklistedRels.Contains(relAttr.Value.ToLower()))
                                {
                                    try
                                    {
                                        var extension = Path.GetExtension(hrefAttr.Value);
                                        if (_iconExtensions.Contains(extension.ToLower()))
                                        {
                                            icons.Add(new IconResult(hrefAttr.Value, sizesAttr?.Value));
                                        }
                                    }
                                    catch (ArgumentException) { }
                                }

                                sizesAttr = null;
                                relAttr   = null;
                                hrefAttr  = null;
                            }

                            links = null;
                        }

                        var iconResultTasks = new List <Task>();
                        foreach (var icon in icons.OrderBy(i => i.Priority).Take(10))
                        {
                            Uri iconUri = null;
                            if (icon.Path.StartsWith("//") && Uri.TryCreate($"{GetScheme(uri)}://{icon.Path.Substring(2)}",
                                                                            UriKind.Absolute, out var slashUri))
                            {
                                iconUri = slashUri;
                            }
                            else if (Uri.TryCreate(icon.Path, UriKind.Relative, out var relUri))
                            {
                                iconUri = ResolveUri($"{GetScheme(uri)}://{uri.Host}", baseUrl, relUri.OriginalString);
                            }
                            else if (Uri.TryCreate(icon.Path, UriKind.Absolute, out var absUri))
                            {
                                iconUri = absUri;
                            }

                            if (iconUri != null)
                            {
                                var task = GetIconAsync(iconUri).ContinueWith(async(r) =>
                                {
                                    var result = await r;
                                    if (result != null)
                                    {
                                        icon.Path = iconUri.ToString();
                                        icon.Icon = result.Icon;
                                    }
                                });
                                iconResultTasks.Add(task);
                            }
                        }

                        await Task.WhenAll(iconResultTasks);

                        if (!icons.Any(i => i.Icon != null))
                        {
                            var faviconUri = ResolveUri($"{GetScheme(uri)}://{uri.Host}", "favicon.ico");
                            var result     = await GetIconAsync(faviconUri);

                            if (result != null)
                            {
                                icons.Add(result);
                            }
                            else
                            {
                                _logger.LogWarning("No favicon.ico found for {0}.", uri.Host);
                                return(null);
                            }
                        }

                        return(icons.Where(i => i.Icon != null).OrderBy(i => i.Priority).First());
                    }
        }
Example #22
0
 public URLSummary(string hostnameAndPort, string port, DomainName domain)
 {
     HostnameAndPort = hostnameAndPort;
     Port = port;
     Domain = domain;
 }
Example #23
0
        private async Task <DnsSecValidationResult> ValidateNonExistenceAsync(DomainName name, RecordType recordType, RecordClass recordClass, List <RrSigRecord> rrSigRecords, DomainName stop, DomainName zoneApex, DnsMessageBase msg, TState state, CancellationToken token)
        {
            var nsecRes = await ValidateNSecAsync(name, recordType, recordClass, rrSigRecords, stop, zoneApex, msg, state, token).ConfigureAwait(false);

            if (nsecRes == DnsSecValidationResult.Signed)
            {
                return(nsecRes);
            }

            var nsec3Res = await ValidateNSec3Async(name, recordType, recordClass, rrSigRecords, stop == DomainName.Asterisk + zoneApex, zoneApex, msg, state, token).ConfigureAwait(false);

            if (nsec3Res == DnsSecValidationResult.Signed)
            {
                return(nsec3Res);
            }

            if ((nsecRes == DnsSecValidationResult.Unsigned) || (nsec3Res == DnsSecValidationResult.Unsigned))
            {
                return(DnsSecValidationResult.Unsigned);
            }

            if ((nsecRes == DnsSecValidationResult.Bogus) || (nsec3Res == DnsSecValidationResult.Bogus))
            {
                return(DnsSecValidationResult.Bogus);
            }

            return(DnsSecValidationResult.Indeterminate);
        }
Example #24
0
 internal override void ParseRecordData(byte[] resultData, int startPosition, int length)
 {
     Preference = DnsMessageBase.ParseUShort(resultData, ref startPosition);
     Map822     = DnsMessageBase.ParseDomainName(resultData, ref startPosition);
     MapX400    = DnsMessageBase.ParseDomainName(resultData, ref startPosition);
 }
        private async Task <List <T> > ResolveAsyncInternal <T>(DomainName name, RecordType recordType, RecordClass recordClass, State state, CancellationToken token)
            where T : DnsRecordBase
        {
            List <T> cachedResults;

            if (_cache.TryGetRecords(name, recordType, recordClass, out cachedResults))
            {
                return(cachedResults);
            }

            List <CNameRecord> cachedCNames;

            if (_cache.TryGetRecords(name, RecordType.CName, recordClass, out cachedCNames))
            {
                return(await ResolveAsyncInternal <T>(cachedCNames.First().CanonicalName, recordType, recordClass, state, token));
            }

            DnsMessage msg = await ResolveMessageAsync(name, recordType, recordClass, state, token);

            // check for cname
            List <DnsRecordBase> cNameRecords = msg.AnswerRecords.Where(x => (x.RecordType == RecordType.CName) && (x.RecordClass == recordClass) && x.Name.Equals(name)).ToList();

            if (cNameRecords.Count > 0)
            {
                _cache.Add(name, RecordType.CName, recordClass, cNameRecords, DnsSecValidationResult.Indeterminate, cNameRecords.Min(x => x.TimeToLive));

                DomainName canonicalName = ((CNameRecord)cNameRecords.First()).CanonicalName;

                List <DnsRecordBase> matchingAdditionalRecords = msg.AnswerRecords.Where(x => (x.RecordType == recordType) && (x.RecordClass == recordClass) && x.Name.Equals(canonicalName)).ToList();
                if (matchingAdditionalRecords.Count > 0)
                {
                    _cache.Add(canonicalName, recordType, recordClass, matchingAdditionalRecords, DnsSecValidationResult.Indeterminate, matchingAdditionalRecords.Min(x => x.TimeToLive));
                    return(matchingAdditionalRecords.OfType <T>().ToList());
                }

                return(await ResolveAsyncInternal <T>(canonicalName, recordType, recordClass, state, token));
            }

            // check for "normal" answer
            List <DnsRecordBase> answerRecords = msg.AnswerRecords.Where(x => (x.RecordType == recordType) && (x.RecordClass == recordClass) && x.Name.Equals(name)).ToList();

            if (answerRecords.Count > 0)
            {
                _cache.Add(name, recordType, recordClass, answerRecords, DnsSecValidationResult.Indeterminate, answerRecords.Min(x => x.TimeToLive));
                return(answerRecords.OfType <T>().ToList());
            }

            // check for negative answer
            SoaRecord soaRecord = msg.AuthorityRecords
                                  .Where(x =>
                                         (x.RecordType == RecordType.Soa) &&
                                         (name.Equals(x.Name) || name.IsSubDomainOf(x.Name)))
                                  .OfType <SoaRecord>()
                                  .FirstOrDefault();

            if (soaRecord != null)
            {
                _cache.Add(name, recordType, recordClass, new List <DnsRecordBase>(), DnsSecValidationResult.Indeterminate, soaRecord.NegativeCachingTTL);
                return(new List <T>());
            }

            // authoritive response does not contain answer
            throw new Exception("Could not resolve " + name);
        }
Example #26
0
 /// <summary>
 ///   Creates a new instance of the RrSigRecord class
 /// </summary>
 /// <param name="name"> Name of the record </param>
 /// <param name="recordClass"> Class of the record </param>
 /// <param name="timeToLive"> Seconds the record should be cached at most </param>
 /// <param name="typeCovered">
 ///   <see cref="RecordType">Record type</see> that is covered by this record
 /// </param>
 /// <param name="algorithm">
 ///   <see cref="DnsSecAlgorithm">Algorithm</see> that is used for signature
 /// </param>
 /// <param name="labels"> Label count of original record that is covered by this record </param>
 /// <param name="originalTimeToLive"> Original time to live value of original record that is covered by this record </param>
 /// <param name="signatureExpiration"> Signature is valid until this date </param>
 /// <param name="signatureInception"> Signature is valid from this date </param>
 /// <param name="keyTag"> Key tag </param>
 /// <param name="signersName"> Domain name of generator of the signature </param>
 /// <param name="signature"> Binary data of the signature </param>
 public RrSigRecord(DomainName name, RecordClass recordClass, int timeToLive, RecordType typeCovered, DnsSecAlgorithm algorithm, byte labels, int originalTimeToLive, DateTime signatureExpiration, DateTime signatureInception, ushort keyTag, DomainName signersName, byte[] signature)
     : base(name, RecordType.RrSig, recordClass, timeToLive)
 {
     TypeCovered         = typeCovered;
     Algorithm           = algorithm;
     Labels              = labels;
     OriginalTimeToLive  = originalTimeToLive;
     SignatureExpiration = signatureExpiration;
     SignatureInception  = signatureInception;
     KeyTag              = keyTag;
     SignersName         = signersName ?? DomainName.Root;
     Signature           = signature ?? Array.Empty <byte>();
 }
Example #27
0
 /// <summary>
 ///   Queries a dns resolver for specified records.
 /// </summary>
 /// <typeparam name="T"> Type of records, that should be returned </typeparam>
 /// <param name="resolver"> The resolver instance, that should be used for queries </param>
 /// <param name="name"> Domain, that should be queried </param>
 /// <param name="recordType"> Type the should be queried </param>
 /// <param name="recordClass"> Class the should be queried </param>
 /// <returns> The validating result and a list of matching <see cref="DnsRecordBase">records</see> </returns>
 public static DnsSecResult <T> ResolveSecure <T>(this IDnsSecResolver resolver, string name, RecordType recordType = RecordType.A, RecordClass recordClass = RecordClass.INet)
     where T : DnsRecordBase
 {
     return(resolver.ResolveSecure <T>(DomainName.Parse(name), recordType, recordClass));
 }
Example #28
0
        private 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);
            }
            catch (WebException e)
            {
                HttpWebResponse response = (HttpWebResponse)e.Response;
                try
                {
                    BackgroundLog($@"| - Catch WebException : {Convert.ToInt32(response.StatusCode)} {response.StatusCode} | {domainName} | {response.ResponseUri}");
                }
                catch (Exception exception)
                {
                    BackgroundLog($@"| - Catch WebException : {exception.Message} | {domainName} | {dohUrl}");
                    //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:
                    {
                        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:
                    {
                        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);
        }
Example #29
0
 /// <summary>
 ///   Creates a new instance of the ARecord class
 /// </summary>
 /// <param name="name"> Domain name of the host </param>
 /// <param name="timeToLive"> Seconds the record should be cached at most </param>
 /// <param name="address"> IP address of the host </param>
 public ARecord(DomainName name, int timeToLive, IPAddress address)
     : base(name, RecordType.A, timeToLive, address ?? IPAddress.None)
 {
 }
Example #30
0
        public static async Task ServerOnQueryReceived(object sender, QueryReceivedEventArgs e)
        {
            if (!(e.Query is DnsMessage query))
            {
                return;
            }

            IPAddress clientAddress = e.RemoteEndpoint.Address;

            if (DnsSettings.EDnsCustomize)
            {
                clientAddress = Equals(DnsSettings.EDnsIp, IPAddress.Parse("0.0.0.1"))
                    ? IPAddress.Parse(MainWindow.IntIPAddr.ToString().Substring(
                                          0, MainWindow.IntIPAddr.ToString().LastIndexOf(".", StringComparison.Ordinal)) + ".1") : DnsSettings.EDnsIp;
            }
            else if (Equals(clientAddress, IPAddress.Loopback) || IpTools.InSameLaNet(clientAddress, MainWindow.LocIPAddr))
            {
                clientAddress = MainWindow.IntIPAddr;
            }

            DnsMessage response = query.CreateResponseInstance();

            if (query.Questions.Count <= 0)
            {
                response.ReturnCode = ReturnCode.ServerFailure;
            }

            else
            {
                foreach (DnsQuestion dnsQuestion in query.Questions)
                {
                    response.ReturnCode = ReturnCode.NoError;

                    if (DnsSettings.DebugLog)
                    {
                        BackgroundLog($@"| {DateTime.Now} {e.RemoteEndpoint.Address} : {dnsQuestion.Name} | {dnsQuestion.RecordType.ToString().ToUpper()}");
                    }

                    if (DomainName.Parse(new Uri(DnsSettings.HttpsDnsUrl).DnsSafeHost) == dnsQuestion.Name ||
                        DomainName.Parse(new Uri(DnsSettings.SecondHttpsDnsUrl).DnsSafeHost) == dnsQuestion.Name ||
                        DomainName.Parse(new Uri(UrlSettings.WhatMyIpApi).DnsSafeHost) == dnsQuestion.Name)
                    {
                        response.AnswerRecords.AddRange(new DnsClient(DnsSettings.SecondDnsIp, 5000)
                                                        .Resolve(dnsQuestion.Name, dnsQuestion.RecordType).AnswerRecords);

                        if (DnsSettings.DebugLog)
                        {
                            BackgroundLog($"| -- Startup SecondDns : {DnsSettings.SecondDnsIp}");
                        }
                    }
                    else if (DnsSettings.DnsCacheEnable && MemoryCache.Default.Contains($"{dnsQuestion.Name}{dnsQuestion.RecordType}"))
                    {
                        response.AnswerRecords.AddRange(
                            (List <DnsRecordBase>)MemoryCache.Default.Get($"{dnsQuestion.Name}{dnsQuestion.RecordType}"));
                        response.AnswerRecords.Add(new TxtRecord(DomainName.Parse("cache.auroradns.mili.one"), 0,
                                                                 "AuroraDNSC Cached"));

                        if (DnsSettings.DebugLog)
                        {
                            BackgroundLog($@"|- CacheContains : {dnsQuestion.Name} | Count : {MemoryCache.Default.Count()}");
                        }
                    }
                    else if (DnsSettings.BlackListEnable && DnsSettings.BlackList.Contains(dnsQuestion.Name))
                    {
                        response.AnswerRecords.Add(new ARecord(dnsQuestion.Name, 10, IPAddress.Any));
                        response.AnswerRecords.Add(new TxtRecord(DomainName.Parse("blacklist.auroradns.mili.one"), 0,
                                                                 "AuroraDNSC Blocked"));

                        if (DnsSettings.DebugLog)
                        {
                            BackgroundLog(@"|- BlackList");
                        }
                    }
                    else if (DnsSettings.WhiteListEnable && DnsSettings.WhiteList.ContainsKey(dnsQuestion.Name))
                    {
                        List <DnsRecordBase> whiteRecords = new List <DnsRecordBase>();
                        if (!IpTools.IsIp(DnsSettings.WhiteList[dnsQuestion.Name]))
                        {
                            whiteRecords.AddRange(new DnsClient(DnsSettings.SecondDnsIp, 5000)
                                                  .Resolve(dnsQuestion.Name, dnsQuestion.RecordType).AnswerRecords);
                        }
                        else
                        {
                            whiteRecords.Add(new ARecord(dnsQuestion.Name, 10,
                                                         IPAddress.Parse(DnsSettings.WhiteList[dnsQuestion.Name])));
                        }

                        response.AnswerRecords.AddRange(whiteRecords);
                        response.AnswerRecords.Add(new TxtRecord(DomainName.Parse("whitelist.auroradns.mili.one"), 0,
                                                                 "AuroraDNSC Rewrote"));

                        if (DnsSettings.DebugLog)
                        {
                            BackgroundLog(@"|- WhiteList");
                        }
                    }
                    else if (DnsSettings.ChinaListEnable && DomainNameInChinaList(dnsQuestion.Name))
                    {
                        try
                        {
                            var resolvedDnsList = ResolveOverHttpByDPlus(dnsQuestion.Name.ToString());
                            if (resolvedDnsList != null && resolvedDnsList != new List <DnsRecordBase>())
                            {
                                resolvedDnsList.Add(new TxtRecord(DomainName.Parse("chinalist.auroradns.mili.one"),
                                                                  0, "AuroraDNSC ChinaList - DNSPod D+"));
                                foreach (var item in resolvedDnsList)
                                {
                                    response.AnswerRecords.Add(item);
                                }

                                if (DnsSettings.DebugLog)
                                {
                                    BackgroundLog(@"|- ChinaList - DNSPOD D+");
                                }

                                if (DnsSettings.DnsCacheEnable && response.ReturnCode == ReturnCode.NoError)
                                {
                                    BackgroundWriteCache(
                                        new CacheItem($"{dnsQuestion.Name}{dnsQuestion.RecordType}",
                                                      resolvedDnsList),
                                        resolvedDnsList[0].TimeToLive);
                                }
                            }
                        }
                        catch (Exception exception)
                        {
                            BackgroundLog(exception.ToString());
                        }
                    }
                    else
                    {
                        //Resolve
                        try
                        {
                            (List <DnsRecordBase> resolvedDnsList, ReturnCode statusCode) = DnsSettings.DnsMsgEnable
                                ? ResolveOverHttpsByDnsMsg(clientAddress.ToString(),
                                                           dnsQuestion.Name.ToString(), DnsSettings.HttpsDnsUrl, DnsSettings.ProxyEnable,
                                                           DnsSettings.WProxy, dnsQuestion.RecordType)
                                : ResolveOverHttpsByDnsJson(clientAddress.ToString(),
                                                            dnsQuestion.Name.ToString(), DnsSettings.HttpsDnsUrl, DnsSettings.ProxyEnable,
                                                            DnsSettings.WProxy, dnsQuestion.RecordType);

                            if (resolvedDnsList != null && resolvedDnsList.Count != 0 && statusCode == ReturnCode.NoError)
                            {
                                response.AnswerRecords.AddRange(resolvedDnsList);

                                if (DnsSettings.DnsCacheEnable)
                                {
                                    BackgroundWriteCache(
                                        new CacheItem($"{dnsQuestion.Name}{dnsQuestion.RecordType}", resolvedDnsList),
                                        resolvedDnsList[0].TimeToLive);
                                }
                            }
                            else if (statusCode == ReturnCode.ServerFailure)
                            {
                                response.AnswerRecords = new DnsClient(DnsSettings.SecondDnsIp, 1000)
                                                         .Resolve(dnsQuestion.Name, dnsQuestion.RecordType).AnswerRecords;
                                BackgroundLog($"| -- SecondDns : {DnsSettings.SecondDnsIp}");
                            }
                            else
                            {
                                response.ReturnCode = statusCode;
                            }
                        }
                        catch (Exception ex)
                        {
                            response.ReturnCode = ReturnCode.ServerFailure;
                            BackgroundLog(@"| " + ex);
                        }
                    }
                }
            }
            e.Response = response;
        }
Example #31
0
        public async Task <Tuple <IEnumerable <Cipher>, IEnumerable <Cipher>, IEnumerable <Cipher> > > GetAllAsync(
            string uriString)
        {
            if (string.IsNullOrWhiteSpace(uriString))
            {
                return(null);
            }

            string domainName = null;
            var    mobileApp  = UriIsMobileApp(uriString);

            if (!mobileApp &&
                (!Uri.TryCreate(uriString, UriKind.Absolute, out Uri uri) ||
                 !DomainName.TryParseBaseDomain(uri.Host, out domainName)))
            {
                return(null);
            }

            var mobileAppInfo         = InfoFromMobileAppUri(uriString);
            var mobileAppWebUriString = mobileAppInfo?.Item1;
            var mobileAppSearchTerms  = mobileAppInfo?.Item2;
            var eqDomains             = (await _settingsService.GetEquivalentDomainsAsync()).Select(d => d.ToArray());
            var matchingDomains       = new List <string>();
            var matchingFuzzyDomains  = new List <string>();

            foreach (var eqDomain in eqDomains)
            {
                if (mobileApp)
                {
                    if (Array.IndexOf(eqDomain, uriString) >= 0)
                    {
                        matchingDomains.AddRange(eqDomain.Select(d => d).ToList());
                    }
                    else if (mobileAppWebUriString != null && Array.IndexOf(eqDomain, mobileAppWebUriString) >= 0)
                    {
                        matchingFuzzyDomains.AddRange(eqDomain.Select(d => d).ToList());
                    }
                }
                else if (Array.IndexOf(eqDomain, domainName) >= 0)
                {
                    matchingDomains.AddRange(eqDomain.Select(d => d).ToList());
                }
            }

            if (!matchingDomains.Any())
            {
                matchingDomains.Add(mobileApp ? uriString : domainName);
            }

            if (mobileApp && mobileAppWebUriString != null &&
                !matchingFuzzyDomains.Any() && !matchingDomains.Contains(mobileAppWebUriString))
            {
                matchingFuzzyDomains.Add(mobileAppWebUriString);
            }

            var matchingDomainsArray      = matchingDomains.ToArray();
            var matchingFuzzyDomainsArray = matchingFuzzyDomains.ToArray();
            var matchingLogins            = new List <Cipher>();
            var matchingFuzzyLogins       = new List <Cipher>();
            var others  = new List <Cipher>();
            var ciphers = await GetAllAsync();

            foreach (var cipher in ciphers)
            {
                if (cipher.Type != Enums.CipherType.Login)
                {
                    others.Add(cipher);
                    continue;
                }

                if (cipher.Login?.Uris == null || !cipher.Login.Uris.Any())
                {
                    continue;
                }

                foreach (var u in cipher.Login.Uris)
                {
                    var loginUriString = u.Uri?.Decrypt(cipher.OrganizationId);
                    if (string.IsNullOrWhiteSpace(loginUriString))
                    {
                        break;
                    }

                    var match = false;
                    switch (u.Match)
                    {
                    case null:
                    case Enums.UriMatchType.Domain:
                        match = CheckDefaultUriMatch(cipher, loginUriString, matchingLogins, matchingFuzzyLogins,
                                                     matchingDomainsArray, matchingFuzzyDomainsArray, mobileApp, mobileAppSearchTerms);
                        break;

                    case Enums.UriMatchType.Host:
                        var urlHost = Helpers.GetUrlHost(uriString);
                        match = urlHost != null && urlHost == Helpers.GetUrlHost(loginUriString);
                        if (match)
                        {
                            AddMatchingLogin(cipher, matchingLogins, matchingFuzzyLogins);
                        }
                        break;

                    case Enums.UriMatchType.Exact:
                        match = uriString == loginUriString;
                        if (match)
                        {
                            AddMatchingLogin(cipher, matchingLogins, matchingFuzzyLogins);
                        }
                        break;

                    case Enums.UriMatchType.StartsWith:
                        match = uriString.StartsWith(loginUriString);
                        if (match)
                        {
                            AddMatchingLogin(cipher, matchingLogins, matchingFuzzyLogins);
                        }
                        break;

                    case Enums.UriMatchType.RegularExpression:
                        var regex = new Regex(loginUriString, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1));
                        match = regex.IsMatch(uriString);
                        if (match)
                        {
                            AddMatchingLogin(cipher, matchingLogins, matchingFuzzyLogins);
                        }
                        break;

                    case Enums.UriMatchType.Never:
                    default:
                        break;
                    }

                    if (match)
                    {
                        break;
                    }
                }
            }

            return(new Tuple <IEnumerable <Cipher>, IEnumerable <Cipher>, IEnumerable <Cipher> >(
                       matchingLogins, matchingFuzzyLogins, others));
        }
Example #32
0
        /// <summary>
        ///   Resolves specified records as an asynchronous operation.
        /// </summary>
        /// <typeparam name="T"> Type of records, that should be returned </typeparam>
        /// <param name="name"> Domain, that should be queried </param>
        /// <param name="recordType"> Type the should be queried </param>
        /// <param name="recordClass"> Class the should be queried </param>
        /// <param name="token"> The token to monitor cancellation requests </param>
        /// <returns> A list of matching <see cref="DnsRecordBase">records</see> </returns>
        public async Task <DnsSecResult <T> > ResolveSecureAsync <T>(DomainName name, RecordType recordType = RecordType.A, RecordClass recordClass = RecordClass.INet, CancellationToken token = default(CancellationToken))
            where T : DnsRecordBase
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name), "Name must be provided");
            }

            DnsCacheRecordList <T> cacheResult;

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

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

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

            DnsSecValidationResult validationResult;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return(new DnsSecResult <T>(res, validationResult));
        }
 public void CreateReturnsNoSpecimenWhenEmailAddressLocalPartIsInvalidForMailAddress()
 {
     // Fixture setup
     var localPart = new EmailAddressLocalPart("@Invalid@");
     var anonymousDomainName = new DomainName(Guid.NewGuid().ToString());
     var request = typeof(MailAddress);
     var context = new DelegatingSpecimenContext()
     {
         OnResolve = r =>
         {
             Assert.True(typeof(EmailAddressLocalPart).Equals(r) || typeof(DomainName).Equals(r));
             if (typeof(EmailAddressLocalPart).Equals(r))
             {
                 return localPart;
             }
             else
             {
                 return anonymousDomainName;
             }
         }
     };
     var sut = new MailAddressGenerator();
     // Exercise system
     var result = sut.Create(request, context);
     // Verify outcome
     var expectedResult = new NoSpecimen(request);
     Assert.Equal(expectedResult, result);
     // Teardown
 }
 /// <summary>
 ///   Creates a new instance of the Eui48Record class
 /// </summary>
 /// <param name="name"> Domain name of the host </param>
 /// <param name="timeToLive"> Seconds the record should be cached at most </param>
 /// <param name="address"> The EUI48 address</param>
 public Eui64Record(DomainName name, int timeToLive, byte[] address)
     : base(name, RecordType.Eui64, RecordClass.INet, timeToLive)
 {
     Address = address ?? new byte[8];
 }
        public void CreateWithMailAddressRequestReturnsNoSpecimenWhenContextReturnsNullLocalPart()
        {
            // Fixture setup
            var request = typeof(MailAddress);
            var anonymousDomainName = new DomainName(Guid.NewGuid().ToString());

            var context = new DelegatingSpecimenContext()
            {
                OnResolve = r =>
                {
                    Assert.True(typeof(EmailAddressLocalPart).Equals(r) || typeof(DomainName).Equals(r));
                    return typeof(DomainName).Equals(r) ? anonymousDomainName : null;
                }
            };
            var sut = new MailAddressGenerator();
            // Exercise system
            var result = sut.Create(request, context);
            // Verify outcome
            var expectedResult = new NoSpecimen(request);
            Assert.Equal(expectedResult, result);
            // Teardown
        }
Example #36
0
 /// <inheritdoc />
 public override void ReadData(WireReader reader, int length)
 {
     Subtype = reader.ReadUInt16();
     Target  = reader.ReadDomainName();
 }
Example #37
0
 public void GetHashCodeReturnsCorrectResult()
 {
     // Fixture setup
     var domainName = Guid.NewGuid().ToString();
     var sut = new DomainName(domainName);
     // Exercise system
     int result = sut.GetHashCode();
     // Verify outcome
     int expectedHashCode = domainName.GetHashCode();
     Assert.Equal(expectedHashCode, result);
     // Teardown
 }
Example #38
0
 public void RemoveDomain(DomainName domain)
 {
     if (this.Domains.Contains(domain))
         domains.Remove(domain);
 }
 public SiteDomainIsAlreadyTakenFailure(DomainName domain, Site site)
     : base(string.Format("Failed to create site [{1}] because the domain name [{0}] is already taken by another site.", site, domain))
 {
 }
Example #40
0
        private async Task <DnsSecResult <T> > ResolveAsyncInternal <T>(DomainName name, RecordType recordType, RecordClass recordClass, State state, CancellationToken token)
            where T : DnsRecordBase
        {
            DnsCacheRecordList <T> cachedResults;

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

            DnsCacheRecordList <CNameRecord> cachedCNames;

            if (_cache.TryGetRecords(name, RecordType.CName, recordClass, out cachedCNames))
            {
                var cNameResult = await ResolveAsyncInternal <T>(cachedCNames.First().CanonicalName, recordType, recordClass, state, token);

                return(new DnsSecResult <T>(cNameResult.Records, cachedCNames.ValidationResult == cNameResult.ValidationResult ? cachedCNames.ValidationResult : DnsSecValidationResult.Unsigned));
            }

            DnsMessage msg = await ResolveMessageAsync(name, recordType, recordClass, state, token);

            // check for cname
            List <DnsRecordBase> cNameRecords = msg.AnswerRecords.Where(x => (x.RecordType == RecordType.CName) && (x.RecordClass == recordClass) && x.Name.Equals(name)).ToList();

            if (cNameRecords.Count > 0)
            {
                DnsSecValidationResult cNameValidationResult = await _validator.ValidateAsync(name, RecordType.CName, recordClass, msg, cNameRecords, state, token);

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

                _cache.Add(name, RecordType.CName, recordClass, cNameRecords, cNameValidationResult, cNameRecords.Min(x => x.TimeToLive));

                DomainName canonicalName = ((CNameRecord)cNameRecords.First()).CanonicalName;

                List <DnsRecordBase> matchingAdditionalRecords = msg.AnswerRecords.Where(x => (x.RecordType == recordType) && (x.RecordClass == recordClass) && x.Name.Equals(canonicalName)).ToList();
                if (matchingAdditionalRecords.Count > 0)
                {
                    DnsSecValidationResult matchingValidationResult = await _validator.ValidateAsync(canonicalName, recordType, recordClass, msg, matchingAdditionalRecords, state, token);

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

                    DnsSecValidationResult validationResult = cNameValidationResult == matchingValidationResult ? cNameValidationResult : DnsSecValidationResult.Unsigned;
                    _cache.Add(canonicalName, recordType, recordClass, matchingAdditionalRecords, validationResult, matchingAdditionalRecords.Min(x => x.TimeToLive));

                    return(new DnsSecResult <T>(matchingAdditionalRecords.OfType <T>().ToList(), validationResult));
                }

                var cNameResults = await ResolveAsyncInternal <T>(canonicalName, recordType, recordClass, state, token);

                return(new DnsSecResult <T>(cNameResults.Records, cNameValidationResult == cNameResults.ValidationResult ? cNameValidationResult : DnsSecValidationResult.Unsigned));
            }

            // check for "normal" answer
            List <DnsRecordBase> answerRecords = msg.AnswerRecords.Where(x => (x.RecordType == recordType) && (x.RecordClass == recordClass) && x.Name.Equals(name)).ToList();

            if (answerRecords.Count > 0)
            {
                DnsSecValidationResult validationResult = await _validator.ValidateAsync(name, recordType, recordClass, msg, answerRecords, state, token);

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

                _cache.Add(name, recordType, recordClass, answerRecords, validationResult, answerRecords.Min(x => x.TimeToLive));
                return(new DnsSecResult <T>(answerRecords.OfType <T>().ToList(), validationResult));
            }

            // check for negative answer
            SoaRecord soaRecord = msg.AuthorityRecords
                                  .Where(x =>
                                         (x.RecordType == RecordType.Soa) &&
                                         (name.Equals(x.Name) || name.IsSubDomainOf(x.Name)))
                                  .OfType <SoaRecord>()
                                  .FirstOrDefault();

            if (soaRecord != null)
            {
                DnsSecValidationResult validationResult = await _validator.ValidateAsync(name, recordType, recordClass, msg, answerRecords, state, token);

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

                _cache.Add(name, recordType, recordClass, new List <DnsRecordBase>(), validationResult, soaRecord.NegativeCachingTTL);
                return(new DnsSecResult <T>(new List <T>(), validationResult));
            }

            // authoritive response does not contain answer
            throw new Exception("Could not resolve " + name);
        }
Example #41
0
        private async Task <DnsSecValidationResult> ValidateRrSigAsync <TRecord>(DomainName name, RecordType recordType, RecordClass recordClass, List <TRecord> resultRecords, List <RrSigRecord> rrSigRecords, DomainName zoneApex, DnsMessageBase msg, TState state, CancellationToken token)
            where TRecord : DnsRecordBase
        {
            DnsSecValidationResult res = DnsSecValidationResult.Bogus;

            foreach (var record in rrSigRecords.Where(x => x.Name.Equals(name) && (x.TypeCovered == recordType)))
            {
                res = await VerifyAsync(record, resultRecords, recordClass, state, token).ConfigureAwait(false);

                if (res == DnsSecValidationResult.Signed)
                {
                    if ((record.Labels == name.LabelCount) ||
                        ((name.Labels[0] == "*") && (record.Labels == name.LabelCount - 1)))
                    {
                        return(DnsSecValidationResult.Signed);
                    }

                    if (await ValidateNonExistenceAsync(name, recordType, recordClass, rrSigRecords, DomainName.Asterisk + record.Name.GetParentName(record.Name.LabelCount - record.Labels), zoneApex, msg, state, token).ConfigureAwait(false) == DnsSecValidationResult.Signed)
                    {
                        return(DnsSecValidationResult.Signed);
                    }
                }
            }

            return(res);
        }
Example #42
0
 Task <DnsMessage> IInternalDnsSecResolver <State> .ResolveMessageAsync(DomainName name, RecordType recordType, RecordClass recordClass, State state, CancellationToken token)
 {
     return(ResolveMessageAsync(name, recordType, recordClass, state, token));
 }
Example #43
0
 /// <inheritdoc />
 public override void ReadData(PresentationReader reader)
 {
     Subtype = reader.ReadUInt16();
     Target  = reader.ReadDomainName();
 }
Example #44
0
 internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
 {
     ParseUnknownRecordData(stringRepresentation);
 }
Example #45
0
        private async Task <DnsMessage> ResolveMessageAsync(DomainName name, RecordType recordType, RecordClass recordClass, State state, CancellationToken token)
        {
            for (; state.QueryCount <= MaximumReferalCount; state.QueryCount++)
            {
                DnsMessage msg = await new DnsClient(GetBestNameservers(recordType == RecordType.Ds ? name.GetParentName() : name), QueryTimeout)
                {
                    IsResponseValidationEnabled = IsResponseValidationEnabled,
                    Is0x20ValidationEnabled     = Is0x20ValidationEnabled
                }.ResolveAsync(name, recordType, recordClass, new DnsQueryOptions()
                {
                    IsRecursionDesired = false,
                    IsEDnsEnabled      = true,
                    IsDnsSecOk         = true,
                    IsCheckingDisabled = true
                }, token);

                if ((msg != null) && ((msg.ReturnCode == ReturnCode.NoError) || (msg.ReturnCode == ReturnCode.NxDomain)))
                {
                    if (msg.IsAuthoritiveAnswer)
                    {
                        return(msg);
                    }

                    List <NsRecord> referalRecords = msg.AuthorityRecords
                                                     .Where(x =>
                                                            (x.RecordType == RecordType.Ns) &&
                                                            (name.Equals(x.Name) || name.IsSubDomainOf(x.Name)))
                                                     .OfType <NsRecord>()
                                                     .ToList();

                    if (referalRecords.Count > 0)
                    {
                        if (referalRecords.GroupBy(x => x.Name).Count() == 1)
                        {
                            var newServers = referalRecords.Join(msg.AdditionalRecords.OfType <AddressRecordBase>(), x => x.NameServer, x => x.Name, (x, y) => new { y.Address, TimeToLive = Math.Min(x.TimeToLive, y.TimeToLive) }).ToList();

                            if (newServers.Count > 0)
                            {
                                DomainName zone = referalRecords.First().Name;

                                foreach (var newServer in newServers)
                                {
                                    _nameserverCache.Add(zone, newServer.Address, newServer.TimeToLive);
                                }

                                continue;
                            }
                            else
                            {
                                NsRecord firstReferal = referalRecords.First();

                                var newLookedUpServers = await ResolveHostWithTtlAsync(firstReferal.NameServer, state, token);

                                foreach (var newServer in newLookedUpServers)
                                {
                                    _nameserverCache.Add(firstReferal.Name, newServer.Item1, Math.Min(firstReferal.TimeToLive, newServer.Item2));
                                }

                                if (newLookedUpServers.Count > 0)
                                {
                                    continue;
                                }
                            }
                        }
                    }

                    // Response of best known server is not authoritive and has no referrals --> No chance to get a result
                    throw new Exception("Could not resolve " + name);
                }
            }

            // query limit reached without authoritive answer
            throw new Exception("Could not resolve " + name);
        }
Example #46
0
 public void AddDomain(DomainName domain)
 {
     if (!this.Domains.Contains(domain))
         domains.Add(domain);
 }