Example #1
0
 public void ReadFrom(XmlDictionaryReader reader, long maxBufferSize)
 {
     this.ValidateReadState();
     reader.MoveToStartElement(this.OpeningElementName, EncryptedType.NamespaceUri);
     this.encoding = reader.GetAttribute(EncryptedType.EncodingAttribute, (XmlDictionaryString)null);
     this.id       = reader.GetAttribute(System.IdentityModel.XD.XmlEncryptionDictionary.Id, (XmlDictionaryString)null) ?? SecurityUniqueId.Create().Value;
     this.wsuId    = reader.GetAttribute(System.IdentityModel.XD.XmlEncryptionDictionary.Id, System.IdentityModel.XD.UtilityDictionary.Namespace) ?? SecurityUniqueId.Create().Value;
     this.mimeType = reader.GetAttribute(EncryptedType.MimeTypeAttribute, (XmlDictionaryString)null);
     this.type     = reader.GetAttribute(EncryptedType.TypeAttribute, (XmlDictionaryString)null);
     this.ReadAdditionalAttributes(reader);
     reader.Read();
     if (reader.IsStartElement(EncryptedType.EncryptionMethodElement.ElementName, EncryptedType.NamespaceUri))
     {
         this.encryptionMethod.ReadFrom(reader);
     }
     if (this.tokenSerializer.CanReadKeyIdentifier((XmlReader)reader))
     {
         XmlElement          xmlElement = (XmlElement)null;
         XmlDictionaryReader dictionaryReader;
         if (this.ShouldReadXmlReferenceKeyInfoClause)
         {
             xmlElement       = new XmlDocument().ReadNode((XmlReader)reader) as XmlElement;
             dictionaryReader = XmlDictionaryReader.CreateDictionaryReader((XmlReader) new XmlNodeReader((XmlNode)xmlElement));
         }
         else
         {
             dictionaryReader = reader;
         }
         try
         {
             this.KeyIdentifier = this.tokenSerializer.ReadKeyIdentifier((XmlReader)dictionaryReader);
         }
         catch (Exception ex)
         {
             if (Fx.IsFatal(ex) || !this.ShouldReadXmlReferenceKeyInfoClause)
             {
                 throw;
             }
             else
             {
                 this.keyIdentifier = this.ReadGenericXmlSecurityKeyIdentifier(XmlDictionaryReader.CreateDictionaryReader((XmlReader) new XmlNodeReader((XmlNode)xmlElement)), ex);
             }
         }
     }
     reader.ReadStartElement(EncryptedType.CipherDataElementName, EncryptedType.NamespaceUri);
     reader.ReadStartElement(EncryptedType.CipherValueElementName, EncryptedType.NamespaceUri);
     if (maxBufferSize == 0L)
     {
         this.ReadCipherData(reader);
     }
     else
     {
         this.ReadCipherData(reader, maxBufferSize);
     }
     reader.ReadEndElement();
     reader.ReadEndElement();
     this.ReadAdditionalElements(reader);
     reader.ReadEndElement();
     this.State = EncryptedType.EncryptionState.Read;
 }
        /// <summary>
        /// Finds a named collection of <see cref="SecurityKey"/>(s) that match the <see cref="SecurityKeyIdentifier"/> and returns a <see cref="NamedKeySecurityToken"/> that contains the <see cref="SecurityKey"/>(s).
        /// </summary>
        /// <param name="keyIdentifier">The <see cref="SecurityKeyIdentifier"/> to resolve to a <see cref="SecurityToken"/></param>
        /// <param name="token">The resolved <see cref="SecurityToken"/>.</param>
        /// <remarks>
        /// <para>
        /// A <see cref="SecurityKeyIdentifier"/> can contain multiple <see cref="SecurityKeyIdentifierClause"/>(s). This method will return the named collection that matches the first <see cref="SecurityKeyIdentifierClause"/>
        /// </para>
        /// <para>
        /// If there is no match, then <see cref="IssuerTokenResolver"/> and 'base' are called in order.
        /// </para>
        /// </remarks>
        /// <returns>
        /// true is the keyIdentifier is resolved, false otherwise.
        /// </returns>
        protected override bool TryResolveTokenCore(SecurityKeyIdentifier keyIdentifier, out SecurityToken token)
        {
            if (keyIdentifier == null)
            {
                throw new ArgumentNullException("keyIdentifier");
            }

            token = null;
            foreach (SecurityKeyIdentifierClause clause in keyIdentifier)
            {
                if (null == clause)
                {
                    continue;
                }

                NamedKeySecurityKeyIdentifierClause namedKeyIdentifierClause = clause as NamedKeySecurityKeyIdentifierClause;
                if (namedKeyIdentifierClause != null)
                {
                    IList <SecurityKey> resolvedKeys = null;
                    if (this.keys.TryGetValue(namedKeyIdentifierClause.Name, out resolvedKeys))
                    {
                        token = new NamedKeySecurityToken(namedKeyIdentifierClause.Name, namedKeyIdentifierClause.Id, resolvedKeys);
                        return(true);
                    }
                }
            }

            if (IssuerTokenResolver != null && IssuerTokenResolver.TryResolveToken(keyIdentifier, out token))
            {
                return(true);
            }

            return(base.TryResolveTokenCore(keyIdentifier, out token));
        }
Example #3
0
        private SecurityKeyIdentifier ReadGenericXmlSecurityKeyIdentifier(XmlDictionaryReader localReader, Exception previousException)
        {
            if (!localReader.IsStartElement(XD.XmlSignatureDictionary.KeyInfo, XD.XmlSignatureDictionary.Namespace))
            {
                return(null);
            }

            localReader.ReadStartElement(XD.XmlSignatureDictionary.KeyInfo, XD.XmlSignatureDictionary.Namespace);
            SecurityKeyIdentifier keyIdentifier = new SecurityKeyIdentifier();

            if (localReader.IsStartElement())
            {
                SecurityKeyIdentifierClause clause = null;
                string      strId = localReader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace);
                XmlDocument doc   = new XmlDocument();
                XmlElement  keyIdentifierReferenceXml = (doc.ReadNode(localReader) as XmlElement);
                clause = new GenericXmlSecurityKeyIdentifierClause(keyIdentifierReferenceXml);
                if (!string.IsNullOrEmpty(strId))
                {
                    clause.Id = strId;
                }
                keyIdentifier.Add(clause);
            }

            if (keyIdentifier.Count == 0)
            {
                throw previousException;
            }

            localReader.ReadEndElement();
            return(keyIdentifier);
        }
        protected override void StartPrimarySignatureCore(SecurityToken token, SecurityKeyIdentifier keyIdentifier, MessagePartSpecification signatureParts, bool generateTargettableSignature)
        {
            string str3;
            XmlDictionaryString    str4;
            SecurityAlgorithmSuite algorithmSuite   = base.AlgorithmSuite;
            string defaultCanonicalizationAlgorithm = algorithmSuite.DefaultCanonicalizationAlgorithm;
            XmlDictionaryString defaultCanonicalizationAlgorithmDictionaryString = algorithmSuite.DefaultCanonicalizationAlgorithmDictionaryString;

            if (defaultCanonicalizationAlgorithm != "http://www.w3.org/2001/10/xml-exc-c14n#")
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("UnsupportedCanonicalizationAlgorithm", new object[] { algorithmSuite.DefaultCanonicalizationAlgorithm })));
            }
            algorithmSuite.GetSignatureAlgorithmAndKey(token, out str3, out this.signatureKey, out str4);
            string defaultDigestAlgorithm = algorithmSuite.DefaultDigestAlgorithm;
            XmlDictionaryString defaultDigestAlgorithmDictionaryString = algorithmSuite.DefaultDigestAlgorithmDictionaryString;

            this.signedInfo = new PreDigestedSignedInfo(ServiceModelDictionaryManager.Instance, defaultCanonicalizationAlgorithm, defaultCanonicalizationAlgorithmDictionaryString, defaultDigestAlgorithm, defaultDigestAlgorithmDictionaryString, str3, str4);
            this.signedXml  = new SignedXml(this.signedInfo, ServiceModelDictionaryManager.Instance, base.StandardsManager.SecurityTokenSerializer);
            if (keyIdentifier != null)
            {
                this.signedXml.Signature.KeyIdentifier = keyIdentifier;
            }
            if (generateTargettableSignature)
            {
                this.signedXml.Id = base.GenerateId();
            }
            this.effectiveSignatureParts = signatureParts;
            this.hashStream = this.signedInfo.ResourcePool.TakeHashStream(defaultDigestAlgorithm);
        }
        protected override SecurityKeyIdentifier ReadKeyIdentifierCore(XmlReader reader)
        {
            var result = new SecurityKeyIdentifier();

            reader.ReadStartElement("KeyInfo", SignedXml.XmlDsigNamespaceUrl);

            while (reader.IsStartElement())
            {
                if (reader.IsStartElement("X509Data", SignedXml.XmlDsigNamespaceUrl))
                {
                    foreach (var clause in ReadX509Data(reader))
                    {
                        result.Add(clause);
                    }
                }
                else
                {
                    if (reader.IsStartElement("KeyName", SignedXml.XmlDsigNamespaceUrl))
                    {
                        result.Add(ReadKeyNameClause(reader));
                    }
                    else
                    {
                        reader.Skip();
                    }
                }
            }

            reader.ReadEndElement();

            return result;
        }
