/// <summary>
        /// Gets the name of the issuer.
        /// </summary>
        /// <param name="securityToken">The security token.</param>
        /// <returns></returns>
        public override string GetIssuerName(SecurityToken securityToken)
        {
            if (securityToken == null)
            {
                Tracing.Error("SimpleIssuerNameRegistry: securityToken is null");
                throw new ArgumentNullException("securityToken");
            }

            X509SecurityToken token = securityToken as X509SecurityToken;

            if (token != null)
            {
                Tracing.Information("SimpleIssuerNameRegistry: X509 SubjectName: " + token.Certificate.SubjectName.Name);
                Tracing.Information("SimpleIssuerNameRegistry: X509 Thumbprint : " + token.Certificate.Thumbprint);
                return(token.Certificate.Thumbprint);
            }

            RsaSecurityToken token2 = securityToken as RsaSecurityToken;

            if (token2 == null)
            {
                throw new SecurityTokenException(securityToken.GetType().FullName);
            }

            Tracing.Information("SimpleIssuerNameRegistry: RSA Key: " + token2.Rsa.ToXmlString(false));
            return(token2.Rsa.ToXmlString(false));
        }
        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 #3
0
        protected override SecurityKeyIdentifierClause CreateKeyIdentifierClause(
            SecurityToken token, SecurityTokenReferenceStyle referenceStyle)
        {
            RsaSecurityToken r = token as RsaSecurityToken;

            return(r.CreateKeyIdentifierClause <RsaKeyIdentifierClause> ());
        }
Example #4
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);
 }
Example #5
0
            // This is to address RSACryptoServiceProvider finalizer exception issue
            // Step 1. Create Rsa and force deterministic keypair gen in this calling context.
            // Step 2. Cache if the calling thread is under impersonation context.  The cache will
            // be disposed on Close/Abort assuming same calling context thread as the one calling open.
            RsaSecurityToken CreateAndCacheRsaSecurityToken()
            {
                RsaSecurityToken token;

                // Cache only under impersonation context.
                // 1) set cacheSize less than 0, to ignore this new behavior at all.
                // 2) set cacheSize to 0, if token provider should not dispose issued tokens on close/abort.
                // 3) other than that, the token provider will track and dispose issued tokens as much.
                if (MaxRsaSecurityTokenCacheSize >= 0 && IsImpersonatedContext())
                {
                    // This will force deterministic keypair gen in this context.
                    token = RsaSecurityToken.CreateSafeRsaSecurityToken(this.keySize);
                    if (MaxRsaSecurityTokenCacheSize > 0)
                    {
                        lock (this.rsaSecurityTokens)
                        {
                            // Remove/Dispose the first token if cache is full.
                            // The first token (if not disposed) will rely on GC for finalization.
                            if (this.rsaSecurityTokens.Count >= MaxRsaSecurityTokenCacheSize)
                            {
                                this.rsaSecurityTokens.RemoveAt(0);
                            }
                            this.rsaSecurityTokens.Add(token);
                        }
                    }
                }
                else
                {
                    token = new RsaSecurityToken(new RSACryptoServiceProvider(this.keySize));
                }
                return(token);
            }
 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 #7
