Exemplo n.º 1
0
        internal void ConfigureProtocolFactory(SecurityProtocolFactory factory, SecurityCredentialsManager credentialsManager, bool isForService, BindingContext issuerBindingContext, Binding binding)
        {
            if (factory == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(factory)));
            }

            if (credentialsManager == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(credentialsManager)));
            }

            factory.AddTimestamp              = IncludeTimestamp;
            factory.IncomingAlgorithmSuite    = DefaultAlgorithmSuite;
            factory.OutgoingAlgorithmSuite    = DefaultAlgorithmSuite;
            factory.SecurityHeaderLayout      = SecurityHeaderLayout;
            factory.TimestampValidityDuration = LocalServiceSettings.TimestampValidityDuration;
            factory.DetectReplays             = LocalServiceSettings.DetectReplays;
            factory.MaxCachedNonces           = LocalServiceSettings.ReplayCacheSize;
            factory.MaxClockSkew              = LocalServiceSettings.MaxClockSkew;
            factory.ReplayWindow              = LocalServiceSettings.ReplayWindow;

            if (LocalServiceSettings.DetectReplays)
            {
                factory.NonceCache = LocalServiceSettings.NonceCache;
            }
            factory.SecurityBindingElement = (SecurityBindingElement)Clone();
            factory.SecurityBindingElement.SetIssuerBindingContextIfRequired(issuerBindingContext);
            factory.SecurityTokenManager = credentialsManager.CreateSecurityTokenManager();
            SecurityTokenSerializer tokenSerializer = factory.SecurityTokenManager.CreateSecurityTokenSerializer(_messageSecurityVersion.SecurityTokenVersion);

            factory.StandardsManager = new SecurityStandardsManager(_messageSecurityVersion, tokenSerializer);
        }
        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));
        }
Exemplo n.º 3
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));
        }
Exemplo n.º 4
0
 private void InitializeSecurityTokenManager()
 {
     if (_channelCredentials == null)
     {
         _channelCredentials = ClientCredentials.CreateDefaultCredentials();
     }
 }
        public WindowsStreamSecurityUpgradeProvider(WindowsStreamSecurityBindingElement bindingElement,
                                                    BindingContext context, bool isClient)
            : base(context.Binding)
        {
            _extractGroupsForWindowsAccounts = TransportDefaults.ExtractGroupsForWindowsAccounts;
            _protectionLevel = bindingElement.ProtectionLevel;
            _scheme          = context.Binding.Scheme;
            _isClient        = isClient;
            _listenUri       = TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);

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

            if (credentialProvider == null)
            {
                if (isClient)
                {
                    credentialProvider = ClientCredentials.CreateDefaultCredentials();
                }
                else
                {
                    throw ExceptionHelper.PlatformNotSupported("WindowsStreamSecurityUpgradeProvider for server is not supported.");
                }
            }

            _securityTokenManager = credentialProvider.CreateSecurityTokenManager();
        }
        public WindowsStreamSecurityUpgradeProvider(WindowsStreamSecurityBindingElement bindingElement,
                                                    BindingContext context, bool isClient)
            : base(context.Binding)
        {
            ExtractGroupsForWindowsAccounts = TransportDefaults.ExtractGroupsForWindowsAccounts;
            ProtectionLevel = bindingElement.ProtectionLevel;
            Scheme          = context.Binding.Scheme;
            _isClient       = isClient;
            _listenUri      = TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);

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

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

            if (credentialProvider is ServiceCredentials)
            {
                ServiceCredentials serviceCred = (ServiceCredentials)credentialProvider;
                LdapSettings = serviceCred.WindowsAuthentication.LdapSetting;
            }
            _securityTokenManager = credentialProvider.CreateSecurityTokenManager();
        }
        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();
        }
        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);
        }