Example #6
0
		public SigningCredentials (SecurityKey signingKey, string signatureAlgorithm, string digestAlgorithm, SecurityKeyIdentifier signingKeyIdentifier)
			: this (signingKey, signatureAlgorithm, digestAlgorithm)
		{
			if (signingKeyIdentifier == null)
				throw new ArgumentNullException ("signingKeyIdentifier");
			this.identifier = signingKeyIdentifier;
		}
Example #7
0
        public void ReadOnlyAdd()
        {
            SecurityKeyIdentifier ki = new SecurityKeyIdentifier();

            ki.MakeReadOnly();
            ki.Add(new LocalIdKeyIdentifierClause("foo"));
        }
 protected override bool TryResolveTokenCore(SecurityKeyIdentifier keyIdentifier, out SecurityToken token)
 {
     bool flag = false;
     token = null;
     flag = this.tokenResolver.TryResolveToken(keyIdentifier, false, false, out token);
     if (!flag && (this.outOfBandTokenResolvers != null))
     {
         for (int i = 0; i < this.outOfBandTokenResolvers.Count; i++)
         {
             flag = this.outOfBandTokenResolvers[i].TryResolveToken(keyIdentifier, out token);
             if (flag)
             {
                 break;
             }
         }
     }
     if (!flag)
     {
         for (int j = 0; j < keyIdentifier.Count; j++)
         {
             if (this.TryResolveTokenFromIntrinsicKeyClause(keyIdentifier[j], out token))
             {
                 return true;
             }
         }
     }
     return flag;
 }
Example #9
0
        private static SigningCredentials SetSigningCredentials <T>(T contract) where T : SamlTokenContract
        {
            SigningCredentials signingCredentials;

            if (contract.UseRsa)
            {
                var rsa = contract.SigningCertificate.PrivateKey as RSACryptoServiceProvider;
                if (rsa == null)
                {
                    throw new InvalidOperationException(
                              "Signing certificate must include private key for RSA signature.");
                }
                var rsaKey    = new RsaSecurityKey(rsa);
                var rsaClause = new RsaKeyIdentifierClause(rsa);
                var ski       = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { rsaClause });
                signingCredentials = new SigningCredentials(rsaKey,
                                                            contract.AlgorithmSuite.DefaultAsymmetricSignatureAlgorithm,
                                                            contract.AlgorithmSuite.DefaultDigestAlgorithm, ski);
            }
            else
            {
                var clause =
                    new X509SecurityToken(contract.SigningCertificate)
                    .CreateKeyIdentifierClause <X509RawDataKeyIdentifierClause>();
                var ski = new SecurityKeyIdentifier(clause);
                signingCredentials = new X509SigningCredentials(contract.SigningCertificate, ski,
                                                                contract.AlgorithmSuite.DefaultAsymmetricSignatureAlgorithm,
                                                                contract.AlgorithmSuite.DefaultDigestAlgorithm);
            }
            return(signingCredentials);
        }
        private Saml2Assertion CreateSamlAssertionWithSymmetricKey(BinarySecretSecurityToken proofToken)
        {
            X509SecurityToken           x509SecurityToken           = new X509SecurityToken(base.ClientCredentials.ClientCertificate.Certificate);
            X509SecurityToken           x509SecurityToken2          = new X509SecurityToken(base.ClientCredentials.ServiceCertificate.DefaultCertificate);
            SecurityKey                 signatureKey                = x509SecurityToken.SecurityKeys[0];
            SecurityKeyIdentifierClause securityKeyIdentifierClause = x509SecurityToken.CreateKeyIdentifierClause <X509ThumbprintKeyIdentifierClause>();
            SecurityKeyIdentifier       signatureKeyIdentifier      = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[]
            {
                securityKeyIdentifierClause
            });
            SecurityKey securityKey = x509SecurityToken2.SecurityKeys[0];
            SecurityKeyIdentifierClause securityKeyIdentifierClause2 = x509SecurityToken2.CreateKeyIdentifierClause <X509ThumbprintKeyIdentifierClause>();
            SecurityKeyIdentifier       encryptingKeyIdentifier      = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[]
            {
                securityKeyIdentifierClause2
            });

            byte[] keyBytes     = proofToken.GetKeyBytes();
            byte[] encryptedKey = securityKey.EncryptKey(base.SecurityAlgorithmSuite.DefaultAsymmetricKeyWrapAlgorithm, keyBytes);
            SecurityKeyIdentifier proofKeyIdentifier = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[]
            {
                new EncryptedKeyIdentifierClause(encryptedKey, base.SecurityAlgorithmSuite.DefaultAsymmetricKeyWrapAlgorithm, encryptingKeyIdentifier)
            });

            return(this.CreateSamlAssertion(signatureKey, signatureKeyIdentifier, proofKeyIdentifier));
        }
 private SecurityToken ResolveSignatureToken(SecurityKeyIdentifier keyIdentifier, SecurityTokenResolver resolver, bool isPrimarySignature)
 {
     TryResolveKeyIdentifier(keyIdentifier, resolver, true, out SecurityToken token);
     if (token == null && !isPrimarySignature)
     {
         // check if there is a rsa key token authenticator
         if (keyIdentifier.Count == 1)
         {
             if (keyIdentifier.TryFind <RsaKeyIdentifierClause>(out RsaKeyIdentifierClause rsaClause))
             {
                 RsaSecurityTokenAuthenticator rsaAuthenticator = FindAllowedAuthenticator <RsaSecurityTokenAuthenticator>(false);
                 if (rsaAuthenticator != null)
                 {
                     token = new RsaSecurityToken(rsaClause.Rsa);
                     ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies = rsaAuthenticator.ValidateToken(token);
                     TokenTracker rsaTracker = GetSupportingTokenTracker(rsaAuthenticator, out SupportingTokenAuthenticatorSpecification spec);
                     if (rsaTracker == null)
                     {
                         throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.Format(SR.UnknownTokenAuthenticatorUsedInTokenProcessing, rsaAuthenticator)));
                     }
                     rsaTracker.RecordToken(token);
                     SecurityTokenAuthorizationPoliciesMapping.Add(token, authorizationPolicies);
                 }
             }
         }
     }
     if (token == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
                                                                       SR.Format(SR.UnableToResolveKeyInfoForVerifyingSignature, keyIdentifier, resolver)));
     }
     return(token);
 }
Example #12
0
        public static Saml2SecurityToken CreateSaml2SecurityTokenSigningByRsa(byte[] certificate, string password, params Claim[] claims)
        {
            var descriptor = new SecurityTokenDescriptor();

            var digestAlgorithm    = "http://www.w3.org/2000/09/xmldsig#sha1";
            var signatureAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";

            var signingCert = new X509Certificate2(certificate, password);

            var rsa                = signingCert.PrivateKey as RSACryptoServiceProvider;
            var rsaKey             = new RsaSecurityKey(rsa);
            var rsaClause          = new RsaKeyIdentifierClause(rsa);
            var signingSki         = new SecurityKeyIdentifier(rsaClause);
            var signingCredentials = new SigningCredentials(rsaKey, signatureAlgorithm, digestAlgorithm, signingSki);

            descriptor.TokenType          = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0";
            descriptor.TokenIssuerName    = "CN=app.nhin-hv.com, OU=Domain Control Validated, O=app.nhin-hv.com";
            descriptor.SigningCredentials = signingCredentials;
            descriptor.Subject            = new ClaimsIdentity(claims);
            descriptor.AppliesToAddress   = "http://localhost/RelyingPartyApplication";

            var issueInstant = DateTime.UtcNow;

            descriptor.Lifetime = new Lifetime(issueInstant, issueInstant + TimeSpan.FromHours(8));

            var tokenHandler = new Saml2SecurityTokenHandler();
            var token        = tokenHandler.CreateToken(descriptor) as Saml2SecurityToken;

            return(token);
        }
