示例#1
0
        /// <summary>
        /// Converts the ListenUri in the <see cref="SecurityTokenRequirement"/> to a normalized string.
        /// The method preserves the Uri scheme, port and absolute path and replaces the host name
        /// with the string 'NormalizedHostName'.
        /// </summary>
        /// <param name="tokenRequirement">The <see cref="SecurityTokenRequirement"/> which contains the 'ListenUri' property.</param>
        /// <returns>A string representing the Normalized URI string.</returns>
        public static string GetNormalizedEndpointId(SecurityTokenRequirement tokenRequirement)
        {
            if (tokenRequirement == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenRequirement");
            }

            Uri listenUri = null;

            if (tokenRequirement.Properties.ContainsKey(ListenUriProperty))
            {
                listenUri = tokenRequirement.Properties[ListenUriProperty] as Uri;
            }

            if (listenUri == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4287, tokenRequirement));
            }

            if (listenUri.IsDefaultPort)
            {
                return(String.Format(CultureInfo.InvariantCulture, "{0}://NormalizedHostName{1}", listenUri.Scheme, listenUri.AbsolutePath));
            }
            else
            {
                return(String.Format(CultureInfo.InvariantCulture, "{0}://NormalizedHostName:{1}{2}", listenUri.Scheme, listenUri.Port, listenUri.AbsolutePath));
            }
        }
示例#2
0
 public static string GetString(string name)
 {
     System.ServiceModel.SR loader = GetLoader();
     if (loader == null)
     {
         return(null);
     }
     return(loader.resources.GetString(name, Culture));
 }
示例#3
0
 private static System.ServiceModel.SR GetLoader()
 {
     if (loader == null)
     {
         System.ServiceModel.SR sr = new System.ServiceModel.SR();
         Interlocked.CompareExchange <System.ServiceModel.SR>(ref loader, sr, null);
     }
     return(loader);
 }
示例#4
0
        public void UpdateContextCachingTime(SecurityContextSecurityToken token, DateTime expirationTime)
        {
            if (token.ValidTo <= expirationTime.ToUniversalTime())
            {
                return;
            }

            SessionSecurityTokenCacheKey key          = new SessionSecurityTokenCacheKey(_claimsHandler.EndpointId, token.ContextId, token.KeyGeneration);
            SessionSecurityToken         sessionToken = SecurityContextSecurityTokenHelper.ConvertSctToSessionToken(token, SecureConversationVersion.Default);
            DateTime expiryTime = DateTimeUtil.Add(sessionToken.ValidTo, _claimsHandler.SecurityTokenHandlerCollection.Configuration.MaxClockSkew);

            if (_tokenCache.Get(key) == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4285, sessionToken.ContextId.ToString()));
            }
            _tokenCache.AddOrUpdate(key, sessionToken, expiryTime);
        }
        public override IChannelFactory <TChannel> BuildChannelFactory <TChannel>(BindingContext context)
        {
            if (context == null)
            {
                throw FxTrace.Exception.ArgumentNull("context");
            }

            if (!this.CanBuildChannelFactory <TChannel>(context.Clone()))
            {
                throw FxTrace.Exception.Argument("TChannel", SR2.GetString(SR2.ChannelTypeNotSupported, typeof(TChannel)));
            }

            IChannelFactory <TChannel> innerFactory = context.BuildInnerChannelFactory <TChannel>();

            if (innerFactory != null)
            {
                return(new SynchronousChannelFactory <TChannel>(context.Binding, innerFactory));
            }
            return(null);
        }
示例#6
0
        public static string GetString(string name, params object[] args)
        {
            System.ServiceModel.SR loader = GetLoader();
            if (loader == null)
            {
                return(null);
            }
            string format = loader.resources.GetString(name, Culture);

            if ((args == null) || (args.Length <= 0))
            {
                return(format);
            }
            for (int i = 0; i < args.Length; i++)
            {
                string str2 = args[i] as string;
                if ((str2 != null) && (str2.Length > 0x400))
                {
                    args[i] = str2.Substring(0, 0x3fd) + "...";
                }
            }
            return(string.Format(CultureInfo.CurrentCulture, format, args));
        }