Exemplo n.º 10
0
        static PeerSecurityCredentialsManager GetCredentialsManager(PeerAuthenticationMode mode, bool signing, BindingContext context)
        {
            if (mode == PeerAuthenticationMode.None && !signing)
            {
                return(null);
            }
            ClientCredentials clientCredentials = context.BindingParameters.Find <ClientCredentials>();

            if (clientCredentials != null)
            {
                return(new PeerSecurityCredentialsManager(clientCredentials.Peer, mode, signing));
            }
            ServiceCredentials serviceCredentials = context.BindingParameters.Find <ServiceCredentials>();

            if (serviceCredentials != null)
            {
                return(new PeerSecurityCredentialsManager(serviceCredentials.Peer, mode, signing));
            }
            SecurityCredentialsManager credman = context.BindingParameters.Find <SecurityCredentialsManager>();

            if (credman == null)
            {
                PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.Credentials);
            }
            return(new PeerSecurityCredentialsManager(credman.CreateSecurityTokenManager(), mode, signing));
        }
Exemplo n.º 11
0
        void InitializeSecurityTokenManager(BindingContext context)
        {
            SecurityCredentialsManager credentials = context.BindingParameters.Find <SecurityCredentialsManager>();

            if (credentials != null)
            {
                this.securityTokenManager = credentials.CreateSecurityTokenManager();
            }
        }
Exemplo n.º 12
0
        public static SslStreamSecurityUpgradeProvider CreateClientProvider(SslStreamSecurityBindingElement bindingElement, BindingContext context)
        {
            SecurityCredentialsManager manager = context.BindingParameters.Find <SecurityCredentialsManager>();

            if (manager == null)
            {
                manager = ClientCredentials.CreateDefaultCredentials();
            }
            return(new SslStreamSecurityUpgradeProvider(context.Binding, manager.CreateSecurityTokenManager(), bindingElement.RequireClientCertificate, context.Binding.Scheme, bindingElement.IdentityVerifier));
        }
Exemplo n.º 13
0
        internal HttpChannelFactory(HttpTransportBindingElement bindingElement, BindingContext context)
            : base(bindingElement, context, HttpTransportDefaults.GetDefaultMessageEncoderFactory())
        {
            // validate setting interactions
            if (bindingElement.TransferMode == TransferMode.Buffered)
            {
                if (bindingElement.MaxReceivedMessageSize > int.MaxValue)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize",
                                                              SR.MaxReceivedMessageSizeMustBeInIntegerRange));
                }

                if (bindingElement.MaxBufferSize != bindingElement.MaxReceivedMessageSize)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
                                                                                 SR.MaxBufferSizeMustMatchMaxReceivedMessageSize);
                }
            }
            else
            {
                if (bindingElement.MaxBufferSize > bindingElement.MaxReceivedMessageSize)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
                                                                                 SR.MaxBufferSizeMustNotExceedMaxReceivedMessageSize);
                }
            }

            if (TransferModeHelper.IsRequestStreamed(bindingElement.TransferMode) &&
                bindingElement.AuthenticationScheme != AuthenticationSchemes.Anonymous)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
                                                                             SR.HttpAuthDoesNotSupportRequestStreaming);
            }

            _allowCookies = bindingElement.AllowCookies;

            if (_allowCookies)
            {
                _httpCookieContainerManager = new HttpCookieContainerManager();
            }

            if (!bindingElement.AuthenticationScheme.IsSingleton())
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.Format(SR.HttpRequiresSingleAuthScheme,
                                                                                                bindingElement.AuthenticationScheme));
            }
            _authenticationScheme = bindingElement.AuthenticationScheme;
            _maxBufferSize        = bindingElement.MaxBufferSize;
            _transferMode         = bindingElement.TransferMode;
            _useDefaultWebProxy   = bindingElement.UseDefaultWebProxy;

            _channelCredentials   = context.BindingParameters.Find <SecurityCredentialsManager>();
            _securityCapabilities = bindingElement.GetProperty <ISecurityCapabilities>(context);
        }
Exemplo n.º 14
0
        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();
        }
        void IServiceBehavior.AddBindingParameters(System.ServiceModel.Description.ServiceDescription description, ServiceHostBase serviceHostBase, Collection <ServiceEndpoint> endpoints, BindingParameterCollection parameters)
        {
            if (parameters == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters");
            }
            SecurityCredentialsManager manager = parameters.Find <SecurityCredentialsManager>();

            if (manager != null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("MultipleSecurityCredentialsManagersInServiceBindingParameters", new object[] { manager })));
            }
            parameters.Add(this);
        }