0
        public void ValidateJsonWebToken(string tokenString, SsoSettings settings, IList <string> audiences)
        {
            try
            {
                TokenString = tokenString;
                SecurityToken securityToken;
                log.DebugFormat("Jwt Validation securityAlgorithm={0}, audience[0]={1}, audience[1]={2}", settings.ValidationType, audiences[0], audiences[1]);

                switch (settings.ValidationType)
                {
                case ValidationTypes.RSA_SHA256:
                    RSACryptoServiceProvider publicOnly = new RSACryptoServiceProvider();
                    //"<RSAKeyValue><Modulus>zeyPa4SwRb0IO+KMq20760ZmaUvy/qzecdOkRUNdNpdUe1E72Xt1WkAcWNu24/UeS3pETu08rVTqHJUMfhHcSKgL7LAk/MMj2inGFxop1LipGZSnqZhnjsfj1ERJL5eXs1O9hqyAcXvY4A2wo67qqv/lbHLKTW59W+YQkbIOVR4nQlbh1lK1TIY+oqK0J/5Ileb4QfERn0Rv/J/K0fy6VzLmVt+kg9MRNxYwnVsC3m5/kIu1fw3OpZxcaCC68SRqLLb/UXmaJM8NXYKkAkHKxT4DQqSk6KbFSQG6qi49Q34akohekzxjxmmGeoO5tsFCuMJofKAsBKKtOkLPaJD2rQ==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"
                    publicOnly.FromXmlString(settings.PublicKey);
                    securityToken = new RsaSecurityToken(publicOnly);
                    break;

                case ValidationTypes.HMAC_SHA256:
                    //var key = "zeyPa4SwRb0IO+KMq20760ZmaUvy/qzecdOkRUNdNpdUe1E72Xu24/UeS3pETu";
                    securityToken = new System.ServiceModel.Security.Tokens.BinarySecretSecurityToken(GetBytes(settings.PublicKey));
                    break;

                case ValidationTypes.X509:
                    var certificate = new Certificate();
                    certificate.LoadCertificate(settings.PublicKey);
                    securityToken = new X509SecurityToken(certificate.Cert);
                    break;

                default:
                    log.ErrorFormat("ValidationType has wrong value: {0}", settings.ValidationType);
                    throw new ArgumentException("ValidationType has wrong value");
                }
                TokenValidationParameters validationParams = new TokenValidationParameters
                {
                    ValidIssuer              = settings.Issuer,
                    ValidAudiences           = audiences,
                    ValidateIssuer           = true,
                    ValidateIssuerSigningKey = true,
                    ValidateAudience         = true,
                    ValidateActor            = true,
                    IssuerSigningToken       = securityToken
                };

                JwtSecurityTokenHandler recipientTokenHandler = new JwtSecurityTokenHandler
                {
                    TokenLifetimeInMinutes = MaxClockSkew
                };
                SecurityToken validatedToken;
                ClaimsPrincipalReceived = recipientTokenHandler.ValidateToken(TokenString, validationParams, out validatedToken);
                JwtSecurityToken        = validatedToken;
            }
            catch (Exception e)
            {
                log.ErrorFormat("Jwt Validation error. {0}", e);
            }
        }