示例#7
0
        /// <summary>
        /// This method creates a SAML security token authenticator when token type is null.
        /// It wraps the SAML 1.1 and the SAML 2.0 token handlers that are configured.
        /// If no token handler was found, then the inner token manager is created.
        /// </summary>
        SecurityTokenAuthenticator CreateSamlSecurityTokenAuthenticator(SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver)
        {
            outOfBandTokenResolver = null;

            SecurityTokenAuthenticator securityTokenAuthenticator = null;

            SamlSecurityTokenHandler  saml11SecurityTokenHandler = _securityTokenHandlerCollection[SecurityTokenTypes.SamlTokenProfile11] as SamlSecurityTokenHandler;
            Saml2SecurityTokenHandler saml2SecurityTokenHandler  = _securityTokenHandlerCollection[SecurityTokenTypes.Saml2TokenProfile11] as Saml2SecurityTokenHandler;

            if (saml11SecurityTokenHandler != null && saml11SecurityTokenHandler.Configuration == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274));
            }

            if (saml2SecurityTokenHandler != null && saml2SecurityTokenHandler.Configuration == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274));
            }

            if (saml11SecurityTokenHandler != null && saml2SecurityTokenHandler != null)
            {
                //
                // Both SAML 1.1 and SAML 2.0 token handlers have been configured.
                //

                WrappedSaml11SecurityTokenAuthenticator wrappedSaml11SecurityTokenAuthenticator = new WrappedSaml11SecurityTokenAuthenticator(saml11SecurityTokenHandler, _exceptionMapper);
                WrappedSaml2SecurityTokenAuthenticator  wrappedSaml2SecurityTokenAuthenticator  = new WrappedSaml2SecurityTokenAuthenticator(saml2SecurityTokenHandler, _exceptionMapper);

                securityTokenAuthenticator = new WrappedSamlSecurityTokenAuthenticator(wrappedSaml11SecurityTokenAuthenticator, wrappedSaml2SecurityTokenAuthenticator);

                // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
                List <SecurityTokenResolver> resolvers = new List <SecurityTokenResolver>();
                resolvers.Add(saml11SecurityTokenHandler.Configuration.ServiceTokenResolver);
                resolvers.Add(saml2SecurityTokenHandler.Configuration.ServiceTokenResolver);
                outOfBandTokenResolver = new AggregateTokenResolver(resolvers);
            }
            else if (saml11SecurityTokenHandler == null && saml2SecurityTokenHandler != null)
            {
                //
                // SAML 1.1 token handler is not present but SAML 2.0 is. Set the token type to SAML 2.0
                //

                securityTokenAuthenticator = new WrappedSaml2SecurityTokenAuthenticator(saml2SecurityTokenHandler, _exceptionMapper);

                // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
                outOfBandTokenResolver = saml2SecurityTokenHandler.Configuration.ServiceTokenResolver;
            }
            else if (saml11SecurityTokenHandler != null && saml2SecurityTokenHandler == null)
            {
                //
                // SAML 1.1 token handler is present but SAML 2.0 is not. Set the token type to SAML 1.1
                //

                securityTokenAuthenticator = new WrappedSaml11SecurityTokenAuthenticator(saml11SecurityTokenHandler, _exceptionMapper);

                // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
                outOfBandTokenResolver = saml11SecurityTokenHandler.Configuration.ServiceTokenResolver;
            }
            else
            {
                securityTokenAuthenticator = CreateInnerSecurityTokenAuthenticator(tokenRequirement, out outOfBandTokenResolver);
            }

            return(securityTokenAuthenticator);
        }