Exemplo n.º 16
0
        void IEndpointBehavior.AddBindingParameters(ServiceEndpoint serviceEndpoint, BindingParameterCollection bindingParameters)
        {
            if (bindingParameters == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("bindingParameters");
            }
            SecurityCredentialsManager manager = bindingParameters.Find <SecurityCredentialsManager>();

            if (manager != null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("MultipleSecurityCredentialsManagersInChannelBindingParameters", new object[] { manager })));
            }
            bindingParameters.Add(this);
        }
Exemplo n.º 17
0
        void IServiceBehavior.AddBindingParameters(ServiceDescription description, ServiceHostBase serviceHostBase, Collection <ServiceEndpoint> endpoints, BindingParameterCollection parameters)
        {
            if (parameters == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(parameters));
            }
            // throw if bindingParameters already has a SecurityCredentialsManager
            SecurityCredentialsManager otherCredentialsManager = parameters.Find <SecurityCredentialsManager>();

            if (otherCredentialsManager != null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.MultipleSecurityCredentialsManagersInServiceBindingParameters, otherCredentialsManager)));
            }
            parameters.Add(this);
        }
Exemplo n.º 18
0
        void IEndpointBehavior.AddBindingParameters(ServiceEndpoint serviceEndpoint, BindingParameterCollection bindingParameters)
        {
            if (bindingParameters == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("bindingParameters");
            }
            // throw if bindingParameters already has a SecurityCredentialsManager
            SecurityCredentialsManager otherCredentialsManager = bindingParameters.Find <SecurityCredentialsManager>();

            if (otherCredentialsManager != null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.MultipleSecurityCredentialsManagersInChannelBindingParameters, otherCredentialsManager)));
            }
            bindingParameters.Add(this);
        }