Example #8
0
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
        {
            RsaSecurityToken rsaToken = (RsaSecurityToken)token;
            List <Claim>     claims   = new List <Claim>(2);

            claims.Add(new Claim(ClaimTypes.Rsa, rsaToken.Rsa, Rights.Identity));
            claims.Add(Claim.CreateRsaClaim(rsaToken.Rsa));

            DefaultClaimSet             claimSet = new DefaultClaimSet(ClaimSet.Anonymous, claims);
            List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>(1);

            policies.Add(new UnconditionalPolicy(claimSet, rsaToken.ValidTo));
            return(policies.AsReadOnly());
        }
        public void ValidateJsonWebToken(string tokenString, SsoSettings settings, IList<string> audiences)
        {
            try
            {

                TokenString = tokenString;
                SecurityToken securityToken;
                _log.DebugFormat("JWT Validation securityAlgorithm={0}, audience[0]={1}, audience[1]={2}", settings.ValidationType, audiences[0], audiences[1]);

                switch (settings.ValidationType)
                {
                    case ValidationTypes.RSA_SHA256:
                        RSACryptoServiceProvider publicOnly = new RSACryptoServiceProvider();
                        //"<RSAKeyValue><Modulus>zeyPa4SwRb0IO+KMq20760ZmaUvy/qzecdOkRUNdNpdUe1E72Xt1WkAcWNu24/UeS3pETu08rVTqHJUMfhHcSKgL7LAk/MMj2inGFxop1LipGZSnqZhnjsfj1ERJL5eXs1O9hqyAcXvY4A2wo67qqv/lbHLKTW59W+YQkbIOVR4nQlbh1lK1TIY+oqK0J/5Ileb4QfERn0Rv/J/K0fy6VzLmVt+kg9MRNxYwnVsC3m5/kIu1fw3OpZxcaCC68SRqLLb/UXmaJM8NXYKkAkHKxT4DQqSk6KbFSQG6qi49Q34akohekzxjxmmGeoO5tsFCuMJofKAsBKKtOkLPaJD2rQ==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"
                        publicOnly.FromXmlString(settings.PublicKey);
                        securityToken = new RsaSecurityToken(publicOnly);
                        break;
                    case ValidationTypes.HMAC_SHA256:
                        //var key = "zeyPa4SwRb0IO+KMq20760ZmaUvy/qzecdOkRUNdNpdUe1E72Xu24/UeS3pETu";
                        securityToken = new System.ServiceModel.Security.Tokens.BinarySecretSecurityToken(GetBytes(settings.PublicKey));
                        break;
                    case ValidationTypes.X509:
                        var certificate = new Certificate();
                        certificate.LoadCertificate(settings.PublicKey);
                        securityToken = new X509SecurityToken(certificate.cert);
                        break;
                    default:
                        _log.ErrorFormat("ValidationType has wrong value: {0}", settings.ValidationType);
                        throw new ArgumentException("ValidationType has wrong value");
                }
                TokenValidationParameters validationParams = new TokenValidationParameters();
                validationParams.ValidIssuer = settings.Issuer;
                validationParams.ValidAudiences = audiences;
                validationParams.ValidateIssuer = true;
                validationParams.ValidateIssuerSigningKey = true;
                validationParams.ValidateAudience = true;
                validationParams.ValidateActor = true;
                validationParams.IssuerSigningToken = securityToken;

                JwtSecurityTokenHandler recipientTokenHandler = new JwtSecurityTokenHandler();
                recipientTokenHandler.TokenLifetimeInMinutes = MAX_CLOCK_SKEW;
                SecurityToken validatedToken = null;
                ClaimsPrincipalReceived = recipientTokenHandler.ValidateToken(TokenString, validationParams, out validatedToken);
                JwtSecurityToken = validatedToken;
            }
            catch (Exception e)
            {
                _log.ErrorFormat("JWT Validation error. {0}", e);
            }
        }
        ValidateTokenCore(SecurityToken token)
        {
            RsaSecurityToken rt = token as RsaSecurityToken;

            if (rt == null)
            {
                throw new InvalidOperationException("Security token '{0}' cannot be validated by this security token authenticator.");
            }

            IAuthorizationPolicy policy =
                new RsaAuthorizationPolicy(rt.Rsa);

            return(new ReadOnlyCollection <IAuthorizationPolicy> (new IAuthorizationPolicy [] { policy }));
        }
Example #11
0
        protected override void WriteTokenCore(XmlWriter w, SecurityToken token)
        {
            RsaSecurityToken r = token as RsaSecurityToken;

            w.Flush();
            if (r != null)
            {
                w.WriteRaw(r.Rsa.ToXmlString(false));
            }
            else
            {
                base.WriteTokenCore(w, token);
            }
        }
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
        {
            RsaSecurityToken token2 = (RsaSecurityToken)token;
            List <Claim>     claims = new List <Claim>(2)
            {
                new Claim(ClaimTypes.Rsa, token2.Rsa, Rights.Identity),
                Claim.CreateRsaClaim(token2.Rsa)
            };
            DefaultClaimSet issuance = new DefaultClaimSet(ClaimSet.Anonymous, claims);

            return(new List <IAuthorizationPolicy>(1)
            {
                new UnconditionalPolicy(issuance, token2.ValidTo)
            }.AsReadOnly());
        }
Example #13
0
        protected override SecurityKeyIdentifierClause CreateKeyIdentifierClause(
            SecurityToken token, SecurityTokenReferenceStyle referenceStyle)
        {
            if (token == null)
            {
                throw new ArgumentNullException("token");
            }
            RsaSecurityToken rt = token as RsaSecurityToken;

            if (rt == null)
            {
                throw new NotSupportedException(String.Format("Cannot create a key identifier clause from this security token '{0}'", token));
            }
            return(new RsaKeyIdentifierClause(rt.Rsa));
        }