Example #13
0
        /// <summary>
        /// Adds a specific <see cref="X509Certificate2"/> to decrypt
        /// authorization requests received by the OpenID Connect server.
        /// </summary>
        /// <param name="credentials">The options used to configure the OpenID Connect server.</param>
        /// <param name="certificate">The certificate used to decrypt authorization requests received by the server.</param>
        /// <returns>The encryption credentials.</returns>
        public static IList <EncryptingCredentials> AddCertificate(
            [NotNull] this IList <EncryptingCredentials> credentials,
            [NotNull] X509Certificate2 certificate)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }

            if (certificate == null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }

            if (certificate.PrivateKey == null)
            {
                throw new InvalidOperationException("The certificate doesn't contain the required private key.");
            }

            var identifier = new SecurityKeyIdentifier {
                new X509IssuerSerialKeyIdentifierClause(certificate),
                new X509RawDataKeyIdentifierClause(certificate),
                new X509ThumbprintKeyIdentifierClause(certificate),
                new LocalIdKeyIdentifierClause(certificate.Thumbprint.ToUpperInvariant())
            };

            // Mark the security key identifier as read-only to
            // ensure it can't be altered during a request.
            identifier.MakeReadOnly();

            credentials.Add(new X509EncryptingCredentials(certificate, identifier));

            return(credentials);
        }
    public static void Methods_NonNullParam_InvokeAndReturn()
    {
        var xmlReader           = XmlReader.Create(new MemoryStream());
        var xmlWriter           = XmlWriter.Create(new MemoryStream());
        var dummyToken          = new DummySecurityToken();
        var keyIdentifier       = new SecurityKeyIdentifier();
        var keyIdentifierClause = new SecurityKeyIdentifierClauseImpl("DummyClause");
        var sts = new SecurityTokenSerializerImpl();

        Assert.NotNull(sts);
        Assert.True(sts.CanReadKeyIdentifier(xmlReader));
        Assert.True(sts.CanReadKeyIdentifierClause(xmlReader));
        Assert.True(sts.CanReadToken(xmlReader));
        Assert.True(sts.CanWriteKeyIdentifier(keyIdentifier));
        Assert.True(sts.CanWriteKeyIdentifierClause(keyIdentifierClause));
        Assert.True(sts.CanWriteToken(dummyToken));

        SecurityToken token = sts.ReadToken(xmlReader, SecurityTokenResolver.CreateDefaultSecurityTokenResolver(new ReadOnlyCollection <SecurityToken>(new List <SecurityToken>()
        {
            dummyToken
        }), false));
        SecurityKeyIdentifier       identifier       = sts.ReadKeyIdentifier(xmlReader);
        SecurityKeyIdentifierClause identifierClause = sts.ReadKeyIdentifierClause(xmlReader);

        Assert.IsType <DummySecurityToken>(token);
        Assert.IsType <SecurityKeyIdentifier>(identifier);
        Assert.IsType <SecurityKeyIdentifierClauseImpl>(identifierClause);

        sts.WriteToken(xmlWriter, dummyToken);
        sts.WriteKeyIdentifier(xmlWriter, keyIdentifier);
        sts.WriteKeyIdentifierClause(xmlWriter, keyIdentifierClause);
        Assert.True(sts.WriteTokenCoreCalled);
        Assert.True(sts.WriteKeyIdentifierCoreCalled);
        Assert.True(sts.WriteKeyIdentifierClauseCoreCalled);
    }
    /// <summary>
    /// Returns the collection of certificates that the STS uses to sign tokens.
    /// </summary>
    /// <returns>The collection of certificates.</returns>
    private IEnumerable <X509Certificate2> ReadStsSigningCertificates(SecurityTokenServiceDescriptor stsDescriptor)
    {
        List <X509Certificate2> stsCertificates = new List <X509Certificate2>();

        if (stsDescriptor != null && stsDescriptor.Keys != null)
        {
            Collection <KeyDescriptor> keyDescriptors = (Collection <KeyDescriptor>)stsDescriptor.Keys;

            if (keyDescriptors != null && keyDescriptors.Count > 0)
            {
                foreach (KeyDescriptor keyDescriptor in keyDescriptors)
                {
                    if (keyDescriptor.KeyInfo != null && (keyDescriptor.Use == KeyType.Signing || keyDescriptor.Use == KeyType.Unspecified))
                    {
                        SecurityKeyIdentifier          kid    = keyDescriptor.KeyInfo;
                        X509RawDataKeyIdentifierClause clause = null;

                        kid.TryFind <X509RawDataKeyIdentifierClause>(out clause);

                        if (clause != null)
                        {
                            X509Certificate2 certificate = new X509Certificate2(clause.GetX509RawData());
                            stsCertificates.Add(certificate);
                        }
                    }
                }
            }
        }

        return(stsCertificates);
    }
 public SamlSubject(string nameFormat, string nameQualifier, string name, IEnumerable<string> confirmations, string confirmationData, SecurityKeyIdentifier securityKeyIdentifier)
 {
     this.confirmationMethods = new ImmutableCollection<string>();
     if (confirmations != null)
     {
         foreach (string str in confirmations)
         {
             if (string.IsNullOrEmpty(str))
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("SAMLEntityCannotBeNullOrEmpty", new object[] { XD.SamlDictionary.SubjectConfirmationMethod.Value }));
             }
             this.confirmationMethods.Add(str);
         }
     }
     if ((this.confirmationMethods.Count == 0) && string.IsNullOrEmpty(name))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("SAMLSubjectRequiresNameIdentifierOrConfirmationMethod"));
     }
     if ((this.confirmationMethods.Count == 0) && ((confirmationData != null) || (securityKeyIdentifier != null)))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("SAMLSubjectRequiresConfirmationMethodWhenConfirmationDataOrKeyInfoIsSpecified"));
     }
     this.name = name;
     this.nameFormat = nameFormat;
     this.nameQualifier = nameQualifier;
     this.confirmationData = confirmationData;
     this.securityKeyIdentifier = securityKeyIdentifier;
 }
Example #17
0
        protected override bool TryResolveTokenCore(SecurityKeyIdentifier keyIdentifier, out SecurityToken token)
        {
            bool flag = false;

            token = null;
            flag  = this.tokenResolver.TryResolveToken(keyIdentifier, false, false, out token);
            if (!flag && (this.outOfBandTokenResolvers != null))
            {
                for (int i = 0; i < this.outOfBandTokenResolvers.Count; i++)
                {
                    flag = this.outOfBandTokenResolvers[i].TryResolveToken(keyIdentifier, out token);
                    if (flag)
                    {
                        break;
                    }
                }
            }
            if (!flag)
            {
                for (int j = 0; j < keyIdentifier.Count; j++)
                {
                    if (this.TryResolveTokenFromIntrinsicKeyClause(keyIdentifier[j], out token))
                    {
                        return(true);
                    }
                }
            }
            return(flag);
        }