Exemplo n.º 19
0
        private static HandshakeDelegate BuildHandshakeDelegateForDispatcher(IServiceDispatcher dispatcher)
        {
            BindingElementCollection                  be     = dispatcher.Binding.CreateBindingElements();
            MessageEncodingBindingElement             mebe   = be.Find <MessageEncodingBindingElement>();
            MessageEncoderFactory                     mefact = mebe.CreateMessageEncoderFactory();
            ConnectionOrientedTransportBindingElement tbe    = be.Find <ConnectionOrientedTransportBindingElement>();
            int                   maxReceivedMessageSize     = (int)Math.Min(tbe.MaxReceivedMessageSize, int.MaxValue);
            int                   maxBufferSize          = tbe.MaxBufferSize;
            var                   bufferManager          = BufferManager.CreateBufferManager(tbe.MaxBufferPoolSize, maxReceivedMessageSize);
            int                   connectionBufferSize   = tbe.ConnectionBufferSize;
            TransferMode          transferMode           = tbe.TransferMode;
            var                   upgradeBindingElements = (from element in be where element is StreamUpgradeBindingElement select element).Cast <StreamUpgradeBindingElement>().ToList();
            StreamUpgradeProvider streamUpgradeProvider  = null;
            ISecurityCapabilities securityCapabilities   = null;

            if (upgradeBindingElements.Count > 1)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.MultipleStreamUpgradeProvidersInParameters));
            }
            // TODO: Limit NamedPipes to prevent it using SslStreamSecurityUpgradeProvider
            else if ((upgradeBindingElements.Count == 1) /*&& this.SupportsUpgrade(upgradeBindingElements[0])*/)
            {
                SecurityCredentialsManager credentialsManager = dispatcher.Host.Description.Behaviors.Find <SecurityCredentialsManager>();
                var bindingContext = new BindingContext(new CustomBinding(dispatcher.Binding), new BindingParameterCollection());

                if (credentialsManager != null)
                {
                    bindingContext.BindingParameters.Add(credentialsManager);
                }

                streamUpgradeProvider = upgradeBindingElements[0].BuildServerStreamUpgradeProvider(bindingContext);
                streamUpgradeProvider.OpenAsync().GetAwaiter().GetResult();
                securityCapabilities = upgradeBindingElements[0].GetProperty <ISecurityCapabilities>(bindingContext);
            }
            return((connection) =>
            {
                connection.MessageEncoderFactory = mefact;
                connection.StreamUpgradeAcceptor = streamUpgradeProvider?.CreateUpgradeAcceptor();
                connection.SecurityCapabilities = securityCapabilities;
                connection.ServiceDispatcher = dispatcher;
                connection.BufferManager = bufferManager;
                connection.MaxReceivedMessageSize = maxReceivedMessageSize;
                connection.MaxBufferSize = maxBufferSize;
                connection.ConnectionBufferSize = connectionBufferSize;
                connection.TransferMode = transferMode;
                return Task.CompletedTask;
            });
        }
        protected override IChannelFactory <TChannel> BuildChannelFactoryCore <TChannel>(BindingContext context)
        {
            ISecurityCapabilities property             = this.GetProperty <ISecurityCapabilities>(context);
            bool           addChannelDemuxerIfRequired = this.RequiresChannelDemuxer();
            ChannelBuilder builder = new ChannelBuilder(context, addChannelDemuxerIfRequired);

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

            if (credentialsManager == null)
            {
                credentialsManager = ClientCredentials.CreateDefaultCredentials();
            }
            return(new SecurityChannelFactory <TChannel>(property, context, builder, this.CreateSecurityProtocolFactory <TChannel>(context, credentialsManager, false, issuanceBindingContext)));
        }
 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);
     }
 }
        public WindowsStreamSecurityUpgradeProvider(WindowsStreamSecurityBindingElement bindingElement,
                                                    BindingContext context, bool isClient)
            : base(context.Binding)
        {
            Contract.Assert(isClient, ".NET Core and .NET Native does not support server side");

            _extractGroupsForWindowsAccounts = TransportDefaults.ExtractGroupsForWindowsAccounts;
            _protectionLevel = bindingElement.ProtectionLevel;
            _scheme          = context.Binding.Scheme;
            _isClient        = isClient;
            _listenUri       = TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);

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

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

            _securityTokenManager = credentialProvider.CreateSecurityTokenManager();
        }
 public HttpChannelListener(HttpTransportBindingElement bindingElement, BindingContext context) : base(bindingElement, context, HttpTransportDefaults.GetDefaultMessageEncoderFactory(), bindingElement.HostNameComparisonMode)
 {
     if (bindingElement.TransferMode == System.ServiceModel.TransferMode.Buffered)
     {
         if (bindingElement.MaxReceivedMessageSize > 0x7fffffffL)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize", System.ServiceModel.SR.GetString("MaxReceivedMessageSizeMustBeInIntegerRange")));
         }
         if (bindingElement.MaxBufferSize != bindingElement.MaxReceivedMessageSize)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement", System.ServiceModel.SR.GetString("MaxBufferSizeMustMatchMaxReceivedMessageSize"));
         }
     }
     else if (bindingElement.MaxBufferSize > bindingElement.MaxReceivedMessageSize)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement", System.ServiceModel.SR.GetString("MaxBufferSizeMustNotExceedMaxReceivedMessageSize"));
     }
     if ((bindingElement.AuthenticationScheme == AuthenticationSchemes.Basic) && (bindingElement.ExtendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.Always))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.ServiceModel.SR.GetString("ExtendedProtectionPolicyBasicAuthNotSupported")));
     }
     this.authenticationScheme       = bindingElement.AuthenticationScheme;
     this.keepAliveEnabled           = bindingElement.KeepAliveEnabled;
     base.InheritBaseAddressSettings = bindingElement.InheritBaseAddressSettings;
     this.maxBufferSize = bindingElement.MaxBufferSize;
     this.method        = bindingElement.Method;
     this.realm         = bindingElement.Realm;
     this.transferMode  = bindingElement.TransferMode;
     this.unsafeConnectionNtlmAuthentication = bindingElement.UnsafeConnectionNtlmAuthentication;
     this.credentialProvider       = context.BindingParameters.Find <SecurityCredentialsManager>();
     this.acceptor                 = new TransportReplyChannelAcceptor(this);
     this.securityCapabilities     = bindingElement.GetProperty <ISecurityCapabilities>(context);
     this.extendedProtectionPolicy = GetPolicyWithDefaultSpnCollection(bindingElement.ExtendedProtectionPolicy, this.authenticationScheme, base.HostNameComparisonModeInternal, base.Uri, out this.usingDefaultSpnList);
     if (bindingElement.AnonymousUriPrefixMatcher != null)
     {
         this.anonymousUriPrefixMatcher = new HttpAnonymousUriPrefixMatcher(bindingElement.AnonymousUriPrefixMatcher);
     }
 }
        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 IChannelFactory <TChannel> BuildChannelFactoryCore <TChannel>(BindingContext context)
        {
            ISecurityCapabilities securityCapabilities = this.GetProperty <ISecurityCapabilities>(context);
            bool           requireDemuxer = RequiresChannelDemuxer();
            ChannelBuilder channelBuilder = new ChannelBuilder(context, requireDemuxer);

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

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

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

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

            return(new SecurityChannelFactory <TChannel>(securityCapabilities, context, channelBuilder, protocolFactory));
        }