Example #14
0
 private RsaSecurityToken CreateAndCacheRsaSecurityToken()
 {
     if ((MaxRsaSecurityTokenCacheSize >= 0) && this.IsImpersonatedContext())
     {
         RsaSecurityToken item = RsaSecurityToken.CreateSafeRsaSecurityToken(this.keySize);
         if (MaxRsaSecurityTokenCacheSize <= 0)
         {
             return(item);
         }
         lock (this.rsaSecurityTokens)
         {
             if (this.rsaSecurityTokens.Count >= MaxRsaSecurityTokenCacheSize)
             {
                 this.rsaSecurityTokens.RemoveAt(0);
             }
             this.rsaSecurityTokens.Add(item);
             return(item);
         }
     }
     return(new RsaSecurityToken(new RSACryptoServiceProvider(this.keySize)));
 }
        // Methods of BodyWriter
        /// <summary>
        /// Writes out an XML representation of the instance.
        /// </summary>
        /// <param name="writer">The writer to be used to write out the XML content</param>
        protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
        {
            // Write out the wst:RequestSecurityToken start tag
            writer.WriteStartElement(Constants.Trust.Elements.RequestSecurityToken, Constants.Trust.NamespaceUri);

            // If we have a non-null, non-empty tokenType...
            if (this.tokenType != null && this.tokenType.Length > 0)
            {
                // Write out the wst:TokenType start tag
                writer.WriteStartElement(Constants.Trust.Elements.TokenType, Constants.Trust.NamespaceUri);
                // Write out the tokenType string
                writer.WriteString(this.tokenType);
                writer.WriteEndElement(); // wst:TokenType
            }

            // If we have a non-null, non-empty requestType...
            if (this.requestType != null && this.requestType.Length > 0)
            {
                // Write out the wst:RequestType start tag
                writer.WriteStartElement(Constants.Trust.Elements.RequestType, Constants.Trust.NamespaceUri);
                // Write out the requestType string
                writer.WriteString(this.requestType);
                writer.WriteEndElement(); // wst:RequestType
            }

            // If we have a non-null appliesTo
            if (this.appliesTo != null)
            {
                // Write out the wsp:AppliesTo start tag
                writer.WriteStartElement(Constants.Policy.Elements.AppliesTo, Constants.Policy.NamespaceUri);
                // Write the appliesTo in WS-Addressing 1.0 format
                this.appliesTo.WriteTo(AddressingVersion.WSAddressing10, writer);
                writer.WriteEndElement(); // wsp:AppliesTo
            }

            if (this.requestorEntropy != null)
            {
                writer.WriteStartElement(Constants.Trust.Elements.Entropy, Constants.Trust.NamespaceUri);
                BinarySecretSecurityToken bsst = this.requestorEntropy as BinarySecretSecurityToken;
                if (bsst != null)
                {
                    writer.WriteStartElement(Constants.Trust.Elements.BinarySecret, Constants.Trust.NamespaceUri);
                    byte[] key = bsst.GetKeyBytes();
                    writer.WriteBase64(key, 0, key.Length);
                    writer.WriteEndElement(); // wst:BinarySecret
                }
                writer.WriteEndElement();     // wst:Entropy
            }

            if (this.keyType != null && this.keyType.Length > 0)
            {
                writer.WriteStartElement(Constants.Trust.Elements.KeyType, Constants.Trust.NamespaceUri);
                writer.WriteString(this.keyType);
                writer.WriteEndElement(); // wst:KeyType
            }

            if (this.keySize > 0)
            {
                writer.WriteStartElement(Constants.Trust.Elements.KeySize, Constants.Trust.NamespaceUri);
                writer.WriteValue(this.keySize);
                writer.WriteEndElement(); // wst:KeySize
            }

            if (this.proofKey != null && this.IsProofKeyAsymmetric())
            {
                writer.WriteStartElement(Constants.Trust.Elements.UseKey, Constants.Trust.NamespaceUri);
                writer.WriteStartElement(Constants.XmlDSig.Elements.KeyInfo, Constants.XmlDSig.NamespaceUri);
                writer.WriteStartElement(Constants.XmlDSig.Elements.KeyValue, Constants.XmlDSig.NamespaceUri);
                RsaSecurityToken rsa = proofKey as RsaSecurityToken;

                if (rsa != null)
                {
                    RSAParameters p = rsa.Rsa.ExportParameters(false);
                    writer.WriteStartElement(Constants.XmlDSig.Elements.RsaKeyValue, Constants.XmlDSig.NamespaceUri);
                    writer.WriteStartElement(Constants.XmlDSig.Elements.Modulus, Constants.XmlDSig.NamespaceUri);
                    byte[] modulus = p.Modulus;
                    writer.WriteBase64(modulus, 0, modulus.Length);
                    writer.WriteEndElement(); // ds:Modulus
                    writer.WriteStartElement(Constants.XmlDSig.Elements.Exponent, Constants.XmlDSig.NamespaceUri);
                    byte[] exp = p.Exponent;
                    writer.WriteBase64(exp, 0, exp.Length);
                    writer.WriteEndElement(); // ds:Exponent
                    writer.WriteEndElement(); // ds:RsaKeyValue
                }

                writer.WriteEndElement(); // ds:KeyValue
                writer.WriteEndElement(); // ds:KeyInfo
                writer.WriteEndElement(); // wst:UseKey
            }

            if (this.claimReqs != null && this.claimReqs.Count > 0)
            {
                writer.WriteStartElement(Constants.Trust.Elements.Claims, Constants.Trust.NamespaceUri);

                foreach (ClaimTypeRequirement ctr in this.claimReqs)
                {
                    writer.WriteStartElement(Constants.IdentityModel.Elements.Claim, Constants.IdentityModel.NamespaceUri);
                    writer.WriteAttributeString(Constants.IdentityModel.Attributes.Uri, ctr.ClaimType);

                    if (ctr.IsOptional)
                    {
                        writer.WriteAttributeString(Constants.IdentityModel.Attributes.Optional, "true");
                    }

                    writer.WriteEndElement(); // wsid:Claim
                }

                writer.WriteEndElement(); // wst:Claims
            }

            writer.WriteEndElement(); // wst:RequestSecurityToken
        }