Example #18
0
        /// <summary>
        /// Adds a specific <see cref="X509Certificate2"/> to sign tokens issued by the OpenID Connect server.
        /// </summary>
        /// <param name="credentials">The options used to configure the OpenID Connect server.</param>
        /// <param name="certificate">The certificate used to sign security tokens issued by the server.</param>
        /// <returns>The signing credentials.</returns>
        public static IList <SigningCredentials> AddCertificate(
            [NotNull] this IList <SigningCredentials> credentials,
            [NotNull] X509Certificate2 certificate)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }

            if (certificate == null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }

            if (certificate.PrivateKey == null)
            {
                throw new InvalidOperationException("The certificate doesn't contain the required private key.");
            }

            var identifier = new SecurityKeyIdentifier(
                new LocalIdKeyIdentifierClause(certificate.Thumbprint.ToUpperInvariant()),
                new X509SecurityToken(certificate).CreateKeyIdentifierClause <X509IssuerSerialKeyIdentifierClause>(),
                new X509SecurityToken(certificate).CreateKeyIdentifierClause <X509RawDataKeyIdentifierClause>(),
                new X509SecurityToken(certificate).CreateKeyIdentifierClause <X509ThumbprintKeyIdentifierClause>());

            credentials.Add(new X509SigningCredentials(certificate, identifier));

            return(credentials);
        }
        protected override SecurityKeyIdentifier ReadKeyIdentifierCore(XmlReader reader)
        {
            var result = new SecurityKeyIdentifier();

            reader.ReadStartElement("KeyInfo", SignedXml.XmlDsigNamespaceUrl);

            while (reader.IsStartElement())
            {
                if (reader.IsStartElement("X509Data", SignedXml.XmlDsigNamespaceUrl))
                {
                    foreach (var clause in ReadX509Data(reader))
                    {
                        result.Add(clause);
                    }
                }
                else
                {
                    if (reader.IsStartElement("KeyName", SignedXml.XmlDsigNamespaceUrl))
                    {
                        result.Add(ReadKeyNameClause(reader));
                    }
                    else
                    {
                        reader.Skip();
                    }
                }
            }

            reader.ReadEndElement();

            return(result);
        }
        /// <summary>
        /// Constructs an EncryptingCredentials with a security key, a security key identifier and
        /// the encryption algorithm.
        /// </summary>
        /// <param name="key">A security key for encryption.</param>
        /// <param name="keyIdentifier">A security key identifier for the encryption key.</param>
        /// <param name="algorithm">The encryption algorithm.</param>
        /// <exception cref="ArgumentNullException">When key is null.</exception>
        /// <exception cref="ArgumentNullException">When key identifier is null.</exception>
        /// <exception cref="ArgumentNullException">When algorithm is null.</exception>
        public EncryptingCredentials(SecurityKey key, SecurityKeyIdentifier keyIdentifier, string algorithm)
        {
            if (key == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("key");
            }

            if (keyIdentifier == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifier");
            }

            if (string.IsNullOrEmpty(algorithm))
            {
                throw DiagnosticUtility.ThrowHelperArgumentNullOrEmptyString("algorithm");
            }

            //
            // It is possible that keyIdentifier is pointing to a token which 
            // is not capable of doing the given algorithm, we have no way verify 
            // that at this level.
            //
            _algorithm = algorithm;
            _key = key;
            _keyIdentifier = keyIdentifier;
        }
        WrappedKeySecurityToken ReadWrappedKeySecurityTokenCore(
            XmlReader reader, SecurityTokenResolver tokenResolver)
        {
            if (tokenResolver == null)
            {
                throw new ArgumentNullException("tokenResolver");
            }
            EncryptedKey ek = new EncryptedKey();

            ek.LoadXml(new XmlDocument().ReadNode(reader) as XmlElement);
            SecurityKeyIdentifier ki = new SecurityKeyIdentifier();

            foreach (KeyInfoClause kic in ek.KeyInfo)
            {
                ki.Add(ReadKeyIdentifierClause(new XmlNodeReader(kic.GetXml())));
            }
            SecurityToken token = tokenResolver.ResolveToken(ki);
            string        alg   = ek.EncryptionMethod.KeyAlgorithm;

            foreach (SecurityKey skey in token.SecurityKeys)
            {
                if (skey.IsSupportedAlgorithm(alg))
                {
                    byte [] key = skey.DecryptKey(alg, ek.CipherData.CipherValue);
                    WrappedKeySecurityToken wk =
                        new WrappedKeySecurityToken(ek.Id, key, alg, token, ki);
                    // FIXME: This should not be required.
                    wk.SetWrappedKey(ek.CipherData.CipherValue);
                    wk.ReferenceList = ek.ReferenceList;
                    return(wk);
                }
            }
            throw new InvalidOperationException(String.Format("Cannot resolve security key with the resolved SecurityToken specified by the key identifier in the EncryptedKey XML. The key identifier is: {0}", ki));
        }
        public SamlSubject(string nameFormat, string nameQualifier, string name, IEnumerable<string> confirmations, string confirmationData, SecurityKeyIdentifier securityKeyIdentifier)
        {
            if (confirmations != null)
            {
                foreach (string method in confirmations)
                {
                    if (string.IsNullOrEmpty(method))
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLEntityCannotBeNullOrEmpty, XD.SamlDictionary.SubjectConfirmationMethod.Value));

                    this.confirmationMethods.Add(method);
                }
            }

            if ((this.confirmationMethods.Count == 0) && (string.IsNullOrEmpty(name)))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLSubjectRequiresNameIdentifierOrConfirmationMethod));

            if ((this.confirmationMethods.Count == 0) && ((confirmationData != null) || (securityKeyIdentifier != null)))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLSubjectRequiresConfirmationMethodWhenConfirmationDataOrKeyInfoIsSpecified));

            this.name = name;
            this.nameFormat = nameFormat;
            this.nameQualifier = nameQualifier;
            this.confirmationData = confirmationData;
            this.securityKeyIdentifier = securityKeyIdentifier;
        }
Example #23
0
        /// <summary>
        /// Creates a SAML assertion based on an Asymmetric proof key
        /// </summary>
        /// <param name="claims">A ClaimSet containing the claims to be placed into the SAML assertion</param>
        /// <param name="proofToken">An  RsaSecurityToken containing the proof key</param>
        /// <param name="algoSuite">The algorithm suite to use when performing cryptographic operations</param>
        /// <returns>A SAML assertion containing the passed in claims and proof key, signed by the proof key</returns>
        public static SamlAssertion CreateAsymmetricKeyBasedAssertion(ClaimSet claims, SecurityToken proofToken, SecurityAlgorithmSuite algoSuite)
        {
            // Check various input parameters
            if (claims == null)
            {
                throw new ArgumentNullException("claims");
            }

            if (proofToken == null)
            {
                throw new ArgumentNullException("proofToken");
            }

            if (claims.Count == 0)
            {
                throw new ArgumentException("Provided ClaimSet must contain at least one claim");
            }

            // Create key identifier for proof key
            SecurityKeyIdentifier proofKeyIdentifier = new SecurityKeyIdentifier(proofToken.CreateKeyIdentifierClause <RsaKeyIdentifierClause>());
            // Get signing key and a key identifier for same
            SecurityKey           signatureKey           = proofToken.SecurityKeys[0];
            SecurityKeyIdentifier signatureKeyIdentifier = proofKeyIdentifier;

            // Create the assertion
            return(CreateAssertion(claims, signatureKey, signatureKeyIdentifier, proofKeyIdentifier, algoSuite));
        }
        protected override bool TryResolveTokenCore(SecurityKeyIdentifier keyIdentifier, out SecurityToken token)
        {
            bool resolved = false;

            token = null;

            resolved = _tokenResolver.TryResolveToken(keyIdentifier, false, false, out token);

            if (!resolved)
            {
                resolved = base.TryResolveTokenCore(keyIdentifier, out token);
            }

            if (!resolved)
            {
                for (int i = 0; i < keyIdentifier.Count; ++i)
                {
                    if (TryResolveTokenFromIntrinsicKeyClause(keyIdentifier[i], out token))
                    {
                        resolved = true;
                        break;
                    }
                }
            }

            return(resolved);
        }
Example #25
0
        /// <summary>
        /// Creates a SAML Token with the input parameters
        /// </summary>
        /// <param name="stsName">Name of the STS issuing the SAML Token</param>
        /// <param name="proofToken">Associated Proof Token</param>
        /// <param name="issuerToken">Associated Issuer Token</param>
        /// <param name="proofKeyEncryptionToken">Token to encrypt the proof key with</param>
        /// <param name="samlConditions">The Saml Conditions to be used in the construction of the SAML Token</param>
        /// <param name="samlAttributes">The Saml Attributes to be used in the construction of the SAML Token</param>
        /// <returns>A SAML Token</returns>
        public static SamlSecurityToken CreateSamlToken(string stsName,
                                                        BinarySecretSecurityToken proofToken,
                                                        SecurityToken issuerToken,
                                                        SecurityToken proofKeyEncryptionToken,
                                                        SamlConditions samlConditions,
                                                        IEnumerable <SamlAttribute> samlAttributes)
        {
            // Create a security token reference to the issuer certificate
            SecurityKeyIdentifierClause skic = issuerToken.CreateKeyIdentifierClause <X509ThumbprintKeyIdentifierClause>();
            SecurityKeyIdentifier       issuerKeyIdentifier = new SecurityKeyIdentifier(skic);

            // Create an encrypted key clause containing the encrypted proof key
            byte[] wrappedKey = proofKeyEncryptionToken.SecurityKeys[0].EncryptKey(SecurityAlgorithms.RsaOaepKeyWrap, proofToken.GetKeyBytes());
            SecurityKeyIdentifierClause  encryptingTokenClause = proofKeyEncryptionToken.CreateKeyIdentifierClause <X509ThumbprintKeyIdentifierClause>();
            EncryptedKeyIdentifierClause encryptedKeyClause    = new EncryptedKeyIdentifierClause(wrappedKey, SecurityAlgorithms.RsaOaepKeyWrap, new SecurityKeyIdentifier(encryptingTokenClause));
            SecurityKeyIdentifier        proofKeyIdentifier    = new SecurityKeyIdentifier(encryptedKeyClause);

            // Create a comfirmationMethod for HolderOfKey
            List <string> confirmationMethods = new List <string>(1);

            confirmationMethods.Add(SamlConstants.HolderOfKey);

            // Create a SamlSubject with proof key and confirmation method from above
            SamlSubject samlSubject = new SamlSubject(null,
                                                      null,
                                                      null,
                                                      confirmationMethods,
                                                      null,
                                                      proofKeyIdentifier);

            // Create a SamlAttributeStatement from the passed in SamlAttribute collection and the SamlSubject from above
            SamlAttributeStatement samlAttributeStatement = new SamlAttributeStatement(samlSubject, samlAttributes);

            // Put the SamlAttributeStatement into a list of SamlStatements
            List <SamlStatement> samlSubjectStatements = new List <SamlStatement>();

            samlSubjectStatements.Add(samlAttributeStatement);

            // Create a SigningCredentials instance from the key associated with the issuerToken.
            SigningCredentials signingCredentials = new SigningCredentials(issuerToken.SecurityKeys[0],
                                                                           SecurityAlgorithms.RsaSha1Signature,
                                                                           SecurityAlgorithms.Sha1Digest,
                                                                           issuerKeyIdentifier);

            // Create a SamlAssertion from the list of SamlStatements created above and the passed in
            // SamlConditions.
            SamlAssertion samlAssertion = new SamlAssertion("_" + Guid.NewGuid().ToString(),
                                                            stsName,
                                                            DateTime.UtcNow,
                                                            samlConditions,
                                                            new SamlAdvice(),
                                                            samlSubjectStatements
                                                            );

            // Set the SigningCredentials for the SamlAssertion
            samlAssertion.SigningCredentials = signingCredentials;

            // Create a SamlSecurityToken from the SamlAssertion and return it
            return(new SamlSecurityToken(samlAssertion));
        }
