Ejemplo n.º 1
0
        protected async Task <MetadataTOCPayload> DeserializeAndValidateToc(string toc)
        {
            if (string.IsNullOrWhiteSpace(toc))
            {
                throw new ArgumentNullException(nameof(toc));
            }

            var jwtParts = toc.Split('.');

            if (jwtParts.Length != 3)
            {
                throw new ArgumentException("The JWT does not have the 3 expected components");
            }

            var tocHeaderString = jwtParts.First();
            var tocHeader       = JObject.Parse(Encoding.UTF8.GetString(Base64Url.Decode(tocHeaderString)));

            _tocAlg = tocHeader["alg"]?.Value <string>();

            if (_tocAlg == null)
            {
                throw new ArgumentNullException("No alg value was present in the TOC header.");
            }

            var x5cArray = tocHeader["x5c"] as JArray;

            if (x5cArray == null)
            {
                throw new Exception("No x5c array was present in the TOC header.");
            }

            var keyStrings = x5cArray.Values <string>().ToList();

            if (keyStrings.Count == 0)
            {
                throw new ArgumentException("No keys were present in the TOC header.");
            }

            var rootCert      = GetX509Certificate(ROOT_CERT);
            var tocCerts      = keyStrings.Select(o => GetX509Certificate(o)).ToArray();
            var tocPublicKeys = keyStrings.Select(o => GetECDsaPublicKey(o)).ToArray();

            var certChain = new X509Chain();

            certChain.ChainPolicy.ExtraStore.Add(rootCert);
            certChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

            var validationParameters = new TokenValidationParameters
            {
                ValidateIssuer           = false,
                ValidateAudience         = false,
                ValidateLifetime         = false,
                ValidateIssuerSigningKey = true,
                IssuerSigningKeys        = tocPublicKeys,
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            tokenHandler.ValidateToken(
                toc,
                validationParameters,
                out var validatedToken);

            if (tocCerts.Length > 1)
            {
                certChain.ChainPolicy.ExtraStore.AddRange(tocCerts.Skip(1).ToArray());
            }

            var certChainIsValid = certChain.Build(tocCerts.First());

            // if the root is trusted in the context we are running in, valid should be true here
            if (!certChainIsValid)
            {
                foreach (var element in certChain.ChainElements)
                {
                    if (element.Certificate.Issuer != element.Certificate.Subject)
                    {
                        var cdp     = CryptoUtils.CDPFromCertificateExts(element.Certificate.Extensions);
                        var crlFile = await DownloadDataAsync(cdp);

                        if (true == CryptoUtils.IsCertInCRL(crlFile, element.Certificate))
                        {
                            throw new VerificationException(string.Format("Cert {0} found in CRL {1}", element.Certificate.Subject, cdp));
                        }
                    }
                }

                // otherwise we have to manually validate that the root in the chain we are testing is the root we downloaded
                if (rootCert.Thumbprint == certChain.ChainElements[certChain.ChainElements.Count - 1].Certificate.Thumbprint &&
                    // and that the number of elements in the chain accounts for what was in x5c plus the root we added
                    certChain.ChainElements.Count == (keyStrings.Count + 1) &&
                    // and that the root cert has exactly one status listed against it
                    certChain.ChainElements[certChain.ChainElements.Count - 1].ChainElementStatus.Length == 1 &&
                    // and that that status is a status of exactly UntrustedRoot
                    certChain.ChainElements[certChain.ChainElements.Count - 1].ChainElementStatus[0].Status == X509ChainStatusFlags.UntrustedRoot)
                {
                    // if we are good so far, that is a good sign
                    certChainIsValid = true;
                    for (var i = 0; i < certChain.ChainElements.Count - 1; i++)
                    {
                        // check each non-root cert to verify zero status listed against it, otherwise, invalidate chain
                        if (0 != certChain.ChainElements[i].ChainElementStatus.Length)
                        {
                            certChainIsValid = false;
                        }
                    }
                }
            }

            if (!certChainIsValid)
            {
                throw new VerificationException("Failed to validate cert chain while parsing TOC");
            }

            var tocPayload = ((JwtSecurityToken)validatedToken).Payload.SerializeToJson();

            return(Newtonsoft.Json.JsonConvert.DeserializeObject <MetadataTOCPayload>(tocPayload));
        }
Ejemplo n.º 2
0
        protected async Task <MetadataTOCPayload> DeserializeAndValidateToc(string toc)
        {
            var jwtToken = new JwtSecurityToken(toc);

            _tocAlg = jwtToken.Header["alg"] as string;
            var keys = (jwtToken.Header["x5c"] as JArray)
                       .Values <string>()
                       .Select(x => new ECDsaSecurityKey(
                                   (ECDsa)(new X509Certificate2(Convert.FromBase64String(x)).GetECDsaPublicKey())))
                       .ToArray();

            var root = new X509Certificate2(Convert.FromBase64String(ROOT_CERT));

            var chain = new X509Chain();

            chain.ChainPolicy.ExtraStore.Add(root);
            chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

            var validationParameters = new TokenValidationParameters
            {
                ValidateIssuer           = false,
                ValidateAudience         = false,
                ValidateLifetime         = false,
                ValidateIssuerSigningKey = true,
                IssuerSigningKeys        = keys,
            };
            var tokenHandler = new JwtSecurityTokenHandler();

            tokenHandler.ValidateToken(
                toc,
                validationParameters,
                out var validatedToken);
            var payload = ((JwtSecurityToken)validatedToken).Payload.SerializeToJson();

            chain.ChainPolicy.ExtraStore.Add(new X509Certificate2(Convert.FromBase64String((jwtToken.Header["x5c"] as JArray).Values <string>().Last())));
            var valid = chain.Build(new X509Certificate2(Convert.FromBase64String((jwtToken.Header["x5c"] as JArray).Values <string>().First())));

            // if the root is trusted in the context we are running in, valid should be true here
            if (false == valid)
            {
                foreach (var element in chain.ChainElements)
                {
                    if (element.Certificate.Issuer != element.Certificate.Subject)
                    {
                        var cdp     = CryptoUtils.CDPFromCertificateExts(element.Certificate.Extensions);
                        var crlFile = await DownloadDataAsync(cdp);

                        if (true == CryptoUtils.IsCertInCRL(crlFile, element.Certificate))
                        {
                            throw new VerificationException(string.Format("Cert {0} found in CRL {1}", element.Certificate.Subject, cdp));
                        }
                    }
                }

                // otherwise we have to manually validate that the root in the chain we are testing is the root we downloaded
                if (root.Thumbprint == chain.ChainElements[chain.ChainElements.Count - 1].Certificate.Thumbprint &&
                    // and that the number of elements in the chain accounts for what was in x5c plus the root we added
                    chain.ChainElements.Count == ((jwtToken.Header["x5c"] as JArray).Count + 1) &&
                    // and that the root cert has exactly one status listed against it
                    chain.ChainElements[chain.ChainElements.Count - 1].ChainElementStatus.Length == 1 &&
                    // and that that status is a status of exactly UntrustedRoot
                    chain.ChainElements[chain.ChainElements.Count - 1].ChainElementStatus[0].Status == X509ChainStatusFlags.UntrustedRoot)
                {
                    // if we are good so far, that is a good sign
                    valid = true;
                    for (var i = 0; i < chain.ChainElements.Count - 1; i++)
                    {
                        // check each non-root cert to verify zero status listed against it, otherwise, invalidate chain
                        if (0 != chain.ChainElements[i].ChainElementStatus.Length)
                        {
                            valid = false;
                        }
                    }
                }
            }
            if (false == valid)
            {
                throw new VerificationException("Failed to validate cert chain while parsing TOC");
            }
            return(JsonConvert.DeserializeObject <MetadataTOCPayload>(payload));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// DeserializeAndValidateBlob method implementation
        /// </summary>
        protected async Task <MetadataBLOBPayload> DeserializeAndValidateBlob(string rawBLOBJwt)
        {
            if (string.IsNullOrWhiteSpace(rawBLOBJwt))
            {
                throw new ArgumentNullException(nameof(rawBLOBJwt));
            }

            var jwtParts = rawBLOBJwt.Split('.');

            if (jwtParts.Length != 3)
            {
                throw new ArgumentException("The JWT does not have the 3 expected components");
            }

            var blobHeader  = jwtParts.First();
            var tokenHeader = JObject.Parse(System.Text.Encoding.UTF8.GetString(Base64Url.Decode(blobHeader)));

            var blobAlg = tokenHeader["alg"]?.Value <string>();

            if (blobAlg == null)
            {
                throw new ArgumentNullException("No alg value was present in the BLOB header.");
            }

            var x5cArray = tokenHeader["x5c"] as JArray;

            if (x5cArray == null)
            {
                throw new ArgumentException("No x5c array was present in the BLOB header.");
            }

            var rootCert         = GetX509Certificate(ROOT_CERT);
            var blobCertStrings  = x5cArray.Values <string>().ToList();
            var blobCertificates = new List <X509Certificate2>();
            var blobPublicKeys   = new List <SecurityKey>();

            foreach (var certString in blobCertStrings)
            {
                var cert = GetX509Certificate(certString);
                blobCertificates.Add(cert);

                var ecdsaPublicKey = cert.GetECDsaPublicKey();
                if (ecdsaPublicKey != null)
                {
                    blobPublicKeys.Add(new ECDsaSecurityKey(ecdsaPublicKey));
                }

                var rsa = cert.GetRSAPublicKey();
                if (rsa != null)
                {
                    blobPublicKeys.Add(new RsaSecurityKey(rsa));
                }
            }

            var certChain = new X509Chain();

            certChain.ChainPolicy.ExtraStore.Add(rootCert);
            certChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

            var validationParameters = new TokenValidationParameters
            {
                ValidateIssuer           = false,
                ValidateAudience         = false,
                ValidateLifetime         = false,
                ValidateIssuerSigningKey = true,
                IssuerSigningKeys        = blobPublicKeys,
            };

            var tokenHandler = new JwtSecurityTokenHandler()
            {
                // 250k isn't enough bytes for conformance test tool
                // https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/1097
                MaximumTokenSizeInBytes = rawBLOBJwt.Length
            };

            tokenHandler.ValidateToken(
                rawBLOBJwt,
                validationParameters,
                out var validatedToken);

            if (blobCertificates.Count > 1)
            {
                certChain.ChainPolicy.ExtraStore.AddRange(blobCertificates.Skip(1).ToArray());
            }

            var certChainIsValid = certChain.Build(blobCertificates.First());

            // if the root is trusted in the context we are running in, valid should be true here
            if (!certChainIsValid)
            {
                foreach (var element in certChain.ChainElements)
                {
                    if (element.Certificate.Issuer != element.Certificate.Subject)
                    {
                        var cdp     = CryptoUtils.CDPFromCertificateExts(element.Certificate.Extensions);
                        var crlFile = await DownloadDataAsync(cdp);

                        if (true == CryptoUtils.IsCertInCRL(crlFile, element.Certificate))
                        {
                            throw new VerificationException(string.Format("Cert {0} found in CRL {1}", element.Certificate.Subject, cdp));
                        }
                    }
                }

                // otherwise we have to manually validate that the root in the chain we are testing is the root we downloaded
                if (rootCert.Thumbprint == certChain.ChainElements[certChain.ChainElements.Count - 1].Certificate.Thumbprint &&
                    // and that the number of elements in the chain accounts for what was in x5c plus the root we added
                    certChain.ChainElements.Count == (blobCertStrings.Count + 1) &&
                    // and that the root cert has exactly one status listed against it
                    certChain.ChainElements[certChain.ChainElements.Count - 1].ChainElementStatus.Length == 1 &&
                    // and that that status is a status of exactly UntrustedRoot
                    certChain.ChainElements[certChain.ChainElements.Count - 1].ChainElementStatus[0].Status == X509ChainStatusFlags.UntrustedRoot)
                {
                    // if we are good so far, that is a good sign
                    certChainIsValid = true;
                    for (var i = 0; i < certChain.ChainElements.Count - 1; i++)
                    {
                        // check each non-root cert to verify zero status listed against it, otherwise, invalidate chain
                        if (0 != certChain.ChainElements[i].ChainElementStatus.Length)
                        {
                            certChainIsValid = false;
                        }
                    }
                }
            }

            if (!certChainIsValid)
            {
                throw new VerificationException("Failed to validate cert chain while parsing BLOB");
            }

            var blobPayload = ((JwtSecurityToken)validatedToken).Payload.SerializeToJson();

            var blob = Newtonsoft.Json.JsonConvert.DeserializeObject <MetadataBLOBPayload>(blobPayload);

            blob.JwtAlg = blobAlg;
            return(blob);
        }