public WindowsStreamSecurityUpgradeProvider(WindowsStreamSecurityBindingElement bindingElement,
                                                    BindingContext context, bool isClient)
            : base(context.Binding)
        {
            this.extractGroupsForWindowsAccounts = TransportDefaults.ExtractGroupsForWindowsAccounts;
            this.protectionLevel = bindingElement.ProtectionLevel;
            this.scheme          = context.Binding.Scheme;
            this.isClient        = isClient;
            this.listenUri       = TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);

            SecurityCredentialsManager credentialProvider = context.BindingParameters.Find <SecurityCredentialsManager>();

            if (credentialProvider == null)
            {
                if (isClient)
                {
                    credentialProvider = ClientCredentials.CreateDefaultCredentials();
                }
                else
                {
                    credentialProvider = ServiceCredentials.CreateDefaultCredentials();
                }
            }


            this.securityTokenManager = credentialProvider.CreateSecurityTokenManager();
        }
Beispiel #2
0
        public static SslStreamSecurityUpgradeProvider CreateServerProvider(SslStreamSecurityBindingElement bindingElement, BindingContext context)
        {
            SecurityCredentialsManager manager = context.BindingParameters.Find <SecurityCredentialsManager>();

            if (manager == null)
            {
                manager = ServiceCredentials.CreateDefaultCredentials();
            }
            Uri listenUri = TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);
            SecurityTokenManager tokenManager = manager.CreateSecurityTokenManager();
            RecipientServiceModelSecurityTokenRequirement tokenRequirement = new RecipientServiceModelSecurityTokenRequirement {
                TokenType = SecurityTokenTypes.X509Certificate,
                RequireCryptographicToken = true,
                KeyUsage        = SecurityKeyUsage.Exchange,
                TransportScheme = context.Binding.Scheme,
                ListenUri       = listenUri
            };
            SecurityTokenProvider serverTokenProvider = tokenManager.CreateSecurityTokenProvider(tokenRequirement);

            if (serverTokenProvider == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("ClientCredentialsUnableToCreateLocalTokenProvider", new object[] { tokenRequirement })));
            }
            return(new SslStreamSecurityUpgradeProvider(context.Binding, serverTokenProvider, bindingElement.RequireClientCertificate, TransportSecurityHelpers.GetCertificateTokenAuthenticator(tokenManager, context.Binding.Scheme, listenUri), context.Binding.Scheme, bindingElement.IdentityVerifier));
        }
        public HttpsChannelListener(HttpsTransportBindingElement httpsBindingElement, BindingContext context) : base(httpsBindingElement, context)
        {
            this.requireClientCertificate = httpsBindingElement.RequireClientCertificate;
            SecurityCredentialsManager manager = context.BindingParameters.Find <SecurityCredentialsManager>();

            if (manager == null)
            {
                manager = ServiceCredentials.CreateDefaultCredentials();
            }
            SecurityTokenManager tokenManager = manager.CreateSecurityTokenManager();

            this.certificateAuthenticator = TransportSecurityHelpers.GetCertificateTokenAuthenticator(tokenManager, context.Binding.Scheme, TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress));
            ServiceCredentials credentials = manager as ServiceCredentials;

            if ((credentials != null) && (credentials.ClientCertificate.Authentication.CertificateValidationMode == X509CertificateValidationMode.Custom))
            {
                this.useCustomClientCertificateVerification = true;
            }
            else
            {
                this.useCustomClientCertificateVerification = false;
                X509SecurityTokenAuthenticator certificateAuthenticator = this.certificateAuthenticator as X509SecurityTokenAuthenticator;
                if (certificateAuthenticator != null)
                {
                    this.certificateAuthenticator = new X509SecurityTokenAuthenticator(X509CertificateValidator.None, certificateAuthenticator.MapCertificateToWindowsAccount, base.ExtractGroupsForWindowsAccounts, false);
                }
            }
            if (this.RequireClientCertificate && (base.AuthenticationScheme != AuthenticationSchemes.Anonymous))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelper(new InvalidOperationException(System.ServiceModel.SR.GetString("HttpAuthSchemeAndClientCert", new object[] { base.AuthenticationScheme })), TraceEventType.Error);
            }
            this.channelBindingProvider = new ChannelBindingProviderHelper();
        }
        protected override IChannelListener <TChannel> BuildChannelListenerCore <TChannel>(BindingContext context)
        {
            bool           requireDemuxer = RequiresChannelDemuxer();
            ChannelBuilder channelBuilder = new ChannelBuilder(context, requireDemuxer);

            if (requireDemuxer)
            {
                ApplyPropertiesOnDemuxer(channelBuilder, context);
            }
            BindingContext issuerBindingContext = context.Clone();

            SecurityChannelListener <TChannel> channelListener    = new SecurityChannelListener <TChannel>(this, context);
            SecurityCredentialsManager         credentialsManager = context.BindingParameters.Find <SecurityCredentialsManager>();

            if (credentialsManager == null)
            {
                credentialsManager = ServiceCredentials.CreateDefaultCredentials();
            }

            SecurityProtocolFactory protocolFactory = this.CreateSecurityProtocolFactory <TChannel>(context, credentialsManager, true, issuerBindingContext);

            channelListener.SecurityProtocolFactory = protocolFactory;
            channelListener.InitializeListener(channelBuilder);

            return(channelListener);
        }
        public static SslStreamSecurityUpgradeProvider CreateServerProvider(
            SslStreamSecurityBindingElement bindingElement, BindingContext context)
        {
            SecurityCredentialsManager credentialProvider =
                context.BindingParameters.Find <SecurityCredentialsManager>();

            if (credentialProvider == null)
            {
                credentialProvider = ServiceCredentials.CreateDefaultCredentials();
            }

            Uri listenUri = TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);
            SecurityTokenManager tokenManager = credentialProvider.CreateSecurityTokenManager();

            RecipientServiceModelSecurityTokenRequirement serverCertRequirement = new RecipientServiceModelSecurityTokenRequirement();

            serverCertRequirement.TokenType = SecurityTokenTypes.X509Certificate;
            serverCertRequirement.RequireCryptographicToken = true;
            serverCertRequirement.KeyUsage        = SecurityKeyUsage.Exchange;
            serverCertRequirement.TransportScheme = context.Binding.Scheme;
            serverCertRequirement.ListenUri       = listenUri;

            SecurityTokenProvider tokenProvider = tokenManager.CreateSecurityTokenProvider(serverCertRequirement);

            if (tokenProvider == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ClientCredentialsUnableToCreateLocalTokenProvider, serverCertRequirement)));
            }

            SecurityTokenAuthenticator certificateAuthenticator =
                TransportSecurityHelpers.GetCertificateTokenAuthenticator(tokenManager, context.Binding.Scheme, listenUri);

            return(new SslStreamSecurityUpgradeProvider(context.Binding, tokenProvider, bindingElement.RequireClientCertificate,
                                                        certificateAuthenticator, context.Binding.Scheme, bindingElement.IdentityVerifier, bindingElement.SslProtocols));
        }
        internal IChannelListener <TChannel> BuildNegotiationChannelListener <TChannel>(BindingContext context)
            where TChannel : class, IChannel
        {
            SecurityCredentialsManager securityCredentials = this.IssuerBindingContext.BindingParameters.Find <SecurityCredentialsManager>();

            if (securityCredentials == null)
            {
                securityCredentials = ServiceCredentials.CreateDefaultCredentials();
            }

            this.bootstrapSecurityBindingElement.ReaderQuotas = context.GetInnerProperty <XmlDictionaryReaderQuotas>();
            if (this.bootstrapSecurityBindingElement.ReaderQuotas == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.EncodingBindingElementDoesNotHandleReaderQuotas)));
            }

            TransportBindingElement transportBindingElement = context.RemainingBindingElements.Find <TransportBindingElement>();

            if (transportBindingElement != null)
            {
                this.bootstrapSecurityBindingElement.MaxReceivedMessageSize = transportBindingElement.MaxReceivedMessageSize;
            }

            SecurityProtocolFactory        securityProtocolFactory = this.bootstrapSecurityBindingElement.CreateSecurityProtocolFactory <TChannel>(this.IssuerBindingContext.Clone(), securityCredentials, true, this.IssuerBindingContext.Clone());
            MessageSecurityProtocolFactory soapBindingFactory      = securityProtocolFactory as MessageSecurityProtocolFactory;

            if (soapBindingFactory != null)
            {
                soapBindingFactory.ApplyConfidentiality             = soapBindingFactory.ApplyIntegrity
                                                                    = soapBindingFactory.RequireConfidentiality = soapBindingFactory.RequireIntegrity = true;
                MessagePartSpecification bodyPart = new MessagePartSpecification(true);
                soapBindingFactory.ProtectionRequirements.OutgoingSignatureParts.AddParts(bodyPart, RequestSecurityTokenResponseAction);
                soapBindingFactory.ProtectionRequirements.OutgoingEncryptionParts.AddParts(bodyPart, RequestSecurityTokenResponseAction);
                soapBindingFactory.ProtectionRequirements.IncomingSignatureParts.AddParts(bodyPart, RequestSecurityTokenAction);
                soapBindingFactory.ProtectionRequirements.IncomingEncryptionParts.AddParts(bodyPart, RequestSecurityTokenAction);
            }

            SecurityChannelListener <TChannel> securityChannelListener =
                new SecurityChannelListener <TChannel>(this.bootstrapSecurityBindingElement, context);

            securityChannelListener.SecurityProtocolFactory = securityProtocolFactory;
            // do not send back unsecured faults over composite duplex
            securityChannelListener.SendUnsecuredFaults = !SecurityUtils.IsCompositeDuplexBinding(context);

            ChannelBuilder channelBuilder = new ChannelBuilder(context, true);

            securityChannelListener.InitializeListener(channelBuilder);
            this.shouldMatchRstWithEndpointFilter = SecurityUtils.ShouldMatchRstWithEndpointFilter(this.bootstrapSecurityBindingElement);
            return(securityChannelListener);
        }
        public HttpsChannelListener(HttpsTransportBindingElement httpsBindingElement, BindingContext context)
            : base(httpsBindingElement, context)
        {
            this.requireClientCertificate        = httpsBindingElement.RequireClientCertificate;
            this.shouldValidateClientCertificate = ShouldValidateClientCertificate(this.requireClientCertificate, context);

            // Pick up the MapCertificateToWindowsAccount setting from the configured token authenticator.
            SecurityCredentialsManager credentialProvider =
                context.BindingParameters.Find <SecurityCredentialsManager>();

            if (credentialProvider == null)
            {
                credentialProvider = ServiceCredentials.CreateDefaultCredentials();
            }
            SecurityTokenManager tokenManager = credentialProvider.CreateSecurityTokenManager();

            this.certificateAuthenticator =
                TransportSecurityHelpers.GetCertificateTokenAuthenticator(tokenManager, context.Binding.Scheme,
                                                                          TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress));


            ServiceCredentials serviceCredentials = credentialProvider as ServiceCredentials;

            if (serviceCredentials != null &&
                serviceCredentials.ClientCertificate.Authentication.CertificateValidationMode == X509CertificateValidationMode.Custom)
            {
                useCustomClientCertificateVerification = true;
            }
            else
            {
                useCustomClientCertificateVerification = false;

                X509SecurityTokenAuthenticator authenticator = this.certificateAuthenticator as X509SecurityTokenAuthenticator;

                if (authenticator != null)
                {
                    this.certificateAuthenticator = new X509SecurityTokenAuthenticator(X509CertificateValidator.None,
                                                                                       authenticator.MapCertificateToWindowsAccount, this.ExtractGroupsForWindowsAccounts, false);
                }
            }

            if (this.RequireClientCertificate &&
                this.AuthenticationScheme.IsNotSet(AuthenticationSchemes.Anonymous))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelper(new InvalidOperationException(SR.GetString(
                                                                                                       SR.HttpAuthSchemeAndClientCert, this.AuthenticationScheme)), TraceEventType.Error);
            }

            this.channelBindingProvider = new ChannelBindingProviderHelper();
        }
        internal IChannelListener <TChannel> BuildNegotiationChannelListener <TChannel>(BindingContext context) where TChannel : class, IChannel
        {
            SecurityCredentialsManager credentialsManager = base.IssuerBindingContext.BindingParameters.Find <SecurityCredentialsManager>();

            if (credentialsManager == null)
            {
                credentialsManager = ServiceCredentials.CreateDefaultCredentials();
            }
            this.bootstrapSecurityBindingElement.ReaderQuotas = context.GetInnerProperty <XmlDictionaryReaderQuotas>();
            if (this.bootstrapSecurityBindingElement.ReaderQuotas == null)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("EncodingBindingElementDoesNotHandleReaderQuotas")));
            }
            TransportBindingElement element = context.RemainingBindingElements.Find <TransportBindingElement>();

            if (element != null)
            {
                this.bootstrapSecurityBindingElement.MaxReceivedMessageSize = element.MaxReceivedMessageSize;
            }
            SecurityProtocolFactory        factory  = this.bootstrapSecurityBindingElement.CreateSecurityProtocolFactory <TChannel>(base.IssuerBindingContext.Clone(), credentialsManager, true, base.IssuerBindingContext.Clone());
            MessageSecurityProtocolFactory factory2 = factory as MessageSecurityProtocolFactory;

            if (factory2 != null)
            {
                factory2.ApplyConfidentiality = factory2.ApplyIntegrity = factory2.RequireConfidentiality = factory2.RequireIntegrity = true;
                MessagePartSpecification parts = new MessagePartSpecification(true);
                factory2.ProtectionRequirements.OutgoingSignatureParts.AddParts(parts, this.RequestSecurityTokenResponseAction);
                factory2.ProtectionRequirements.OutgoingEncryptionParts.AddParts(parts, this.RequestSecurityTokenResponseAction);
                factory2.ProtectionRequirements.IncomingSignatureParts.AddParts(parts, this.RequestSecurityTokenAction);
                factory2.ProtectionRequirements.IncomingEncryptionParts.AddParts(parts, this.RequestSecurityTokenAction);
            }
            SecurityChannelListener <TChannel> listener = new SecurityChannelListener <TChannel>(this.bootstrapSecurityBindingElement, context)
            {
                SecurityProtocolFactory = factory,
                SendUnsecuredFaults     = !System.ServiceModel.Security.SecurityUtils.IsCompositeDuplexBinding(context)
            };
            ChannelBuilder channelBuilder = new ChannelBuilder(context, true);

            listener.InitializeListener(channelBuilder);
            this.shouldMatchRstWithEndpointFilter = System.ServiceModel.Security.SecurityUtils.ShouldMatchRstWithEndpointFilter(this.bootstrapSecurityBindingElement);
            return(listener);
        }
 protected void SetSecurityTokenAuthenticator(string scheme, BindingContext context)
 {
     if (base.ReceiveParameters.TransportSecurity.MsmqAuthenticationMode == MsmqAuthenticationMode.Certificate)
     {
         SecurityTokenResolver      resolver;
         SecurityCredentialsManager manager = context.BindingParameters.Find <SecurityCredentialsManager>();
         if (manager == null)
         {
             manager = ServiceCredentials.CreateDefaultCredentials();
         }
         SecurityTokenManager manager2 = manager.CreateSecurityTokenManager();
         RecipientServiceModelSecurityTokenRequirement tokenRequirement = new RecipientServiceModelSecurityTokenRequirement {
             TokenType       = SecurityTokenTypes.X509Certificate,
             TransportScheme = scheme,
             ListenUri       = this.Uri,
             KeyUsage        = SecurityKeyUsage.Signature
         };
         this.x509SecurityTokenAuthenticator = manager2.CreateSecurityTokenAuthenticator(tokenRequirement, out resolver);
     }
 }
        protected override IChannelListener <TChannel> BuildChannelListenerCore <TChannel>(BindingContext context) where TChannel : class, IChannel
        {
            bool           addChannelDemuxerIfRequired = this.RequiresChannelDemuxer();
            ChannelBuilder builder = new ChannelBuilder(context, addChannelDemuxerIfRequired);

            if (addChannelDemuxerIfRequired)
            {
                base.ApplyPropertiesOnDemuxer(builder, context);
            }
            BindingContext issuanceBindingContext                 = context.Clone();
            SecurityChannelListener <TChannel> listener           = new SecurityChannelListener <TChannel>(this, context);
            SecurityCredentialsManager         credentialsManager = context.BindingParameters.Find <SecurityCredentialsManager>();

            if (credentialsManager == null)
            {
                credentialsManager = ServiceCredentials.CreateDefaultCredentials();
            }
            SecurityProtocolFactory factory = this.CreateSecurityProtocolFactory <TChannel>(context, credentialsManager, true, issuanceBindingContext);

            listener.SecurityProtocolFactory = factory;
            listener.InitializeListener(builder);
            return(listener);
        }
        protected override IServiceDispatcher BuildServiceDispatcherCore <TChannel>(BindingContext context, IServiceDispatcher serviceDispatcher)
        {
            SecurityServiceDispatcher  securityServiceDispatcher = new SecurityServiceDispatcher(context, serviceDispatcher);
            SecurityCredentialsManager credentialsManager        = serviceDispatcher.Host.Description.Behaviors.Find <SecurityCredentialsManager>();

            if (credentialsManager == null)
            {
                credentialsManager = ServiceCredentials.CreateDefaultCredentials();
            }

            SecureConversationSecurityTokenParameters scParameters;

            if (EndpointSupportingTokenParameters.Endorsing.Count > 0)
            {
                scParameters = EndpointSupportingTokenParameters.Endorsing[0] as SecureConversationSecurityTokenParameters;
            }
            else
            {
                scParameters = null;
            }

            bool           requireDemuxer = RequiresChannelDemuxer();
            ChannelBuilder channelBuilder = new ChannelBuilder(context, requireDemuxer);

            if (requireDemuxer)
            {
                ApplyPropertiesOnDemuxer(channelBuilder, context);
            }

            BindingContext issuerBindingContext = context.Clone();

            issuerBindingContext.BindingParameters.Add(credentialsManager);
            if (scParameters != null)
            {
                if (scParameters.BootstrapSecurityBindingElement == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SecureConversationSecurityTokenParametersRequireBootstrapBinding)));
                }

                AddDemuxerForSecureConversation(channelBuilder, issuerBindingContext);

                if (scParameters.RequireCancellation)
                {
                    SessionSymmetricTransportSecurityProtocolFactory sessionFactory = new SessionSymmetricTransportSecurityProtocolFactory
                    {
                        // base.ApplyAuditBehaviorSettings(context, sessionFactory);
                        SecurityTokenParameters = scParameters.Clone()
                    };
                    ((SecureConversationSecurityTokenParameters)sessionFactory.SecurityTokenParameters).IssuerBindingContext = issuerBindingContext;
                    EndpointSupportingTokenParameters.Endorsing.RemoveAt(0);
                    try
                    {
                        ConfigureProtocolFactory(sessionFactory, credentialsManager, true, issuerBindingContext, context.Binding);
                    }
                    finally
                    {
                        EndpointSupportingTokenParameters.Endorsing.Insert(0, scParameters);
                    }

                    securityServiceDispatcher.SessionMode = true;
                    securityServiceDispatcher.SessionServerSettings.InactivityTimeout             = LocalServiceSettings.InactivityTimeout;
                    securityServiceDispatcher.SessionServerSettings.KeyRolloverInterval           = LocalServiceSettings.SessionKeyRolloverInterval;
                    securityServiceDispatcher.SessionServerSettings.MaximumPendingSessions        = LocalServiceSettings.MaxPendingSessions;
                    securityServiceDispatcher.SessionServerSettings.MaximumKeyRenewalInterval     = LocalServiceSettings.SessionKeyRenewalInterval;
                    securityServiceDispatcher.SessionServerSettings.TolerateTransportFailures     = LocalServiceSettings.ReconnectTransportOnFailure;
                    securityServiceDispatcher.SessionServerSettings.CanRenewSession               = scParameters.CanRenewSession;
                    securityServiceDispatcher.SessionServerSettings.IssuedSecurityTokenParameters = scParameters.Clone();
                    ((SecureConversationSecurityTokenParameters)securityServiceDispatcher.SessionServerSettings.IssuedSecurityTokenParameters).IssuerBindingContext = issuerBindingContext;
                    securityServiceDispatcher.SessionServerSettings.SecurityStandardsManager = sessionFactory.StandardsManager;
                    securityServiceDispatcher.SessionServerSettings.SessionProtocolFactory   = sessionFactory;
                    securityServiceDispatcher.SecurityProtocolFactory = sessionFactory;

                    // pass in the error handler for handling unknown security sessions - dont do this if the underlying channel is duplex since sending
                    // back faults in response to badly secured requests over duplex can result in DoS.
                    if (context.BindingParameters != null && context.BindingParameters.Find <IChannelDemuxFailureHandler>() == null &&
                        !IsUnderlyingDispatcherDuplex <TChannel>(context))
                    {
                        context.BindingParameters.Add(new SecuritySessionServerSettings.SecuritySessionDemuxFailureHandler(sessionFactory.StandardsManager));
                    }
                }
                else
                {
                    //TODO later
                    TransportSecurityProtocolFactory protocolFactory = new TransportSecurityProtocolFactory();
                    // base.ApplyAuditBehaviorSettings(context, protocolFactory);
                    EndpointSupportingTokenParameters.Endorsing.RemoveAt(0);
                    try
                    {
                        ConfigureProtocolFactory(protocolFactory, credentialsManager, true, issuerBindingContext, context.Binding);
                        SecureConversationSecurityTokenParameters acceleratedTokenParameters = (SecureConversationSecurityTokenParameters)scParameters.Clone();
                        acceleratedTokenParameters.IssuerBindingContext = issuerBindingContext;
                        protocolFactory.SecurityBindingElement.EndpointSupportingTokenParameters.Endorsing.Insert(0, acceleratedTokenParameters);
                    }
                    finally
                    {
                        EndpointSupportingTokenParameters.Endorsing.Insert(0, scParameters);
                    }

                    securityServiceDispatcher.SecurityProtocolFactory = protocolFactory;
                }
            }
            else
            {
                SecurityProtocolFactory protocolFactory = CreateSecurityProtocolFactory <TChannel>(context, credentialsManager, true, issuerBindingContext);
                securityServiceDispatcher.SecurityProtocolFactory = protocolFactory;
            }
            securityServiceDispatcher.InitializeSecurityDispatcher(channelBuilder, typeof(TChannel));
            //return channelListener;
            channelBuilder.BuildServiceDispatcher <TChannel>(context, securityServiceDispatcher);
            return(securityServiceDispatcher);
        }
        protected override IChannelListener <TChannel> BuildChannelListenerCore <TChannel>(BindingContext context) where TChannel : class, IChannel
        {
            SecureConversationSecurityTokenParameters parameters;
            SecurityChannelListener <TChannel>        listener = new SecurityChannelListener <TChannel>(this, context);
            SecurityCredentialsManager credentialsManager      = context.BindingParameters.Find <SecurityCredentialsManager>();

            if (credentialsManager == null)
            {
                credentialsManager = ServiceCredentials.CreateDefaultCredentials();
            }
            if (base.EndpointSupportingTokenParameters.Endorsing.Count > 0)
            {
                parameters = base.EndpointSupportingTokenParameters.Endorsing[0] as SecureConversationSecurityTokenParameters;
            }
            else
            {
                parameters = null;
            }
            bool           addChannelDemuxerIfRequired = this.RequiresChannelDemuxer();
            ChannelBuilder builder = new ChannelBuilder(context, addChannelDemuxerIfRequired);

            if (addChannelDemuxerIfRequired)
            {
                base.ApplyPropertiesOnDemuxer(builder, context);
            }
            BindingContext secureConversationBindingContext = context.Clone();

            if (parameters != null)
            {
                if (parameters.BootstrapSecurityBindingElement == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SecureConversationSecurityTokenParametersRequireBootstrapBinding")));
                }
                base.AddDemuxerForSecureConversation(builder, secureConversationBindingContext);
                if (parameters.RequireCancellation)
                {
                    SessionSymmetricTransportSecurityProtocolFactory factory = new SessionSymmetricTransportSecurityProtocolFactory();
                    base.ApplyAuditBehaviorSettings(context, factory);
                    factory.SecurityTokenParameters = parameters.Clone();
                    ((SecureConversationSecurityTokenParameters)factory.SecurityTokenParameters).IssuerBindingContext = secureConversationBindingContext;
                    base.EndpointSupportingTokenParameters.Endorsing.RemoveAt(0);
                    try
                    {
                        base.ConfigureProtocolFactory(factory, credentialsManager, true, secureConversationBindingContext, context.Binding);
                    }
                    finally
                    {
                        base.EndpointSupportingTokenParameters.Endorsing.Insert(0, parameters);
                    }
                    listener.SessionMode = true;
                    listener.SessionServerSettings.InactivityTimeout             = base.LocalServiceSettings.InactivityTimeout;
                    listener.SessionServerSettings.KeyRolloverInterval           = base.LocalServiceSettings.SessionKeyRolloverInterval;
                    listener.SessionServerSettings.MaximumPendingSessions        = base.LocalServiceSettings.MaxPendingSessions;
                    listener.SessionServerSettings.MaximumKeyRenewalInterval     = base.LocalServiceSettings.SessionKeyRenewalInterval;
                    listener.SessionServerSettings.TolerateTransportFailures     = base.LocalServiceSettings.ReconnectTransportOnFailure;
                    listener.SessionServerSettings.CanRenewSession               = parameters.CanRenewSession;
                    listener.SessionServerSettings.IssuedSecurityTokenParameters = parameters.Clone();
                    ((SecureConversationSecurityTokenParameters)listener.SessionServerSettings.IssuedSecurityTokenParameters).IssuerBindingContext = secureConversationBindingContext;
                    listener.SessionServerSettings.SecurityStandardsManager = factory.StandardsManager;
                    listener.SessionServerSettings.SessionProtocolFactory   = factory;
                    if (((context.BindingParameters != null) && (context.BindingParameters.Find <IChannelDemuxFailureHandler>() == null)) && !base.IsUnderlyingListenerDuplex <TChannel>(context))
                    {
                        context.BindingParameters.Add(new SecuritySessionServerSettings.SecuritySessionDemuxFailureHandler(factory.StandardsManager));
                    }
                }
                else
                {
                    TransportSecurityProtocolFactory factory2 = new TransportSecurityProtocolFactory();
                    base.ApplyAuditBehaviorSettings(context, factory2);
                    base.EndpointSupportingTokenParameters.Endorsing.RemoveAt(0);
                    try
                    {
                        base.ConfigureProtocolFactory(factory2, credentialsManager, true, secureConversationBindingContext, context.Binding);
                        SecureConversationSecurityTokenParameters item = (SecureConversationSecurityTokenParameters)parameters.Clone();
                        item.IssuerBindingContext = secureConversationBindingContext;
                        factory2.SecurityBindingElement.EndpointSupportingTokenParameters.Endorsing.Insert(0, item);
                    }
                    finally
                    {
                        base.EndpointSupportingTokenParameters.Endorsing.Insert(0, parameters);
                    }
                    listener.SecurityProtocolFactory = factory2;
                }
            }
            else
            {
                SecurityProtocolFactory factory3 = this.CreateSecurityProtocolFactory <TChannel>(context, credentialsManager, true, secureConversationBindingContext);
                listener.SecurityProtocolFactory = factory3;
            }
            listener.InitializeListener(builder);
            return(listener);
        }
        protected override IChannelListener <TChannel> BuildChannelListenerCore <TChannel>(BindingContext context) where TChannel : class, IChannel
        {
            SecurityChannelListener <TChannel> listener           = new SecurityChannelListener <TChannel>(this, context);
            SecurityCredentialsManager         credentialsManager = context.BindingParameters.Find <SecurityCredentialsManager>();

            if (credentialsManager == null)
            {
                credentialsManager = ServiceCredentials.CreateDefaultCredentials();
            }
            bool           addChannelDemuxerIfRequired = this.RequiresChannelDemuxer();
            ChannelBuilder builder = new ChannelBuilder(context, addChannelDemuxerIfRequired);

            if (addChannelDemuxerIfRequired)
            {
                base.ApplyPropertiesOnDemuxer(builder, context);
            }
            BindingContext issuerBindingContext = context.Clone();

            if (this.ProtectionTokenParameters is SecureConversationSecurityTokenParameters)
            {
                SecureConversationSecurityTokenParameters protectionTokenParameters = (SecureConversationSecurityTokenParameters)this.ProtectionTokenParameters;
                if (protectionTokenParameters.BootstrapSecurityBindingElement == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SecureConversationSecurityTokenParametersRequireBootstrapBinding")));
                }
                BindingContext secureConversationBindingContext = issuerBindingContext.Clone();
                secureConversationBindingContext.BindingParameters.Remove <ChannelProtectionRequirements>();
                secureConversationBindingContext.BindingParameters.Add(protectionTokenParameters.BootstrapProtectionRequirements);
                IMessageFilterTable <EndpointAddress> table = context.BindingParameters.Find <IMessageFilterTable <EndpointAddress> >();
                base.AddDemuxerForSecureConversation(builder, secureConversationBindingContext);
                if (protectionTokenParameters.RequireCancellation)
                {
                    SessionSymmetricMessageSecurityProtocolFactory factory = new SessionSymmetricMessageSecurityProtocolFactory();
                    base.ApplyAuditBehaviorSettings(context, factory);
                    factory.SecurityTokenParameters = protectionTokenParameters.Clone();
                    ((SecureConversationSecurityTokenParameters)factory.SecurityTokenParameters).IssuerBindingContext = secureConversationBindingContext;
                    factory.ApplyConfidentiality           = true;
                    factory.RequireConfidentiality         = true;
                    factory.ApplyIntegrity                 = true;
                    factory.RequireIntegrity               = true;
                    factory.IdentityVerifier               = base.LocalClientSettings.IdentityVerifier;
                    factory.DoRequestSignatureConfirmation = this.RequireSignatureConfirmation;
                    factory.MessageProtectionOrder         = this.MessageProtectionOrder;
                    factory.IdentityVerifier               = base.LocalClientSettings.IdentityVerifier;
                    factory.ProtectionRequirements.Add(SecurityBindingElement.ComputeProtectionRequirements(this, context.BindingParameters, context.Binding.Elements, true));
                    base.ConfigureProtocolFactory(factory, credentialsManager, true, issuerBindingContext, context.Binding);
                    listener.SessionMode = true;
                    listener.SessionServerSettings.InactivityTimeout             = base.LocalServiceSettings.InactivityTimeout;
                    listener.SessionServerSettings.KeyRolloverInterval           = base.LocalServiceSettings.SessionKeyRolloverInterval;
                    listener.SessionServerSettings.MaximumPendingSessions        = base.LocalServiceSettings.MaxPendingSessions;
                    listener.SessionServerSettings.MaximumKeyRenewalInterval     = base.LocalServiceSettings.SessionKeyRenewalInterval;
                    listener.SessionServerSettings.TolerateTransportFailures     = base.LocalServiceSettings.ReconnectTransportOnFailure;
                    listener.SessionServerSettings.CanRenewSession               = protectionTokenParameters.CanRenewSession;
                    listener.SessionServerSettings.IssuedSecurityTokenParameters = protectionTokenParameters.Clone();
                    ((SecureConversationSecurityTokenParameters)listener.SessionServerSettings.IssuedSecurityTokenParameters).IssuerBindingContext = secureConversationBindingContext;
                    listener.SessionServerSettings.SecurityStandardsManager = factory.StandardsManager;
                    listener.SessionServerSettings.SessionProtocolFactory   = factory;
                    listener.SessionServerSettings.SessionProtocolFactory.EndpointFilterTable = table;
                    if (((context.BindingParameters != null) && (context.BindingParameters.Find <IChannelDemuxFailureHandler>() == null)) && !base.IsUnderlyingListenerDuplex <TChannel>(context))
                    {
                        context.BindingParameters.Add(new SecuritySessionServerSettings.SecuritySessionDemuxFailureHandler(factory.StandardsManager));
                    }
                }
                else
                {
                    SymmetricSecurityProtocolFactory factory2 = new SymmetricSecurityProtocolFactory();
                    base.ApplyAuditBehaviorSettings(context, factory2);
                    factory2.SecurityTokenParameters = protectionTokenParameters.Clone();
                    ((SecureConversationSecurityTokenParameters)factory2.SecurityTokenParameters).IssuerBindingContext = secureConversationBindingContext;
                    factory2.ApplyConfidentiality           = true;
                    factory2.RequireConfidentiality         = true;
                    factory2.ApplyIntegrity                 = true;
                    factory2.RequireIntegrity               = true;
                    factory2.IdentityVerifier               = base.LocalClientSettings.IdentityVerifier;
                    factory2.DoRequestSignatureConfirmation = this.RequireSignatureConfirmation;
                    factory2.MessageProtectionOrder         = this.MessageProtectionOrder;
                    factory2.ProtectionRequirements.Add(SecurityBindingElement.ComputeProtectionRequirements(this, context.BindingParameters, context.Binding.Elements, true));
                    factory2.EndpointFilterTable = table;
                    base.ConfigureProtocolFactory(factory2, credentialsManager, true, issuerBindingContext, context.Binding);
                    listener.SecurityProtocolFactory = factory2;
                }
            }
            else
            {
                SecurityProtocolFactory factory3 = this.CreateSecurityProtocolFactory <TChannel>(context, credentialsManager, true, issuerBindingContext);
                listener.SecurityProtocolFactory = factory3;
            }
            listener.InitializeListener(builder);
            return(listener);
        }
        protected override IChannelListener <TChannel> BuildChannelListenerCore <TChannel>(BindingContext context)
        {
            SecurityChannelListener <TChannel> channelListener = new SecurityChannelListener <TChannel>(this, context);

            SecurityCredentialsManager credentialsManager = context.BindingParameters.Find <SecurityCredentialsManager>();

            if (credentialsManager == null)
            {
                credentialsManager = ServiceCredentials.CreateDefaultCredentials();
            }

            // This adds the demuxer element to the context. We add a demuxer element only if the binding is configured to do
            // secure conversation or negotiation

            bool           requireDemuxer = RequiresChannelDemuxer();
            ChannelBuilder channelBuilder = new ChannelBuilder(context, requireDemuxer);

            if (requireDemuxer)
            {
                ApplyPropertiesOnDemuxer(channelBuilder, context);
            }

            BindingContext issuerBindingContext = context.Clone();

            if (this.ProtectionTokenParameters is SecureConversationSecurityTokenParameters)
            {
                SecureConversationSecurityTokenParameters scParameters = (SecureConversationSecurityTokenParameters)this.ProtectionTokenParameters;
                if (scParameters.BootstrapSecurityBindingElement == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SecureConversationSecurityTokenParametersRequireBootstrapBinding)));
                }

                BindingContext scIssuerBindingContext = issuerBindingContext.Clone();
                scIssuerBindingContext.BindingParameters.Remove <ChannelProtectionRequirements>();
                scIssuerBindingContext.BindingParameters.Add(scParameters.BootstrapProtectionRequirements);
                IMessageFilterTable <EndpointAddress> endpointFilterTable = context.BindingParameters.Find <IMessageFilterTable <EndpointAddress> >();

                AddDemuxerForSecureConversation(channelBuilder, scIssuerBindingContext);

                if (scParameters.RequireCancellation)
                {
                    SessionSymmetricMessageSecurityProtocolFactory sessionFactory = new SessionSymmetricMessageSecurityProtocolFactory();
                    base.ApplyAuditBehaviorSettings(context, sessionFactory);
                    sessionFactory.SecurityTokenParameters = scParameters.Clone();
                    ((SecureConversationSecurityTokenParameters)sessionFactory.SecurityTokenParameters).IssuerBindingContext = scIssuerBindingContext;
                    sessionFactory.ApplyConfidentiality           = true;
                    sessionFactory.RequireConfidentiality         = true;
                    sessionFactory.ApplyIntegrity                 = true;
                    sessionFactory.RequireIntegrity               = true;
                    sessionFactory.IdentityVerifier               = this.LocalClientSettings.IdentityVerifier;
                    sessionFactory.DoRequestSignatureConfirmation = this.RequireSignatureConfirmation;
                    sessionFactory.MessageProtectionOrder         = this.MessageProtectionOrder;
                    sessionFactory.IdentityVerifier               = this.LocalClientSettings.IdentityVerifier;
                    sessionFactory.ProtectionRequirements.Add(SecurityBindingElement.ComputeProtectionRequirements(this, context.BindingParameters, context.Binding.Elements, true));
                    base.ConfigureProtocolFactory(sessionFactory, credentialsManager, true, issuerBindingContext, context.Binding);

                    channelListener.SessionMode = true;
                    channelListener.SessionServerSettings.InactivityTimeout             = this.LocalServiceSettings.InactivityTimeout;
                    channelListener.SessionServerSettings.KeyRolloverInterval           = this.LocalServiceSettings.SessionKeyRolloverInterval;
                    channelListener.SessionServerSettings.MaximumPendingSessions        = this.LocalServiceSettings.MaxPendingSessions;
                    channelListener.SessionServerSettings.MaximumKeyRenewalInterval     = this.LocalServiceSettings.SessionKeyRenewalInterval;
                    channelListener.SessionServerSettings.TolerateTransportFailures     = this.LocalServiceSettings.ReconnectTransportOnFailure;
                    channelListener.SessionServerSettings.CanRenewSession               = scParameters.CanRenewSession;
                    channelListener.SessionServerSettings.IssuedSecurityTokenParameters = scParameters.Clone();
                    ((SecureConversationSecurityTokenParameters)channelListener.SessionServerSettings.IssuedSecurityTokenParameters).IssuerBindingContext = scIssuerBindingContext;
                    channelListener.SessionServerSettings.SecurityStandardsManager = sessionFactory.StandardsManager;
                    channelListener.SessionServerSettings.SessionProtocolFactory   = sessionFactory;
                    channelListener.SessionServerSettings.SessionProtocolFactory.EndpointFilterTable = endpointFilterTable;

                    // pass in the error handler for handling unknown security sessions - dont do this if the underlying channel is duplex since sending
                    // back faults in response to badly secured requests over duplex can result in DoS.
                    if (context.BindingParameters != null && context.BindingParameters.Find <IChannelDemuxFailureHandler>() == null &&
                        !IsUnderlyingListenerDuplex <TChannel>(context))
                    {
                        context.BindingParameters.Add(new SecuritySessionServerSettings.SecuritySessionDemuxFailureHandler(sessionFactory.StandardsManager));
                    }
                }
                else
                {
                    SymmetricSecurityProtocolFactory protocolFactory = new SymmetricSecurityProtocolFactory();
                    base.ApplyAuditBehaviorSettings(context, protocolFactory);
                    protocolFactory.SecurityTokenParameters = scParameters.Clone();
                    ((SecureConversationSecurityTokenParameters)protocolFactory.SecurityTokenParameters).IssuerBindingContext = scIssuerBindingContext;
                    protocolFactory.ApplyConfidentiality           = true;
                    protocolFactory.RequireConfidentiality         = true;
                    protocolFactory.ApplyIntegrity                 = true;
                    protocolFactory.RequireIntegrity               = true;
                    protocolFactory.IdentityVerifier               = this.LocalClientSettings.IdentityVerifier;
                    protocolFactory.DoRequestSignatureConfirmation = this.RequireSignatureConfirmation;
                    protocolFactory.MessageProtectionOrder         = this.MessageProtectionOrder;
                    protocolFactory.ProtectionRequirements.Add(SecurityBindingElement.ComputeProtectionRequirements(this, context.BindingParameters, context.Binding.Elements, true));
                    protocolFactory.EndpointFilterTable = endpointFilterTable;
                    base.ConfigureProtocolFactory(protocolFactory, credentialsManager, true, issuerBindingContext, context.Binding);

                    channelListener.SecurityProtocolFactory = protocolFactory;
                }
            }
            else
            {
                SecurityProtocolFactory protocolFactory = this.CreateSecurityProtocolFactory <TChannel>(context, credentialsManager, true, issuerBindingContext);
                channelListener.SecurityProtocolFactory = protocolFactory;
            }

            channelListener.InitializeListener(channelBuilder);

            return(channelListener);
        }