Example #26
0
        private static SecurityKey ResolveRsaKeys(
            string token,
            SecurityToken securityToken,
            SecurityKeyIdentifier keyIdentifier,
            TokenValidationParameters validationParameters)
        {
            string id = null;

            foreach (var keyId in keyIdentifier)
            {
                var nk = keyId as NamedKeySecurityKeyIdentifierClause;
                if (nk != null)
                {
                    id = nk.Id;
                    break;
                }
            }

            if (id == null)
            {
                return(null);
            }

            var issuerToken = validationParameters.IssuerSigningTokens.FirstOrDefault(it => it.Id == id);

            if (issuerToken == null)
            {
                return(null);
            }

            return(issuerToken.SecurityKeys.FirstOrDefault());
        }
Example #27
0
        private SecurityKeyIdentifier ReadGenericXmlSecurityKeyIdentifier(XmlDictionaryReader localReader, Exception previousException)
        {
            if (!localReader.IsStartElement(System.IdentityModel.XD.XmlSignatureDictionary.KeyInfo, System.IdentityModel.XD.XmlSignatureDictionary.Namespace))
            {
                return((SecurityKeyIdentifier)null);
            }
            localReader.ReadStartElement(System.IdentityModel.XD.XmlSignatureDictionary.KeyInfo, System.IdentityModel.XD.XmlSignatureDictionary.Namespace);
            SecurityKeyIdentifier securityKeyIdentifier = new SecurityKeyIdentifier();

            if (localReader.IsStartElement())
            {
#if FEATURE_CORECLR
                throw new NotImplementedException("GenericXmlSecurityKeyIdentifierClause not supported");
#else
                string attribute = localReader.GetAttribute(System.IdentityModel.XD.UtilityDictionary.IdAttribute, System.IdentityModel.XD.UtilityDictionary.Namespace);
                SecurityKeyIdentifierClause clause = (SecurityKeyIdentifierClause) new GenericXmlSecurityKeyIdentifierClause(new XmlDocument().ReadNode((XmlReader)localReader) as XmlElement);
                if (!string.IsNullOrEmpty(attribute))
                {
                    clause.Id = attribute;
                }
                securityKeyIdentifier.Add(clause);
#endif
            }
            if (securityKeyIdentifier.Count == 0)
            {
                throw previousException;
            }
            localReader.ReadEndElement();
            return(securityKeyIdentifier);
        }
        protected override ISecurityElement CompleteEncryptionCore(
            SendSecurityHeaderElement primarySignature,
            SendSecurityHeaderElement[] basicTokens,
            SendSecurityHeaderElement[] signatureConfirmations,
            SendSecurityHeaderElement[] endorsingSignatures)
        {
            if (this.referenceList == null)
            {
                return(null);
            }

            if (primarySignature != null && primarySignature.Item != null && primarySignature.MarkedForEncryption)
            {
                EncryptElement(primarySignature);
            }

            if (basicTokens != null)
            {
                for (int i = 0; i < basicTokens.Length; ++i)
                {
                    if (basicTokens[i].MarkedForEncryption)
                    {
                        EncryptElement(basicTokens[i]);
                    }
                }
            }

            if (signatureConfirmations != null)
            {
                for (int i = 0; i < signatureConfirmations.Length; ++i)
                {
                    if (signatureConfirmations[i].MarkedForEncryption)
                    {
                        EncryptElement(signatureConfirmations[i]);
                    }
                }
            }

            if (endorsingSignatures != null)
            {
                for (int i = 0; i < endorsingSignatures.Length; ++i)
                {
                    if (endorsingSignatures[i].MarkedForEncryption)
                    {
                        EncryptElement(endorsingSignatures[i]);
                    }
                }
            }

            try
            {
                return(this.referenceList.DataReferenceCount > 0 ? this.referenceList : null);
            }
            finally
            {
                this.referenceList = null;
                this.encryptingSymmetricAlgorithm = null;
                this.encryptionKeyIdentifier      = null;
            }
        }
Example #29
0
        // This method encrypts the provided key using the key material associated with the cert
        // returned by DetermineEncryptingCert
        private byte[] GetEncryptedKey(SecurityToken encryptingToken, byte[] key, out SecurityKeyIdentifier ski)
        {
            // If encryptingToken is null, we're toast
            if (encryptingToken == null)
            {
                throw new ArgumentNullException("encryptingToken");
            }

            // If key is null, we're toast
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            // Get the zeroth security key
            SecurityKey encryptingKey = encryptingToken.SecurityKeys[0];

            // Get the encryption algorithm to use
            string keywrapAlgorithm = GetKeyWrapAlgorithm(encryptingKey);

            // encrypt the passed in key
            byte[] encryptedKey = encryptingKey.EncryptKey(keywrapAlgorithm, key);

            // get a key identifier for the encrypting key
            SecurityKeyIdentifier eki = GetExternalSecurityKeyIdentifier(encryptingToken);

            // return the proof key identifier
            ski = GetProofKeyIdentifier(encryptedKey, keywrapAlgorithm, eki);

            // return the encrypted key
            return(encryptedKey);
        }
        protected override void StartPrimarySignatureCore(SecurityToken token,
                                                          SecurityKeyIdentifier keyIdentifier,
                                                          MessagePartSpecification signatureParts,
                                                          bool generateTargettableSignature)
        {
            SecurityAlgorithmSuite suite     = this.AlgorithmSuite;
            string canonicalizationAlgorithm = suite.DefaultCanonicalizationAlgorithm;
            XmlDictionaryString canonicalizationAlgorithmDictionaryString = suite.DefaultCanonicalizationAlgorithmDictionaryString;

            if (canonicalizationAlgorithm != SecurityAlgorithms.ExclusiveC14n)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new MessageSecurityException(SR.GetString(SR.UnsupportedCanonicalizationAlgorithm, suite.DefaultCanonicalizationAlgorithm)));
            }
            string signatureAlgorithm;
            XmlDictionaryString signatureAlgorithmDictionaryString;

            suite.GetSignatureAlgorithmAndKey(token, out signatureAlgorithm, out this.signatureKey, out signatureAlgorithmDictionaryString);
            string digestAlgorithm = suite.DefaultDigestAlgorithm;
            XmlDictionaryString digestAlgorithmDictionaryString = suite.DefaultDigestAlgorithmDictionaryString;

            this.signedInfo = new PreDigestedSignedInfo(ServiceModelDictionaryManager.Instance, canonicalizationAlgorithm, canonicalizationAlgorithmDictionaryString, digestAlgorithm, digestAlgorithmDictionaryString, signatureAlgorithm, signatureAlgorithmDictionaryString);
            this.signedXml  = new SignedXml(this.signedInfo, ServiceModelDictionaryManager.Instance, this.StandardsManager.SecurityTokenSerializer);
            if (keyIdentifier != null)
            {
                this.signedXml.Signature.KeyIdentifier = keyIdentifier;
            }
            if (generateTargettableSignature)
            {
                this.signedXml.Id = GenerateId();
            }
            this.effectiveSignatureParts = signatureParts;
            this.hashStream = this.signedInfo.ResourcePool.TakeHashStream(digestAlgorithm);
        }