示例#8
0
        /// <summary>
        /// Overriden from the base class. Creates the requested Token Authenticator.
        /// Looks up the list of Token Handlers registered with the token Manager
        /// based on the TokenType Uri in the SecurityTokenRequirement. If none is found,
        /// then the call is delegated to the inner Token Manager.
        /// </summary>
        /// <param name="tokenRequirement">Security Token Requirement for which the Authenticator should be created.</param>
        /// <param name="outOfBandTokenResolver">Token resolver that resolves any out-of-band tokens.</param>
        /// <returns>Instance of Security Token Authenticator.</returns>
        /// <exception cref="ArgumentNullException">'tokenRequirement' parameter is null.</exception>
        /// <exception cref="NotSupportedException">No Authenticator is registered for the given token type.</exception>
        public override SecurityTokenAuthenticator CreateSecurityTokenAuthenticator(SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver)
        {
            if (tokenRequirement == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenRequirement");
            }

            outOfBandTokenResolver = null;

            // Check for a registered authenticator
            SecurityTokenAuthenticator securityTokenAuthenticator = null;

            string tokenType = tokenRequirement.TokenType;

            //
            // When the TokenRequirement.TokenType is null, we treat this as a SAML issued token case. It may be SAML 1.1 or SAML 2.0.
            //
            if (String.IsNullOrEmpty(tokenType))
            {
                return(CreateSamlSecurityTokenAuthenticator(tokenRequirement, out outOfBandTokenResolver));
            }

            //
            // When the TokenType is set, build a token authenticator for the specified token type.
            //
            SecurityTokenHandler securityTokenHandler = _securityTokenHandlerCollection[tokenType];

            if ((securityTokenHandler != null) && (securityTokenHandler.CanValidateToken))
            {
                outOfBandTokenResolver = GetDefaultOutOfBandTokenResolver();

                if (StringComparer.Ordinal.Equals(tokenType, SecurityTokenTypes.UserName))
                {
                    UserNameSecurityTokenHandler upSecurityTokenHandler = securityTokenHandler as UserNameSecurityTokenHandler;
                    if (upSecurityTokenHandler == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new InvalidOperationException(SR.GetString(SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof(UserNameSecurityTokenHandler))));
                    }
                    securityTokenAuthenticator = new WrappedUserNameSecurityTokenAuthenticator(upSecurityTokenHandler, _exceptionMapper);
                }
                else if (StringComparer.Ordinal.Equals(tokenType, SecurityTokenTypes.Kerberos))
                {
                    securityTokenAuthenticator = CreateInnerSecurityTokenAuthenticator(tokenRequirement, out outOfBandTokenResolver);
                }
                else if (StringComparer.Ordinal.Equals(tokenType, SecurityTokenTypes.Rsa))
                {
                    RsaSecurityTokenHandler rsaSecurityTokenHandler = securityTokenHandler as RsaSecurityTokenHandler;
                    if (rsaSecurityTokenHandler == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new InvalidOperationException(SR.GetString(SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof(RsaSecurityTokenHandler))));
                    }
                    securityTokenAuthenticator = new WrappedRsaSecurityTokenAuthenticator(rsaSecurityTokenHandler, _exceptionMapper);
                }
                else if (StringComparer.Ordinal.Equals(tokenType, SecurityTokenTypes.X509Certificate))
                {
                    X509SecurityTokenHandler x509SecurityTokenHandler = securityTokenHandler as X509SecurityTokenHandler;
                    if (x509SecurityTokenHandler == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new InvalidOperationException(SR.GetString(SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof(X509SecurityTokenHandler))));
                    }
                    securityTokenAuthenticator = new WrappedX509SecurityTokenAuthenticator(x509SecurityTokenHandler, _exceptionMapper);
                }
                else if (StringComparer.Ordinal.Equals(tokenType, SecurityTokenTypes.SamlTokenProfile11) ||
                         StringComparer.Ordinal.Equals(tokenType, SecurityTokenTypes.OasisWssSamlTokenProfile11))
                {
                    SamlSecurityTokenHandler saml11SecurityTokenHandler = securityTokenHandler as SamlSecurityTokenHandler;
                    if (saml11SecurityTokenHandler == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new InvalidOperationException(SR.GetString(SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof(SamlSecurityTokenHandler))));
                    }

                    if (saml11SecurityTokenHandler.Configuration == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274));
                    }

                    securityTokenAuthenticator = new WrappedSaml11SecurityTokenAuthenticator(saml11SecurityTokenHandler, _exceptionMapper);
                    // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
                    outOfBandTokenResolver = saml11SecurityTokenHandler.Configuration.ServiceTokenResolver;
                }
                else if (StringComparer.Ordinal.Equals(tokenType, SecurityTokenTypes.Saml2TokenProfile11) ||
                         StringComparer.Ordinal.Equals(tokenType, SecurityTokenTypes.OasisWssSaml2TokenProfile11))
                {
                    Saml2SecurityTokenHandler saml2SecurityTokenHandler = securityTokenHandler as Saml2SecurityTokenHandler;
                    if (saml2SecurityTokenHandler == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new InvalidOperationException(SR.GetString(SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof(Saml2SecurityTokenHandler))));
                    }

                    if (saml2SecurityTokenHandler.Configuration == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274));
                    }

                    securityTokenAuthenticator = new WrappedSaml2SecurityTokenAuthenticator(saml2SecurityTokenHandler, _exceptionMapper);
                    // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
                    outOfBandTokenResolver = saml2SecurityTokenHandler.Configuration.ServiceTokenResolver;
                }
                else if (StringComparer.Ordinal.Equals(tokenType, ServiceModelSecurityTokenTypes.SecureConversation))
                {
                    RecipientServiceModelSecurityTokenRequirement tr = tokenRequirement as RecipientServiceModelSecurityTokenRequirement;
                    if (tr == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4240, tokenRequirement.GetType().ToString()));
                    }

                    securityTokenAuthenticator = SetupSecureConversationWrapper(tr, securityTokenHandler as SessionSecurityTokenHandler, out outOfBandTokenResolver);
                }
                else
                {
                    securityTokenAuthenticator = new SecurityTokenAuthenticatorAdapter(securityTokenHandler, _exceptionMapper);
                }
            }
            else
            {
                if (tokenType == ServiceModelSecurityTokenTypes.SecureConversation ||
                    tokenType == ServiceModelSecurityTokenTypes.MutualSslnego ||
                    tokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego ||
                    tokenType == ServiceModelSecurityTokenTypes.SecurityContext ||
                    tokenType == ServiceModelSecurityTokenTypes.Spnego)
                {
                    RecipientServiceModelSecurityTokenRequirement tr = tokenRequirement as RecipientServiceModelSecurityTokenRequirement;
                    if (tr == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4240, tokenRequirement.GetType().ToString()));
                    }

                    securityTokenAuthenticator = SetupSecureConversationWrapper(tr, null, out outOfBandTokenResolver);
                }
                else
                {
                    securityTokenAuthenticator = CreateInnerSecurityTokenAuthenticator(tokenRequirement, out outOfBandTokenResolver);
                }
            }

            return(securityTokenAuthenticator);
        }