Example #16
0
        // This method assumes that the XmlReader is positioned on the start tag of ds:RsaKeyValue
        private static SecurityToken ProcessRsaKeyValueElement(XmlReader xr)
        {
            int initialDepth = xr.Depth;

            if (xr.IsEmptyElement)
                throw new Exception("ds:RsaKeyValue element was empty. Unable to create SecurityToken object");

            SecurityToken st = null;
            StringBuilder rsaXmlString = new StringBuilder();
            rsaXmlString.Append("<RSAKeyValue>");

            while (xr.Read())
            {                
                // Process element start tags
                if (XmlNodeType.Element == xr.NodeType)
                {
                    // Process XMLDSIG elements
                    if (Constants.XmlDSig.NamespaceUri == xr.NamespaceURI)
                    {
                        if (Constants.XmlDSig.Elements.Modulus == xr.LocalName &&
                            !xr.IsEmptyElement)
                        {
                            rsaXmlString.Append("<Modulus>");
                            xr.Read();
                            rsaXmlString.Append(xr.ReadContentAsString());
                            rsaXmlString.Append("</Modulus>");
                        }
                        else if (Constants.XmlDSig.Elements.Exponent == xr.LocalName &&
                                 !xr.IsEmptyElement)
                        {
                            rsaXmlString.Append("<Exponent>");
                            xr.Read();
                            rsaXmlString.Append(xr.ReadContentAsString());
                            rsaXmlString.Append("</Exponent>");
                        }
                        else
                        {
                            Console.WriteLine("Not processing element: {0}:{1}", xr.NamespaceURI, xr.LocalName);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Not processing element: {0}:{1}", xr.NamespaceURI, xr.LocalName);
                    }
                }

                if (Constants.XmlDSig.Elements.RsaKeyValue == xr.LocalName &&
                    Constants.XmlDSig.NamespaceUri == xr.NamespaceURI &&
                    xr.Depth == initialDepth &&
                    XmlNodeType.EndElement == xr.NodeType)
                    break;
            }

            rsaXmlString.Append("</RSAKeyValue>");
            RSA key = RSA.Create();
            key.FromXmlString(rsaXmlString.ToString());
            st = new RsaSecurityToken(key);

            return st;
        }
Example #17
0
 public FederatedTokenProviderState(RsaSecurityToken rsaToken)
     : base(null)
 {
     this.rsaToken = rsaToken;
 }
        /// <summary>
        /// Inherited from <see cref="SecurityTokenResolver"/>.
        /// </summary>
        protected override bool TryResolveTokenCore( SecurityKeyIdentifierClause keyIdentifierClause, out SecurityToken token )
        {
            if ( keyIdentifierClause == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "keyIdentifierClause" );
            }

            token = null;

            //
            // Try raw X509
            //
            X509RawDataKeyIdentifierClause rawDataClause = keyIdentifierClause as X509RawDataKeyIdentifierClause;
            if ( rawDataClause != null )
            {
                token = new X509SecurityToken( new X509Certificate2( rawDataClause.GetX509RawData() ) );
                return true;
            }

            //
            // Try RSA
            //
            RsaKeyIdentifierClause rsaClause = keyIdentifierClause as RsaKeyIdentifierClause;
            if ( rsaClause != null )
            {
                token = new RsaSecurityToken( rsaClause.Rsa );
                return true;
            }

            if ( _wrappedTokenResolver.TryResolveToken( keyIdentifierClause, out token ) )
            {
                return true;
            }
            
            return false;
        }
		public void WriteRsaSecurityToken ()
		{
			StringWriter sw = new StringWriter ();
			RSA rsa = (RSA) cert.PublicKey.Key;
			RsaSecurityToken t = new RsaSecurityToken (rsa, "urn:rsa:1");
			using (XmlWriter w = XmlWriter.Create (sw, GetWriterSettings ())) {
				WSSecurityTokenSerializer.DefaultInstance.WriteToken (w, t);
			}
		}
        internal static SecurityToken ResolveSecurityToken(SecurityKeyIdentifier ski, SecurityTokenResolver tokenResolver)
        {
            SecurityToken token = null;

            if (tokenResolver != null)
            {
                tokenResolver.TryResolveToken(ski, out token);
            }

            if (token == null)
            {
                // Check if this is a RSA key.
                RsaKeyIdentifierClause rsaClause;
                if (ski.TryFind<RsaKeyIdentifierClause>(out rsaClause))
                    token = new RsaSecurityToken(rsaClause.Rsa);
            }

            if (token == null)
            {
                // Check if this is a X509RawDataKeyIdentifier Clause.
                X509RawDataKeyIdentifierClause rawDataKeyIdentifierClause;
                if (ski.TryFind<X509RawDataKeyIdentifierClause>(out rawDataKeyIdentifierClause))
                    token = new X509SecurityToken(new X509Certificate2(rawDataKeyIdentifierClause.GetX509RawData()));
            }

            return token;
        }
 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;
 }
 SecurityToken ResolveSignatureToken(SecurityKeyIdentifier keyIdentifier, SecurityTokenResolver resolver, bool isPrimarySignature)
 {
     SecurityToken token;
     TryResolveKeyIdentifier(keyIdentifier, resolver, true, out token);
     if (token == null && !isPrimarySignature)
     {
         // check if there is a rsa key token authenticator
         if (keyIdentifier.Count == 1)
         {
             RsaKeyIdentifierClause rsaClause;
             if (keyIdentifier.TryFind<RsaKeyIdentifierClause>(out rsaClause))
             {
                 RsaSecurityTokenAuthenticator rsaAuthenticator = FindAllowedAuthenticator<RsaSecurityTokenAuthenticator>(false);
                 if (rsaAuthenticator != null)
                 {
                     token = new RsaSecurityToken(rsaClause.Rsa);
                     ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = rsaAuthenticator.ValidateToken(token);
                     SupportingTokenAuthenticatorSpecification spec;
                     TokenTracker rsaTracker = GetSupportingTokenTracker(rsaAuthenticator, out spec);
                     if (rsaTracker == null)
                     {
                         throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.UnknownTokenAuthenticatorUsedInTokenProcessing, rsaAuthenticator)));
                     }
                     rsaTracker.RecordToken(token);
                     SecurityTokenAuthorizationPoliciesMapping.Add(token, authorizationPolicies);
                 }
             }
         }
     }
     if (token == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
                 SR.GetString(SR.UnableToResolveKeyInfoForVerifyingSignature, keyIdentifier, resolver)));
     }
     return token;
 }
 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;
 }
        // This method assumes that the XmlReader is positioned on the start tag of ds:RsaKeyValue
        private static SecurityToken ProcessRsaKeyValueElement(XmlReader xr)
        {
            int initialDepth = xr.Depth;

            if (xr.IsEmptyElement)
            {
                throw new Exception("ds:RsaKeyValue element was empty. Unable to create SecurityToken object");
            }

            SecurityToken st           = null;
            StringBuilder rsaXmlString = new StringBuilder();

            rsaXmlString.Append("<RSAKeyValue>");

            while (xr.Read())
            {
                // Process element start tags
                if (XmlNodeType.Element == xr.NodeType)
                {
                    // Process XMLDSIG elements
                    if (Constants.XmlDSig.NamespaceUri == xr.NamespaceURI)
                    {
                        if (Constants.XmlDSig.Elements.Modulus == xr.LocalName &&
                            !xr.IsEmptyElement)
                        {
                            rsaXmlString.Append("<Modulus>");
                            xr.Read();
                            rsaXmlString.Append(xr.ReadContentAsString());
                            rsaXmlString.Append("</Modulus>");
                        }
                        else if (Constants.XmlDSig.Elements.Exponent == xr.LocalName &&
                                 !xr.IsEmptyElement)
                        {
                            rsaXmlString.Append("<Exponent>");
                            xr.Read();
                            rsaXmlString.Append(xr.ReadContentAsString());
                            rsaXmlString.Append("</Exponent>");
                        }
                        else
                        {
                            Console.WriteLine("Not processing element: {0}:{1}", xr.NamespaceURI, xr.LocalName);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Not processing element: {0}:{1}", xr.NamespaceURI, xr.LocalName);
                    }
                }

                if (Constants.XmlDSig.Elements.RsaKeyValue == xr.LocalName &&
                    Constants.XmlDSig.NamespaceUri == xr.NamespaceURI &&
                    xr.Depth == initialDepth &&
                    XmlNodeType.EndElement == xr.NodeType)
                {
                    break;
                }
            }

            rsaXmlString.Append("</RSAKeyValue>");
            RSA key = RSA.Create();

            key.FromXmlString(rsaXmlString.ToString());
            st = new RsaSecurityToken(key);

            return(st);
        }
 internal static SecurityToken ResolveSecurityToken(SecurityKeyIdentifier ski, SecurityTokenResolver tokenResolver)
 {
     SecurityToken token = null;
     RsaKeyIdentifierClause clause;
     X509RawDataKeyIdentifierClause clause2;
     if (tokenResolver != null)
     {
         tokenResolver.TryResolveToken(ski, out token);
     }
     if ((token == null) && ski.TryFind<RsaKeyIdentifierClause>(out clause))
     {
         token = new RsaSecurityToken(clause.Rsa);
     }
     if ((token == null) && ski.TryFind<X509RawDataKeyIdentifierClause>(out clause2))
     {
         token = new X509SecurityToken(new X509Certificate2(clause2.GetX509RawData()));
     }
     return token;
 }