Example #31
0
        //</snippet2>

        //<snippet3>
        SecurityKeyIdentifier GetKeyIdentifierForEncryptedKey(byte[] encryptedKey,
                                                              SecurityToken encryptingToken)
        {
            SecurityKeyIdentifier encryptingKeyIdentifier = new SecurityKeyIdentifier(encryptingToken.CreateKeyIdentifierClause <X509ThumbprintKeyIdentifierClause>());

            return(new SecurityKeyIdentifier(new EncryptedKeyIdentifierClause(encryptedKey, SecurityAlgorithms.RsaOaepKeyWrap, encryptingKeyIdentifier)));
        }
        // This method encrypts the provided key using the key material associated with the certificate
        // returned by DetermineEncryptingCert.
        private static byte[] GetEncryptedKey(SecurityToken encryptingToken, byte[] key, out SecurityKeyIdentifier ski)
        {
            // If encryptingToken is null, an exception is thrown.
            if (encryptingToken == null)
            {
                throw new ArgumentNullException("encryptingToken");
            }

            // If key is null, an exception is thrown.
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            // Get the zeroth security key.
            SecurityKey encryptingKey = encryptingToken.SecurityKeys[0];

            // Get the encryption algorithm to use.
            string keywrapAlgorithm = GetKeyWrapAlgorithm(encryptingKey);

            // Encrypt the passed in key.
            byte[] encryptedKey = encryptingKey.EncryptKey(keywrapAlgorithm, key);

            // Get a key identifier for the encrypting key.
            SecurityKeyIdentifier eki = new SecurityKeyIdentifier(encryptingToken.CreateKeyIdentifierClause <X509ThumbprintKeyIdentifierClause>());

            // Return the proof key identifier.
            ski = GetProofKeyIdentifier(encryptedKey, keywrapAlgorithm, eki);

            // Return the encrypted key.
            return(encryptedKey);
        }
        private SecurityToken ResolveSignatureToken(SecurityKeyIdentifier keyIdentifier, SecurityTokenResolver resolver, bool isPrimarySignature)
        {
            SecurityToken          token;
            RsaKeyIdentifierClause clause;

            TryResolveKeyIdentifier(keyIdentifier, resolver, true, out token);
            if (((token == null) && !isPrimarySignature) && ((keyIdentifier.Count == 1) && keyIdentifier.TryFind <RsaKeyIdentifierClause>(out clause)))
            {
                RsaSecurityTokenAuthenticator tokenAuthenticator = base.FindAllowedAuthenticator <RsaSecurityTokenAuthenticator>(false);
                if (tokenAuthenticator != null)
                {
                    SupportingTokenAuthenticatorSpecification specification;
                    token = new RsaSecurityToken(clause.Rsa);
                    ReadOnlyCollection <IAuthorizationPolicy> onlys = tokenAuthenticator.ValidateToken(token);
                    TokenTracker supportingTokenTracker             = base.GetSupportingTokenTracker(tokenAuthenticator, out specification);
                    if (supportingTokenTracker == null)
                    {
                        throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(System.ServiceModel.SR.GetString("UnknownTokenAuthenticatorUsedInTokenProcessing", new object[] { tokenAuthenticator })));
                    }
                    supportingTokenTracker.RecordToken(token);
                    base.SecurityTokenAuthorizationPoliciesMapping.Add(token, onlys);
                }
            }
            if (token == null)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("UnableToResolveKeyInfoForVerifyingSignature", new object[] { keyIdentifier, resolver })));
            }
            return(token);
        }
Example #34
0
        public SigningCredentials GetSigningCredentials()
        {
            string signatureAlgorithm;
            string digestAlgorithm;

            var key = GetKey();

            if (key is RsaSecurityKey)
            {
                signatureAlgorithm = SecurityAlgorithms.RsaSha256Signature;
                digestAlgorithm    = SecurityAlgorithms.Sha256Digest;
            }
            else if (key is EcDsaSecurityKey)
            {
                var ecdsaKey = key as EcDsaSecurityKey;
                signatureAlgorithm = ecdsaKey.SignatureAlgorithm;
                digestAlgorithm    = ecdsaKey.DigestAlgorithm;
            }
            else
            {
                throw new NotImplementedException();
            }

            var keyIdentifierClause   = new NamedKeySecurityKeyIdentifierClause(name: "kid", id: Id);
            var securityKeyIdentifier = new SecurityKeyIdentifier(keyIdentifierClause);

            var signingCredentials = new SigningCredentials(
                GetKey(),
                signatureAlgorithm,
                digestAlgorithm,
                securityKeyIdentifier);

            return(signingCredentials);
        }
Example #35
0
 private bool TryResolveTokenFromIntrinsicKeyClause(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityToken token)
 {
     token = null;
     if (keyIdentifierClause is RsaKeyIdentifierClause)
     {
         token = new RsaSecurityToken(((RsaKeyIdentifierClause)keyIdentifierClause).Rsa);
         return(true);
     }
     if (keyIdentifierClause is X509RawDataKeyIdentifierClause)
     {
         token = new X509SecurityToken(new X509Certificate2(((X509RawDataKeyIdentifierClause)keyIdentifierClause).GetX509RawData()), false);
         return(true);
     }
     if (keyIdentifierClause is EncryptedKeyIdentifierClause)
     {
         SecurityToken token2;
         EncryptedKeyIdentifierClause keyClause = (EncryptedKeyIdentifierClause)keyIdentifierClause;
         SecurityKeyIdentifier        encryptingKeyIdentifier = keyClause.EncryptingKeyIdentifier;
         if (base.TryResolveToken(encryptingKeyIdentifier, out token2))
         {
             token = System.ServiceModel.Security.SecurityUtils.CreateTokenFromEncryptedKeyClause(keyClause, token2);
             return(true);
         }
     }
     return(false);
 }
        protected override void WriteKeyIdentifierCore(XmlWriter writer, SecurityKeyIdentifier keyIdentifier)
        {
            bool flag = false;
            XmlDictionaryWriter writer2 = XmlDictionaryWriter.CreateDictionaryWriter(writer);

            for (int i = 0; i < this.keyIdentifierEntries.Count; i++)
            {
                KeyIdentifierEntry entry = this.keyIdentifierEntries[i];
                if (entry.SupportsCore(keyIdentifier))
                {
                    try
                    {
                        entry.WriteKeyIdentifierCore(writer2, keyIdentifier);
                    }
                    catch (Exception exception)
                    {
                        if (!this.ShouldWrapException(exception))
                        {
                            throw;
                        }
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.ServiceModel.SR.GetString("ErrorSerializingKeyIdentifier"), exception));
                    }
                    flag = true;
                    break;
                }
            }
            if (!flag)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("StandardsManagerCannotWriteObject", new object[] { keyIdentifier.GetType() })));
            }
            writer2.Flush();
        }
 public bool CanWriteKeyIdentifier(SecurityKeyIdentifier keyIdentifier)
 {
     if (keyIdentifier == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifier");
     }
     return this.CanWriteKeyIdentifierCore(keyIdentifier);
 }
 public bool TryResolveToken(SecurityKeyIdentifier keyIdentifier, out SecurityToken token)
 {
     if (keyIdentifier == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifier");
     }
     return TryResolveTokenCore(keyIdentifier, out token);
 }