示例#9
0
 void OnBadData()
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.BadData)));
 }
示例#10
0
        static void ValidatePrivateKey(X509Certificate2 certificate)
        {
            bool hasPrivateKey = false;

            try
            {
                if (System.ServiceModel.LocalAppContextSwitches.DisableCngCertificates)
                {
                    hasPrivateKey = certificate != null && certificate.PrivateKey != null;
                }
                else
                {
                    hasPrivateKey = certificate.HasPrivateKey && SecurityUtils.CanReadPrivateKey(certificate);
                }
            }
            catch (SecurityException e)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.SslCertMayNotDoKeyExchange, certificate.SubjectName.Name), e));
            }
            catch (CryptographicException e)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.SslCertMayNotDoKeyExchange, certificate.SubjectName.Name), e));
            }
            if (!hasPrivateKey)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.SslCertMustHavePrivateKey, certificate.SubjectName.Name)));
            }
        }
示例#11
0
        public byte[] GetOutgoingBlob(byte[] incomingBlob, ChannelBinding channelbinding, ExtendedProtectionPolicy protectionPolicy)
        {
            ThrowIfDisposed();
            SecurityBuffer incomingSecurity = null;

            if (incomingBlob != null)
            {
                incomingSecurity = new SecurityBuffer(incomingBlob, BufferType.Token);
            }

            SecurityBuffer outgoingSecurity = new SecurityBuffer(null, BufferType.Token);

            this.remoteCertificate = null;
            int statusCode = 0;

            if (this.isServer == true)
            {
                statusCode = SspiWrapper.AcceptSecurityContext(
                    this.credentialsHandle,
                    ref this.securityContext,
                    ServerStandardFlags | (this.clientCertRequired ? SspiContextFlags.MutualAuth : SspiContextFlags.Zero),
                    Endianness.Native,
                    incomingSecurity,
                    outgoingSecurity,
                    ref this.attributes
                    );
            }
            else
            {
                statusCode = SspiWrapper.InitializeSecurityContext(
                    this.credentialsHandle,
                    ref this.securityContext,
                    this.destination,
                    ClientStandardFlags,
                    Endianness.Native,
                    incomingSecurity,
                    outgoingSecurity,
                    ref this.attributes
                    );
            }

            if ((statusCode & unchecked ((int)0x80000000)) != 0)
            {
                this.Dispose();
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(statusCode));
            }

            if (statusCode == (int)SecurityStatus.OK)
            {
                // we're done
                // ensure that the key negotiated is strong enough
                if (SecurityUtils.ShouldValidateSslCipherStrength())
                {
                    SslConnectionInfo connectionInfo = (SslConnectionInfo)SspiWrapper.QueryContextAttributes(this.securityContext, ContextAttribute.ConnectionInfo);
                    if (connectionInfo == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.CannotObtainSslConnectionInfo)));
                    }
                    SecurityUtils.ValidateSslCipherStrength(connectionInfo.DataKeySize);
                }
                this.isCompleted = true;
            }
            else if (statusCode == (int)SecurityStatus.CredentialsNeeded)
            {
                // the server requires the client to supply creds
                // Currently we dont attempt to find the client cert to choose at runtime
                // so just re-call the function
                AcquireClientCredentials();
                if (this.ClientCertificate != null)
                {
                    this.wasClientCertificateSent = true;
                }
                return(this.GetOutgoingBlob(incomingBlob, channelbinding, protectionPolicy));
            }
            else if (statusCode != (int)SecurityStatus.ContinueNeeded)
            {
                this.Dispose();
                if (statusCode == (int)SecurityStatus.InternalError)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(statusCode, SR.GetString(SR.LsaAuthorityNotContacted)));
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(statusCode));
                }
            }
            return(outgoingSecurity.token);
        }
        static void ValidatePrivateKey(X509Certificate2 certificate)
        {
            bool hasPrivateKey = false;

            try
            {
                hasPrivateKey = certificate != null && certificate.PrivateKey != null;
            }
            catch (SecurityException e)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.SslCertMayNotDoKeyExchange, certificate.SubjectName.Name), e));
            }
            catch (CryptographicException e)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.SslCertMayNotDoKeyExchange, certificate.SubjectName.Name), e));
            }
            if (!hasPrivateKey)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.SslCertMustHavePrivateKey, certificate.SubjectName.Name)));
            }
        }
 private static System.ServiceModel.SR GetLoader()
 {
     if (loader == null)
     {
         System.ServiceModel.SR sr = new System.ServiceModel.SR();
         Interlocked.CompareExchange<System.ServiceModel.SR>(ref loader, sr, null);
     }
     return loader;
 }