Exemplo n.º 26
0
 internal abstract SecurityProtocolFactory CreateSecurityProtocolFactory <TChannel>(BindingContext context, SecurityCredentialsManager credentialsManager,
                                                                                    bool isForService, BindingContext issuanceBindingContext);
        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);
        }
Exemplo n.º 28
0
        internal HttpChannelFactory(HttpTransportBindingElement bindingElement, BindingContext context)
            : base(bindingElement, context, HttpTransportDefaults.GetDefaultMessageEncoderFactory())
        {
            // validate setting interactions
            if (bindingElement.TransferMode == TransferMode.Buffered)
            {
                if (bindingElement.MaxReceivedMessageSize > int.MaxValue)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize",
                                                              SR.MaxReceivedMessageSizeMustBeInIntegerRange));
                }

                if (bindingElement.MaxBufferSize != bindingElement.MaxReceivedMessageSize)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
                                                                                 SR.MaxBufferSizeMustMatchMaxReceivedMessageSize);
                }
            }
            else
            {
                if (bindingElement.MaxBufferSize > bindingElement.MaxReceivedMessageSize)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
                                                                                 SR.MaxBufferSizeMustNotExceedMaxReceivedMessageSize);
                }
            }

            if (TransferModeHelper.IsRequestStreamed(bindingElement.TransferMode) &&
                bindingElement.AuthenticationScheme != AuthenticationSchemes.Anonymous)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
                                                                             SR.HttpAuthDoesNotSupportRequestStreaming);
            }

            _allowCookies = bindingElement.AllowCookies;

            if (_allowCookies)
            {
                _httpCookieContainerManager = new HttpCookieContainerManager();
            }

            if (!bindingElement.AuthenticationScheme.IsSingleton())
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.Format(SR.HttpRequiresSingleAuthScheme,
                                                                                                bindingElement.AuthenticationScheme));
            }
            _authenticationScheme = bindingElement.AuthenticationScheme;
            _maxBufferSize        = bindingElement.MaxBufferSize;
            _transferMode         = bindingElement.TransferMode;
            _useDefaultWebProxy   = bindingElement.UseDefaultWebProxy;

            _channelCredentials   = context.BindingParameters.Find <SecurityCredentialsManager>();
            _securityCapabilities = bindingElement.GetProperty <ISecurityCapabilities>(context);

            _webSocketSettings = WebSocketHelper.GetRuntimeWebSocketSettings(bindingElement.WebSocketSettings);
            int webSocketBufferSize = WebSocketHelper.ComputeClientBufferSize(MaxReceivedMessageSize);

            _bufferPool               = new ConnectionBufferPool(webSocketBufferSize);
            _clientWebSocketFactory   = ClientWebSocketFactory.GetFactory();
            _webSocketSoapContentType = new Lazy <string>(() => MessageEncoderFactory.CreateSessionEncoder().ContentType, LazyThreadSafetyMode.ExecutionAndPublication);
        }
        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);
        }
        internal override SecurityProtocolFactory CreateSecurityProtocolFactory <TChannel>(BindingContext context, SecurityCredentialsManager credentialsManager, bool isForService, BindingContext issuerBindingContext)
        {
            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(context));
            }

            if (credentialsManager == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(credentialsManager));
            }

            TransportSecurityProtocolFactory protocolFactory = new TransportSecurityProtocolFactory();

            // if (isForService)
            //     base.ApplyAuditBehaviorSettings(context, protocolFactory);
            ConfigureProtocolFactory(protocolFactory, credentialsManager, isForService, issuerBindingContext, context.Binding);
            protocolFactory.DetectReplays = false;

            return(protocolFactory);
        }