Example #39
0
        /// <summary>
        /// Creates a SAML Token with the input parameters
        /// </summary>
        /// <param name="stsName">Name of the STS issuing the SAML Token</param>
        /// <param name="proofToken">Associated Proof Token</param>
        /// <param name="issuerToken">Associated Issuer Token</param>
        /// <param name="proofKeyEncryptionToken">Token to encrypt the proof key with</param>
        /// <param name="samlConditions">The Saml Conditions to be used in the construction of the SAML Token</param>
        /// <param name="samlAttributes">The Saml Attributes to be used in the construction of the SAML Token</param>
        /// <returns>A SAML Token</returns>
        public static SamlSecurityToken CreateSamlToken(string stsName,
                                                        BinarySecretSecurityToken proofToken,
                                                        SecurityToken issuerToken,
                                                        SecurityToken proofKeyEncryptionToken,
                                                        SamlConditions samlConditions,
                                                        IEnumerable<SamlAttribute> samlAttributes)
		{
            // Create a security token reference to the issuer certificate 
            SecurityKeyIdentifierClause skic = issuerToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>();
            SecurityKeyIdentifier issuerKeyIdentifier = new SecurityKeyIdentifier(skic);

            // Create an encrypted key clause containing the encrypted proof key
            byte[] wrappedKey = proofKeyEncryptionToken.SecurityKeys[0].EncryptKey(SecurityAlgorithms.RsaOaepKeyWrap, proofToken.GetKeyBytes());
            SecurityKeyIdentifierClause encryptingTokenClause = proofKeyEncryptionToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>();
            EncryptedKeyIdentifierClause encryptedKeyClause = new EncryptedKeyIdentifierClause(wrappedKey, SecurityAlgorithms.RsaOaepKeyWrap, new SecurityKeyIdentifier(encryptingTokenClause) );
            SecurityKeyIdentifier proofKeyIdentifier = new SecurityKeyIdentifier(encryptedKeyClause);

            // Create a comfirmationMethod for HolderOfKey
			List<string> confirmationMethods = new List<string>(1);
			confirmationMethods.Add(SamlConstants.HolderOfKey);

            // Create a SamlSubject with proof key and confirmation method from above
			SamlSubject samlSubject = new SamlSubject(null,
													  null,
													  null,
													  confirmationMethods,
													  null,
                                                      proofKeyIdentifier);

            // Create a SamlAttributeStatement from the passed in SamlAttribute collection and the SamlSubject from above
			SamlAttributeStatement samlAttributeStatement = new SamlAttributeStatement(samlSubject, samlAttributes);

            // Put the SamlAttributeStatement into a list of SamlStatements
			List<SamlStatement> samlSubjectStatements = new List<SamlStatement>();
			samlSubjectStatements.Add(samlAttributeStatement);

            // Create a SigningCredentials instance from the key associated with the issuerToken.
            SigningCredentials signingCredentials = new SigningCredentials(issuerToken.SecurityKeys[0],
                                                                           SecurityAlgorithms.RsaSha1Signature,
                                                                           SecurityAlgorithms.Sha1Digest,
                                                                           issuerKeyIdentifier);

            // Create a SamlAssertion from the list of SamlStatements created above and the passed in
            // SamlConditions.
			SamlAssertion samlAssertion = new SamlAssertion("_" + Guid.NewGuid().ToString(),
							                                stsName,
							                                DateTime.UtcNow,
							                                samlConditions,
							                                new SamlAdvice(),
							                                samlSubjectStatements
						                                	);
            // Set the SigningCredentials for the SamlAssertion
			samlAssertion.SigningCredentials = signingCredentials;

            // Create a SamlSecurityToken from the SamlAssertion and return it
			return new SamlSecurityToken(samlAssertion);
		}
        /// <summary>
        /// Constructor to use when working with SecurityKeyIdentifiers
        /// </summary>
        /// <param name="securityKeyIdentifier">SecurityKeyIdentifier that represents a SecuriytKey</param>
        /// <param name="securityTokenResolver">SecurityTokenResolver that can be resolved to a SecurityKey</param>
        /// <exception cref="ArgumentNullException">Thrown if the 'securityKeyIdentifier' is null</exception>
        public SecurityKeyElement(SecurityKeyIdentifier securityKeyIdentifier, SecurityTokenResolver securityTokenResolver)
        {
            if (securityKeyIdentifier == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityKeyIdentifier");
            }

            Initialize(securityKeyIdentifier, securityTokenResolver);
        }
 protected override SecurityKey ResolveIssuerSigningKey(string token, SecurityToken securityToken, SecurityKeyIdentifier keyIdentifier, TokenValidationParameters validationParameters)
 {
     var certificate = ((JwtSecurityToken)securityToken).GetCertificateFromToken();
     if (certificate != null)
     {
         keyIdentifier.Add(new X509RawDataKeyIdentifierClause(certificate));
     }
     return base.ResolveIssuerSigningKey(token, securityToken, keyIdentifier, validationParameters);
 }
        /// <summary>
        /// Constructs a proof token based on RSA key.
        /// </summary>
        /// <param name="rsaAlgorithm"></param>
        public AsymmetricProofDescriptor( RSA rsaAlgorithm )
        {
            if ( rsaAlgorithm == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "rsaAlgorithm" );
            }

            _keyIdentifier = new SecurityKeyIdentifier(new RsaKeyIdentifierClause(rsaAlgorithm));
        }
		public EncryptedKeyIdentifierClause (
			byte [] encryptedKey, string encryptionMethod,
			SecurityKeyIdentifier identifier, string carriedKeyName,
			byte [] derivationNonce, int derivationLength)
			: base (encryptionMethod, encryptedKey, true, derivationNonce, derivationLength)
		{
			this.carried_key_name = carriedKeyName;
			this.identifier = identifier;
			this.enc_method = encryptionMethod;
		}
		protected override bool TryResolveTokenCore (
			SecurityKeyIdentifier keyIdentifier,
			out SecurityToken token)
		{
			token = null;
			foreach (SecurityTokenResolver r in resolvers)
				if (r != null && r.TryResolveToken (keyIdentifier, out token))
					return true;
			return false;
		}
 /// <summary>
 /// Initializes a new instance of the <b>RequestSecurityTokenResponse</b> using the specified
 /// security token request, ppid and MRZ information.
 /// </summary>
 /// <param name="rst"><b>RST</b> to which this instance is a response (RSTR)</param>
 /// <param name="ppid">Identifier of the person requesting the token</param>
 /// <param name="mrz">MRZ information used for constructing this RSTR</param>
 public RequestSecurityTokenResponse(RST rst, string ppid, MRZInfo mrz)
     : base(false)
 {
     this.context = rst.Context;
     this.useKey = rst.UseKey;
     this.keyType = rst.KeyType;
     this.claimTypes = rst.ClaimTypes;
     this.ppid = ppid;
     this.mrz = mrz;
 }
Example #46
0
		public SecurityToken ResolveToken (
			SecurityKeyIdentifier keyIdentifier)
		{
			if (keyIdentifier == null)
				throw new ArgumentNullException ("keyIdentifierClause");
			SecurityToken ret;
			if (!TryResolveToken (keyIdentifier, out ret))
				throw new InvalidOperationException (String.Format ("Could not resolve security token from the key identifier '{0}'", keyIdentifier));
			return ret;
		}
 internal EncryptedKeyIdentifierClause(byte[] encryptedKey, string encryptionMethod, SecurityKeyIdentifier encryptingKeyIdentifier, string carriedKeyName, bool cloneBuffer, byte[] derivationNonce, int derivationLength) : base("http://www.w3.org/2001/04/xmlenc#EncryptedKey", encryptedKey, cloneBuffer, derivationNonce, derivationLength)
 {
     if (encryptionMethod == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("encryptionMethod");
     }
     this.carriedKeyName = carriedKeyName;
     this.encryptionMethod = encryptionMethod;
     this.encryptingKeyIdentifier = encryptingKeyIdentifier;
 }
 /// <summary>
 /// Constructs a proof token based on key identifier.
 /// </summary>
 /// <param name="keyIdentifier"></param>
 public AsymmetricProofDescriptor( SecurityKeyIdentifier keyIdentifier )
 {
     if ( keyIdentifier == null )
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "keyIdentifier" );
     }
     //
     // This is a key identifier for an asymmetric key
     //
     _keyIdentifier = keyIdentifier;
 }
        public AzureKeyVaultSigningCredentials(RsaSecurityKey signingKey, string digestAlgorithm, SecurityKeyIdentifier signingKeyIdentifier = null) : base(signingKey, SecurityAlgorithms.RsaSha256Signature, digestAlgorithm, signingKeyIdentifier)
        {
            if (signingKey.HasPrivateKey())
            {
                throw new ArgumentException("For security reasons, the signing key cannot contain the private key. Please remove all traces of this from the application and defer to Azure Key Vault for signing.", nameof(signingKey));
            }

            if (digestAlgorithm != SecurityAlgorithms.Sha256Digest && digestAlgorithm != SecurityAlgorithms.Sha512Digest)
            {
                throw new ArgumentOutOfRangeException(nameof(digestAlgorithm), digestAlgorithm, "Only SHA256 and SHA512 are supported at this time.");
            }
        }
Example #50
0
 SecurityKey SigningKeyResolver(string token, SecurityToken securityToken, SecurityKeyIdentifier keyIdentifier, TokenValidationParameters validationParameters)
 {
     foreach (var keyIdentifierClause in keyIdentifier)
     {
         var match = Issuers
             .SelectMany(issuer => issuer.GetConfigurationAsync(CancellationToken.None).Result.SigningTokens)
             .FirstOrDefault(t => t.MatchesKeyIdentifierClause(keyIdentifierClause));
         if (match != null)
             return match.SecurityKeys[0];
     }
     return null;
 }
Example #51
0
		public SamlSubject (string nameFormat, string nameQualifier, string name, IEnumerable<string> confirmations, string confirmationData, SecurityKeyIdentifier securityKeyIdentifier)
		{
			if (name == null || name.Length == 0)
				throw new ArgumentException ("non-zero length string must be specified for name of SAML Subject.");
			name_format = nameFormat;
			name_qualifier = nameQualifier;
			this.name = name;

			confirmation_methods = new List<string> (confirmations);
			confirmation_data = confirmationData;
			key_identifier = securityKeyIdentifier;
		}
 private WrappedKeySecurityToken CreateWrappedKeyToken(SecurityToken wrappingToken, SecurityTokenParameters wrappingTokenParameters, SecurityTokenReferenceStyle wrappingTokenReferenceStyle)
 {
     int keyLength = Math.Max(0x80, this.Factory.OutgoingAlgorithmSuite.DefaultSymmetricKeyLength);
     CryptoHelper.ValidateSymmetricKeyLength(keyLength, this.Factory.OutgoingAlgorithmSuite);
     byte[] buffer = new byte[keyLength / 8];
     CryptoHelper.FillRandomBytes(buffer);
     string id = System.ServiceModel.Security.SecurityUtils.GenerateId();
     string defaultAsymmetricKeyWrapAlgorithm = this.Factory.OutgoingAlgorithmSuite.DefaultAsymmetricKeyWrapAlgorithm;
     SecurityKeyIdentifierClause clause = wrappingTokenParameters.CreateKeyIdentifierClause(wrappingToken, wrappingTokenReferenceStyle);
     SecurityKeyIdentifier wrappingTokenReference = new SecurityKeyIdentifier();
     wrappingTokenReference.Add(clause);
     return new WrappedKeySecurityToken(id, buffer, defaultAsymmetricKeyWrapAlgorithm, wrappingToken, wrappingTokenReference);
 }
 public SecurityToken ResolveToken(SecurityKeyIdentifier keyIdentifier)
 {
     if (keyIdentifier == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifier");
     }
     SecurityToken token;
     if (!this.TryResolveTokenCore(keyIdentifier, out token))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.UnableToResolveTokenReference, keyIdentifier)));
     }
     return token;
 }
 public SecurityToken ResolveToken(SecurityKeyIdentifier keyIdentifier)
 {
     SecurityToken token;
     if (keyIdentifier == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifier");
     }
     if (!this.TryResolveTokenCore(keyIdentifier, out token))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(System.IdentityModel.SR.GetString("UnableToResolveTokenReference", new object[] { keyIdentifier })));
     }
     return token;
 }
 internal bool CheckExternalWrapperMatch(SecurityKeyIdentifier keyIdentifier)
 {
     if ((this.expectedWrapper != null) && (this.expectedWrapperTokenParameters != null))
     {
         for (int i = 0; i < keyIdentifier.Count; i++)
         {
             if (this.expectedWrapperTokenParameters.MatchesKeyIdentifierClause(this.expectedWrapper, keyIdentifier[i], SecurityTokenReferenceStyle.External))
             {
                 return true;
             }
         }
     }
     return false;
 }
 public void ReadFrom(XmlDictionaryReader reader, DictionaryManager dictionaryManager)
 {
     reader.MoveToStartElement(dictionaryManager.XmlSignatureDictionary.Signature, dictionaryManager.XmlSignatureDictionary.Namespace);
     this.prefix = reader.Prefix;
     this.Id = reader.GetAttribute(dictionaryManager.UtilityDictionary.IdAttribute, null);
     reader.Read();
     this.signedInfo.ReadFrom(reader, this.signedXml.TransformFactory, dictionaryManager);
     this.signatureValueElement.ReadFrom(reader, dictionaryManager);
     if (this.signedXml.SecurityTokenSerializer.CanReadKeyIdentifier(reader))
     {
         this.keyIdentifier = this.signedXml.SecurityTokenSerializer.ReadKeyIdentifier(reader);
     }
     reader.ReadEndElement();
 }
Example #57
0
        /// <summary>
        /// Generate a sample MetadataBase.
        /// </summary>
        /// <remarks>
        /// In a production system this would be generated from the STS configuration.
        /// </remarks>
        public static MetadataBase GetFederationMetadata()
        {
            string endpointId = "http://localhost:61754/";
            EntityDescriptor metadata = new EntityDescriptor();
            metadata.EntityId = new EntityId(endpointId);

            // Define the signing key
            string signingCertificateName = WebConfigurationManager.AppSettings["SigningCertificateName"];
            X509Certificate2 cert = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, signingCertificateName);
            metadata.SigningCredentials = new X509SigningCredentials(cert);

            // Create role descriptor for security token service
            SecurityTokenServiceDescriptor stsRole = new SecurityTokenServiceDescriptor();
            stsRole.ProtocolsSupported.Add(new Uri(WSFederationMetadataConstants.Namespace));
            metadata.RoleDescriptors.Add(stsRole);

            // Add a contact name
            ContactPerson person = new ContactPerson(ContactType.Administrative);
            person.GivenName = "contactName";
            stsRole.Contacts.Add(person);

            // Include key identifier for signing key in metadata
            SecurityKeyIdentifierClause clause = new X509RawDataKeyIdentifierClause(cert);
            SecurityKeyIdentifier ski = new SecurityKeyIdentifier(clause);
            KeyDescriptor signingKey = new KeyDescriptor(ski);
            signingKey.Use = KeyType.Signing;
            stsRole.Keys.Add(signingKey);

            // Add endpoints
            string activeSTSUrl = "http://localhost:61754/";
            EndpointAddress endpointAddress = new EndpointAddress(new Uri(activeSTSUrl),
                                                                   null,
                                                                   null, GetMetadataReader(activeSTSUrl), null);
            stsRole.SecurityTokenServiceEndpoints.Add(endpointAddress);

            // Add a collection of offered claims
            // NOTE: In this sample, these claims must match the claims actually generated in CustomSecurityTokenService.GetOutputClaimsIdentity.
            //       In a production system, there would be some common data store that both use
            stsRole.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name, "Name", "The name of the subject."));
            stsRole.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Role, "Role", "The role of the subject."));
            // Add a special claim for the QuoteService
            stsRole.ClaimTypesOffered.Add(new DisplayClaim(QuotationClassClaimType, "QuotationClass", "Class of quotation desired."));

            return metadata;
        }
        /// <summary>
        /// Override of the base class. Resolves the given SecurityKeyIdentifier to a 
        /// SecurityToken.
        /// </summary>
        /// <param name="keyIdentifier">The KeyIdentifier to be resolved.</param>
        /// <param name="token">The resolved SecurityToken</param>
        /// <returns>True if successfully resolved.</returns>
        /// <exception cref="ArgumentNullException">Input argument 'keyIdentifier' is null.</exception>
        protected override bool TryResolveTokenCore( SecurityKeyIdentifier keyIdentifier, out SecurityToken token )
        {
            if ( keyIdentifier == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "keyIdentifer" );
            }

            token = null;
            foreach ( SecurityTokenResolver tokenResolver in _tokenResolvers )
            {
                if ( tokenResolver.TryResolveToken( keyIdentifier, out token ) )
                {
                    return true;
                }
            }

            return false;
        }
 public virtual ClaimSet ResolveClaimSet(SecurityKeyIdentifier keyIdentifier)
 {
     RsaKeyIdentifierClause clause;
     EncryptedKeyIdentifierClause clause2;
     if (keyIdentifier == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifier");
     }
     if (keyIdentifier.TryFind<RsaKeyIdentifierClause>(out clause))
     {
         return new DefaultClaimSet(new Claim[] { new Claim(ClaimTypes.Rsa, clause.Rsa, Rights.PossessProperty) });
     }
     if (keyIdentifier.TryFind<EncryptedKeyIdentifierClause>(out clause2))
     {
         return new DefaultClaimSet(new Claim[] { Claim.CreateHashClaim(clause2.GetBuffer()) });
     }
     return null;
 }
 public SigningCredentials(SecurityKey signingKey, string signatureAlgorithm, string digestAlgorithm, SecurityKeyIdentifier signingKeyIdentifier)
 {
     if (signingKey == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("signingKey"));
     }
     if (signatureAlgorithm == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("signatureAlgorithm"));
     }
     if (digestAlgorithm == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("digestAlgorithm"));
     }
     this.signingKey = signingKey;
     this.signatureAlgorithm = signatureAlgorithm;
     this.digestAlgorithm = digestAlgorithm;
     this.signingKeyIdentifier = signingKeyIdentifier;
 }