internal static bool TryCreate(SecurityBindingElement sbe, TransportBindingElement transport, PrivacyNoticeBindingElement privacy, ReliableSessionBindingElement rsbe, TransactionFlowBindingElement tfbe, out Binding binding)
 {
     WSFederationHttpSecurityMode mode;
     WSFederationHttpSecurity security2;
     bool isReliableSession = rsbe != null;
     binding = null;
     HttpTransportSecurity transportSecurity = new HttpTransportSecurity();
     if (!WSFederationHttpBinding.GetSecurityModeFromTransport(transport, transportSecurity, out mode))
     {
         return false;
     }
     HttpsTransportBindingElement element = transport as HttpsTransportBindingElement;
     if (((element != null) && (element.MessageSecurityVersion != null)) && (element.MessageSecurityVersion.SecurityPolicyVersion != WS2007MessageSecurityVersion.SecurityPolicyVersion))
     {
         return false;
     }
     if (TryCreateSecurity(sbe, mode, transportSecurity, isReliableSession, out security2))
     {
         binding = new WS2007FederationHttpBinding(security2, privacy, isReliableSession);
     }
     if ((rsbe != null) && (rsbe.ReliableMessagingVersion != ReliableMessagingVersion.WSReliableMessaging11))
     {
         return false;
     }
     if ((tfbe != null) && (tfbe.TransactionProtocol != TransactionProtocol.WSAtomicTransaction11))
     {
         return false;
     }
     return (binding != null);
 }
Exemplo n.º 2
0
 protected virtual SecurityBindingElement ApplyMessageSecurity(SecurityBindingElement securityBindingElement)
 {
     if (securityBindingElement == null)
     {
         throw new ArgumentNullException("securityBindingElement");
     }
     
     if (TrustVersion.WSTrustFeb2005 == _trustVersion)
     {
         securityBindingElement.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
     }
     else
     {
         securityBindingElement.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;
     }
     
     if (_enableRsaProofKeys)
     {
         RsaSecurityTokenParameters item = new RsaSecurityTokenParameters
         {
             InclusionMode = SecurityTokenInclusionMode.Never,
             RequireDerivedKeys = false
         };
         securityBindingElement.OptionalEndpointSupportingTokenParameters.Endorsing.Add(item);
     }
     
     return securityBindingElement;
 }
 internal static bool TryCreate(SecurityBindingElement sbe, out MessageSecurityOverMsmq messageSecurity)
 {
     MessageCredentialType none;
     messageSecurity = null;
     if (sbe == null)
     {
         return false;
     }
     SymmetricSecurityBindingElement element = sbe as SymmetricSecurityBindingElement;
     if (element == null)
     {
         return false;
     }
     if ((sbe.MessageSecurityVersion != MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10) && (sbe.MessageSecurityVersion != MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11))
     {
         return false;
     }
     if (element.IncludeTimestamp)
     {
         return false;
     }
     bool flag = false;
     if (SecurityBindingElement.IsAnonymousForCertificateBinding(sbe))
     {
         none = MessageCredentialType.None;
     }
     else if (SecurityBindingElement.IsUserNameForCertificateBinding(sbe))
     {
         none = MessageCredentialType.UserName;
     }
     else if (SecurityBindingElement.IsMutualCertificateBinding(sbe))
     {
         none = MessageCredentialType.Certificate;
     }
     else if (SecurityBindingElement.IsKerberosBinding(sbe))
     {
         none = MessageCredentialType.Windows;
         flag = true;
     }
     else
     {
         IssuedSecurityTokenParameters parameters;
         if (!SecurityBindingElement.IsIssuedTokenForCertificateBinding(sbe, out parameters))
         {
             return false;
         }
         if (!IssuedSecurityTokenParameters.IsInfoCardParameters(parameters, new SecurityStandardsManager(sbe.MessageSecurityVersion, new WSSecurityTokenSerializer(sbe.MessageSecurityVersion.SecurityVersion, sbe.MessageSecurityVersion.TrustVersion, sbe.MessageSecurityVersion.SecureConversationVersion, true, null, null, null))))
         {
             return false;
         }
         none = MessageCredentialType.IssuedToken;
     }
     messageSecurity = new MessageSecurityOverMsmq();
     messageSecurity.ClientCredentialType = none;
     if ((none != MessageCredentialType.IssuedToken) && !flag)
     {
         messageSecurity.AlgorithmSuite = element.DefaultAlgorithmSuite;
     }
     return true;
 }
        private void Initialize()
        {
            _securityBindingElement = CreateSecurityBindingElement();

            _textEncodingBindingElement = CreateTextEncodingBindingElement();

            //_httpsTransportBindingElement = CreateHttpsTransportBindingElement();
            _httpTransportBindingElement = CreateHttpTransportBindingElement();
        }
 public SpnegoTokenProvider(System.IdentityModel.SafeFreeCredentials credentialsHandle, SecurityBindingElement securityBindingElement) : base(securityBindingElement)
 {
     this.allowedImpersonationLevel = TokenImpersonationLevel.Identification;
     this.identityVerifier = System.ServiceModel.Security.IdentityVerifier.CreateDefault();
     this.allowNtlm = true;
     this.authenticateServer = true;
     this.interactiveNegoExLogonEnabled = true;
     this.credentialsHandle = credentialsHandle;
 }
        private void Initialize()
        {
            _securityBindingElement = CreateSecurityBindingElement();

            _reliableSessionBindingElement = CreateReliableSessionBindingElement();

            _mtomEncodingBindingElement = CreateMtomEncodingBindingElement();

            _httpsTransportBindingElement = CreateHttpsTransportBindingElement() as HttpsTransportBindingElement;
        }
        protected SecureConversationSecurityTokenParameters(SecureConversationSecurityTokenParameters other)
            : base(other)
        {
            _requireCancellation = other._requireCancellation;
            _canRenewSession = other._canRenewSession;
            if (other._bootstrapSecurityBindingElement != null)
                _bootstrapSecurityBindingElement = (SecurityBindingElement)other._bootstrapSecurityBindingElement.Clone();

            if (other._issuerBindingContext != null)
                _issuerBindingContext = other._issuerBindingContext.Clone();
        }
		public SecureConversationSecurityTokenParameters (
			SecurityBindingElement element,
			bool requireCancellation,
			ChannelProtectionRequirements requirements)
		{
			this.element = element;
			this.cancellable = requireCancellation;
			if (requirements == null)
				this.requirements = new ChannelProtectionRequirements (default_channel_protection_requirements);
			else
				this.requirements = new ChannelProtectionRequirements (requirements);
		}
 protected SecureConversationSecurityTokenParameters(SecureConversationSecurityTokenParameters other)
     : base(other)
 {
     this.requireCancellation = other.requireCancellation;
     this.canRenewSession = other.canRenewSession;
     if (other.bootstrapSecurityBindingElement != null)
         this.bootstrapSecurityBindingElement = (SecurityBindingElement)other.bootstrapSecurityBindingElement.Clone();
     if (other.bootstrapProtectionRequirements != null)
         this.bootstrapProtectionRequirements = new ChannelProtectionRequirements(other.bootstrapProtectionRequirements);
     if (other.issuerBindingContext != null)
         this.issuerBindingContext = other.issuerBindingContext.Clone();
 }
        private void Initialize()
        {
            _securityBindingElement = CreateSecurityBindingElement();
            //_securityBindingElement = CreateTransportSecurityBindingElement();

            _reliableSessionBindingElement = CreateReliableSessionBindingElement();

            //binding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11WSAddressing10, Encoding.UTF8));

            _mtomEncodingBindingElement = CreateMtomEncodingBindingElement();

            _httpsTransportBindingElement = CreateHttpsTransportBindingElement() as HttpsTransportBindingElement;
        }
 static IEnumerable<SecurityTokenParameters> EnumerateNestedTokenParameters(SecurityBindingElement element)
 {
     foreach (SecurityTokenParameters parameters in EnumerateTokenParameters(element))
     {
         if (parameters is SecureConversationSecurityTokenParameters)
         {
             SecurityBindingElement nestedElement = ((SecureConversationSecurityTokenParameters)parameters).BootstrapSecurityBindingElement;
             foreach (SecurityTokenParameters nestedParameters in EnumerateTokenParameters(nestedElement))
             {
                 yield return nestedParameters;
             }
         }
     }
 }
        // This is effectively just a copy of WSHttpBinding.TryCreate(), only it news up the 2007 version
        internal new static bool TryCreate(SecurityBindingElement sbe, TransportBindingElement transport, ReliableSessionBindingElement rsbe, TransactionFlowBindingElement tfbe, out Binding binding)
        {
            bool isReliableSession = (rsbe != null);
            binding = null;

            // reverse GetTransport
            HttpTransportSecurity transportSecurity = WSHttpSecurity.GetDefaultHttpTransportSecurity();
            UnifiedSecurityMode mode;
            if (!WSHttpBinding.GetSecurityModeFromTransport(transport, transportSecurity, out mode))
            {
                return false;
            }

            HttpsTransportBindingElement httpsBinding = transport as HttpsTransportBindingElement;
            if (httpsBinding != null && httpsBinding.MessageSecurityVersion != null)
            {
                if (httpsBinding.MessageSecurityVersion.SecurityPolicyVersion != WS2007MessageSecurityVersion.SecurityPolicyVersion)
                {
                    return false;
                }
            }

            WSHttpSecurity security;
            if (WS2007HttpBinding.TryCreateSecurity(sbe, mode, transportSecurity, isReliableSession, out security))
            {
                WS2007HttpBinding ws2007HttpBinding = new WS2007HttpBinding(security, isReliableSession);

                bool allowCookies;
                if (!WSHttpBinding.TryGetAllowCookiesFromTransport(transport, out allowCookies))
                {
                    return false;
                }

                ws2007HttpBinding.AllowCookies = allowCookies;
                binding = ws2007HttpBinding;
            }

            if (rsbe != null && rsbe.ReliableMessagingVersion != ReliableMessagingVersion.WSReliableMessaging11)
            {
                return false;
            }

            if (tfbe != null && tfbe.TransactionProtocol != TransactionProtocol.WSAtomicTransaction11)
            {
                return false;
            }

            return binding != null;
        }
 internal static bool TryCreate(SecurityBindingElement sbe, NetMsmqSecurityMode mode, out NetMsmqSecurity security)
 {
     MessageSecurityOverMsmq msmq;
     security = null;
     if (!MessageSecurityOverMsmq.TryCreate(sbe, out msmq))
     {
         msmq = null;
     }
     security = new NetMsmqSecurity(mode, null, msmq);
     if (sbe != null)
     {
         return SecurityElementBase.AreBindingsMatching(security.CreateMessageSecurity(), sbe, false);
     }
     return true;
 }
 private static bool HasSupportingTokens(SecurityBindingElement binding)
 {
     if (((binding.EndpointSupportingTokenParameters.Endorsing.Count > 0) || (binding.EndpointSupportingTokenParameters.SignedEndorsing.Count > 0)) || ((binding.EndpointSupportingTokenParameters.SignedEncrypted.Count > 0) || (binding.EndpointSupportingTokenParameters.Signed.Count > 0)))
     {
         return true;
     }
     foreach (SupportingTokenParameters parameters in binding.OperationSupportingTokenParameters.Values)
     {
         if (((parameters.Endorsing.Count > 0) || (parameters.SignedEndorsing.Count > 0)) || ((parameters.SignedEncrypted.Count > 0) || (parameters.Signed.Count > 0)))
         {
             return true;
         }
     }
     return false;
 }
 internal static bool TryCreate(SecurityBindingElement sbe, out WSDualHttpSecurity security)
 {
     security = null;
     if (sbe == null)
         security = new WSDualHttpSecurity(WSDualHttpSecurityMode.None, null);
     else
     {
         MessageSecurityOverHttp messageSecurity;
         if (!MessageSecurityOverHttp.TryCreate(sbe, false, true, out messageSecurity))
             return false;
         security = new WSDualHttpSecurity(WSDualHttpSecurityMode.Message, messageSecurity);
     }
     // the last check: make sure that security binding element match the incoming security
     return SecurityElement.AreBindingsMatching(security.CreateMessageSecurity(), sbe);
 }
        protected override SecurityBindingElement CreateMessageSecurity()
        {
            SymmetricSecurityBindingElement element =
                new SymmetricSecurityBindingElement();

            element.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;

//			if (!Security.Message.EstablishSecurityContext)
//				element.SetKeyDerivation (false);

            IssuedSecurityTokenParameters istp =
                new IssuedSecurityTokenParameters();

            // FIXME: issuer binding must be secure.
            istp.IssuerBinding = new CustomBinding(
                new TextMessageEncodingBindingElement(),
                GetTransport());
            element.EndpointSupportingTokenParameters.Endorsing.Add(istp);

            if (Security.Message.NegotiateServiceCredential)
            {
                element.ProtectionTokenParameters =
                    // FIXME: fill proper parameters
                    new SslSecurityTokenParameters(false, true);
            }
            else
            {
                element.ProtectionTokenParameters =
                    new X509SecurityTokenParameters();
            }

//			if (!Security.Message.EstablishSecurityContext)
//				return element;

            // SecureConversation enabled

            ChannelProtectionRequirements reqs =
                new ChannelProtectionRequirements();

            // FIXME: fill the reqs

            // FIXME: for TransportWithMessageCredential mode,
            // return TransportSecurityBindingElement.

            return(SecurityBindingElement.CreateSecureConversationBindingElement(
                       // FIXME: requireCancellation
                       element, true, reqs));
        }
        void ImportOperationScopeSupportingTokensPolicy(MetadataImporter importer, PolicyConversionContext policyContext, SecurityBindingElement binding)
        {
            foreach (OperationDescription operation in policyContext.Contract.Operations)
            {
                string requestAction = null;
                foreach (MessageDescription message in operation.Messages)
                {
                    if (message.Direction == MessageDirection.Input)
                    {
                        requestAction = message.Action;
                        break;
                    }
                }

                SupportingTokenParameters requirements = new SupportingTokenParameters();
                SupportingTokenParameters optionalRequirements = new SupportingTokenParameters();
                ICollection<XmlElement> operationBindingAssertions = policyContext.GetOperationBindingAssertions(operation);
                this.ImportSupportingTokenAssertions(importer, policyContext, operationBindingAssertions, requirements, optionalRequirements);
                if (requirements.Endorsing.Count > 0
                    || requirements.Signed.Count > 0
                    || requirements.SignedEncrypted.Count > 0
                    || requirements.SignedEndorsing.Count > 0)
                {
                    if (requestAction != null)
                    {
                        binding.OperationSupportingTokenParameters[requestAction] = requirements;
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.CannotImportSupportingTokensForOperationWithoutRequestAction)));
                    }
                }
                if (optionalRequirements.Endorsing.Count > 0
                    || optionalRequirements.Signed.Count > 0
                    || optionalRequirements.SignedEncrypted.Count > 0
                    || optionalRequirements.SignedEndorsing.Count > 0)
                {
                    if (requestAction != null)
                    {
                        binding.OptionalOperationSupportingTokenParameters[requestAction] = optionalRequirements;
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.CannotImportSupportingTokensForOperationWithoutRequestAction)));
                    }
                }
            }
        }
Exemplo n.º 18
0
 public SecureConversationSecurityTokenParameters(
     SecurityBindingElement element,
     bool requireCancellation,
     ChannelProtectionRequirements requirements)
 {
     this.element     = element;
     this.cancellable = requireCancellation;
     if (requirements == null)
     {
         this.requirements = new ChannelProtectionRequirements(default_channel_protection_requirements);
     }
     else
     {
         this.requirements = new ChannelProtectionRequirements(requirements);
     }
 }
Exemplo n.º 19
0
        public override BindingElementCollection CreateBindingElements()
        {
            BindingElement security = SecurityBindingElement.CreateSecureConversationBindingElement(
                SecurityBindingElement.CreateUserNameForSslBindingElement(true));


            MessageEncodingBindingElement encoding =
                (MessageEncodingBindingElement) new BinaryMessageEncodingBindingElement();

            return(new BindingElementCollection(new[]
            {
                security,
                encoding,
                transport,
            }));
        }
        SecurityStandardsManager GetConfiguredSecurityStandardsManager(Binding binding)
        {
            if (binding == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("binding");
            }

            SecurityBindingElement securityBindingElement = binding.CreateBindingElements().Find <SecurityBindingElement>();

            if (securityBindingElement == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("binding", SR.GetString(SR.NoSecurityBindingElementFound));
            }

            return(new SecurityStandardsManager(securityBindingElement.MessageSecurityVersion, new WSSecurityTokenSerializer(securityBindingElement.MessageSecurityVersion.SecurityVersion)));
        }
Exemplo n.º 21
0
        public static Binding CreateCustomBinding()
        {
            //<snippet20>
            // Create an empty CustomBinding to populate
            CustomBinding binding = new CustomBinding();
            // Create a SymmetricSecurityBindingElement.
            SymmetricSecurityBindingElement ssbe =
                SecurityBindingElement.CreateSspiNegotiationBindingElement(true);

            // Add the SymmetricSecurityBindingElement to the BindingElementCollection.
            binding.Elements.Add(ssbe);
            binding.Elements.Add(new TextMessageEncodingBindingElement());
            binding.Elements.Add(new HttpTransportBindingElement());
            return(new CustomBinding(binding));
            //</snippet20>
        }
Exemplo n.º 22
0
        internal static bool TryCreate(SecurityBindingElement sbe, NetMsmqSecurityMode mode, out NetMsmqSecurity security)
        {
            MessageSecurityOverMsmq msmq;

            security = null;
            if (!MessageSecurityOverMsmq.TryCreate(sbe, out msmq))
            {
                msmq = null;
            }
            security = new NetMsmqSecurity(mode, null, msmq);
            if (sbe != null)
            {
                return(SecurityElementBase.AreBindingsMatching(security.CreateMessageSecurity(), sbe, false));
            }
            return(true);
        }
        static bool BindingRequiresAuthentication(BindingElementCollection elements)
        {
            SecurityBindingElement element = elements.Find <SecurityBindingElement>();

            if (element != null)
            {
                foreach (SecurityTokenParameters parameters in EnumerateNestedTokenParameters(element))
                {
                    if (parameters is SspiSecurityTokenParameters)
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
        SecurityTokenAuthenticator CreateTlsnegoSecurityTokenAuthenticator(RecipientServiceModelSecurityTokenRequirement recipientRequirement, bool requireClientCertificate, out SecurityTokenResolver sctResolver)
        {
            SecurityBindingElement securityBindingElement = recipientRequirement.SecurityBindingElement;

            if (securityBindingElement == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.TokenAuthenticatorRequiresSecurityBindingElement, recipientRequirement));
            }
            bool isCookieMode = !recipientRequirement.SupportSecurityContextCancellation;
            LocalServiceSecuritySettings localServiceSettings = securityBindingElement.LocalServiceSettings;

            sctResolver = new SecurityContextSecurityTokenResolver(localServiceSettings.MaxCachedCookies, true);

            TlsnegoTokenAuthenticator authenticator = new TlsnegoTokenAuthenticator();

            authenticator.IsClientAnonymous = !requireClientCertificate;
            if (requireClientCertificate)
            {
                authenticator.ClientTokenAuthenticator       = this.CreateTlsnegoClientX509TokenAuthenticator(recipientRequirement);
                authenticator.MapCertificateToWindowsAccount = this.ServiceCredentials.ClientCertificate.Authentication.MapClientCertificateToWindowsAccount;
            }
            authenticator.EncryptStateInServiceToken    = isCookieMode;
            authenticator.IssuedSecurityTokenParameters = recipientRequirement.GetProperty <SecurityTokenParameters>(ServiceModelSecurityTokenRequirement.IssuedSecurityTokenParametersProperty);
            authenticator.IssuedTokenCache       = (ISecurityContextSecurityTokenCache)sctResolver;
            authenticator.IssuerBindingContext   = recipientRequirement.GetProperty <BindingContext>(ServiceModelSecurityTokenRequirement.IssuerBindingContextProperty);
            authenticator.ListenUri              = recipientRequirement.ListenUri;
            authenticator.SecurityAlgorithmSuite = recipientRequirement.SecurityAlgorithmSuite;
            authenticator.StandardsManager       = SecurityUtils.CreateSecurityStandardsManager(recipientRequirement, this);
            authenticator.SecurityStateEncoder   = parent.SecureConversationAuthentication.SecurityStateEncoder;
            authenticator.KnownTypes             = parent.SecureConversationAuthentication.SecurityContextClaimTypes;
            authenticator.ServerTokenProvider    = CreateTlsnegoServerX509TokenProvider(recipientRequirement);
            // local security quotas
            authenticator.MaximumCachedNegotiationState = localServiceSettings.MaxStatefulNegotiations;
            authenticator.NegotiationTimeout            = localServiceSettings.NegotiationTimeout;
            authenticator.ServiceTokenLifetime          = localServiceSettings.IssuedCookieLifetime;
            authenticator.MaximumConcurrentNegotiations = localServiceSettings.MaxStatefulNegotiations;
            // if the TLSNEGO is being done in mixed-mode, the nego blobs are from an anonymous client and so there size bound needs to be enforced.
            if (securityBindingElement is TransportSecurityBindingElement)
            {
                authenticator.MaxMessageSize = SecurityUtils.GetMaxNegotiationBufferSize(authenticator.IssuerBindingContext);
            }
            // audit settings
            authenticator.AuditLogLocation                = recipientRequirement.AuditLogLocation;
            authenticator.SuppressAuditFailure            = recipientRequirement.SuppressAuditFailure;
            authenticator.MessageAuthenticationAuditLevel = recipientRequirement.MessageAuthenticationAuditLevel;
            return(authenticator);
        }
        internal static bool TryCreate(SecurityBindingElement sbe, out BasicHttpMessageSecurity security, out bool isSecureTransportMode)
        {
            BasicHttpMessageCredentialType userName;

            security = null;
            isSecureTransportMode = false;
            if (!sbe.DoNotEmitTrust)
            {
                return(false);
            }
            if (!sbe.IsSetKeyDerivation(false))
            {
                return(false);
            }
            if (sbe.SecurityHeaderLayout != SecurityHeaderLayout.Lax)
            {
                return(false);
            }
            if (sbe.MessageSecurityVersion != MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10)
            {
                return(false);
            }
            if (!SecurityBindingElement.IsMutualCertificateBinding(sbe, true))
            {
                isSecureTransportMode = true;
                if (!SecurityBindingElement.IsCertificateOverTransportBinding(sbe))
                {
                    if (!SecurityBindingElement.IsUserNameOverTransportBinding(sbe))
                    {
                        return(false);
                    }
                    userName = BasicHttpMessageCredentialType.UserName;
                }
                else
                {
                    userName = BasicHttpMessageCredentialType.Certificate;
                }
            }
            else
            {
                userName = BasicHttpMessageCredentialType.Certificate;
            }
            security = new BasicHttpMessageSecurity();
            security.ClientCredentialType = userName;
            security.AlgorithmSuite       = sbe.DefaultAlgorithmSuite;
            return(true);
        }
Exemplo n.º 26
0
        // This method reverses the CreateMessageSecurity(bool) method
        internal static bool TryCreate(SecurityBindingElement sbe, out BasicHttpMessageSecurity security, out bool isSecureTransportMode)
        {
            Fx.Assert(null != sbe, string.Empty);

            security = null;
            isSecureTransportMode = false;

            if (!sbe.IsSetKeyDerivation(false))
            {
                return(false);
            }
            if (sbe.SecurityHeaderLayout != SecurityHeaderLayout.Lax)
            {
                return(false);
            }
            if (sbe.MessageSecurityVersion != MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10)
            {
                return(false);
            }

            BasicHttpMessageCredentialType credentialType;

            if (!SecurityBindingElement.IsMutualCertificateBinding(sbe, true))
            {
                isSecureTransportMode = true;
                if (SecurityBindingElement.IsCertificateOverTransportBinding(sbe))
                {
                    credentialType = BasicHttpMessageCredentialType.Certificate;
                }
                else if (SecurityBindingElement.IsUserNameOverTransportBinding(sbe))
                {
                    credentialType = BasicHttpMessageCredentialType.UserName;
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                credentialType = BasicHttpMessageCredentialType.Certificate;
            }
            security = new BasicHttpMessageSecurity();
            security.ClientCredentialType = credentialType;

            return(true);
        }
Exemplo n.º 27
0
        static void Main(string[] args)
        {
            // Configure the issued token parameters with the correct settings
            IssuedSecurityTokenParameters itp = new IssuedSecurityTokenParameters("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1");

            itp.IssuerMetadataAddress = new EndpointAddress("http://localhost:6000/STS/mex");
            itp.IssuerAddress         = new EndpointAddress("http://localhost:6000/STS");

            // Create the security binding element
            SecurityBindingElement sbe = SecurityBindingElement.CreateIssuedTokenForCertificateBindingElement(itp);

            sbe.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;

            // Create the HTTP transport binding element
            HttpTransportBindingElement httpBE = new HttpTransportBindingElement();

            // Create the custom binding using the prepared binding elements
            CustomBinding binding = new CustomBinding(sbe, httpBE);

            Uri serviceUri = new Uri("http://localhost:6002/Service2");

            using (ServiceHost host = new ServiceHost(typeof(Service2), serviceUri))
            {
                host.AddServiceEndpoint(typeof(IService2), binding, "");
                host.Credentials.ServiceCertificate.SetCertificate("CN=localhost", StoreLocation.LocalMachine, StoreName.My);

                // Enable metadata generation via HTTP GET
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                host.Description.Behaviors.Add(smb);
                host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex");

                // Configure the service host to use the Windows Identity Foundation
                ServiceConfiguration configuration = new ServiceConfiguration();
                configuration.IssuerNameRegistry = new TrustedIssuerNameRegistry();
                configuration.SecurityTokenHandlers.Configuration.AudienceRestriction.AllowedAudienceUris.Add(serviceUri);

                FederatedServiceCredentials.ConfigureServiceHost(host, configuration);

                host.Open();

                Console.WriteLine("Service2 started, press ENTER to stop ...");
                Console.ReadLine();

                host.Close();
            }
        }
        internal SecurityBindingElement CreateMessageSecurity(bool isSecureTransportMode)
        {
            SecurityBindingElement algorithmSuite;

            if (!isSecureTransportMode)
            {
                if (this.clientCredentialType != BasicHttpMessageCredentialType.Certificate)
                {
                    throw Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(Microsoft.ServiceBus.SR.GetString(Resources.BasicHttpMessageSecurityRequiresCertificate, new object[0])));
                }
                algorithmSuite = SecurityBindingElement.CreateMutualCertificateBindingElement(MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10, true);
            }
            else
            {
                MessageSecurityVersion wSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10 = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
                switch (this.clientCredentialType)
                {
                case BasicHttpMessageCredentialType.UserName:
                {
                    algorithmSuite = SecurityBindingElement.CreateUserNameOverTransportBindingElement();
                    algorithmSuite.MessageSecurityVersion = wSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
                    algorithmSuite.DefaultAlgorithmSuite  = this.AlgorithmSuite;
                    algorithmSuite.SecurityHeaderLayout   = SecurityHeaderLayout.Lax;
                    algorithmSuite.SetKeyDerivation(false);
                    InvokeHelper.InvokeInstanceSet(algorithmSuite.GetType(), algorithmSuite, "DoNotEmitTrust", true);
                    return(algorithmSuite);
                }

                case BasicHttpMessageCredentialType.Certificate:
                {
                    algorithmSuite = SecurityBindingElement.CreateCertificateOverTransportBindingElement(wSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10);
                    algorithmSuite.DefaultAlgorithmSuite = this.AlgorithmSuite;
                    algorithmSuite.SecurityHeaderLayout  = SecurityHeaderLayout.Lax;
                    algorithmSuite.SetKeyDerivation(false);
                    InvokeHelper.InvokeInstanceSet(algorithmSuite.GetType(), algorithmSuite, "DoNotEmitTrust", true);
                    return(algorithmSuite);
                }
                }
                Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.DebugAssert("Unsupported basic http message credential type");
                throw Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
            }
            algorithmSuite.DefaultAlgorithmSuite = this.AlgorithmSuite;
            algorithmSuite.SecurityHeaderLayout  = SecurityHeaderLayout.Lax;
            algorithmSuite.SetKeyDerivation(false);
            InvokeHelper.InvokeInstanceSet(algorithmSuite.GetType(), algorithmSuite, "DoNotEmitTrust", true);
            return(algorithmSuite);
        }
Exemplo n.º 29
0
        private Binding CreateIssuedTokenOverTransportBinding()
        {
            var securityTokenParameters = new IssuedSecurityTokenParameters
            {
                KeyType       = SecurityKeyType.AsymmetricKey,
                IssuerBinding = CreateKerberosOverTransportBinding(),
            };

            var securityBindingElement = SecurityBindingElement.CreateIssuedTokenOverTransportBindingElement(securityTokenParameters);

            securityBindingElement.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;

            var customBinding = new CustomBinding("Custom");

            customBinding.Elements.Insert(0, securityBindingElement);
            return(customBinding);
        }
        private void InitializeKeyEntropyMode()
        {
            // Default to combined entropy unless another option is specified in the issuer's security binding element.
            // In previous versions of .NET WsTrust token providers, it was possible to set the default key entropy mode in client credentials.
            // That scenario does not seem to be needed in .NET Core WsTrust scenarios, so key entropy mode is simply being read from the issuer's
            // security binding element. If, in the future, it's necessary to change the default (if some scenarios don't have a security binding
            // element, for example), that could be done by adding a DefaultKeyEntropyMode property to WsTrustChannelCredentials and moving
            // the code that calculates KeyEntropyMode out to WSTrustChannelSecurityTokenManager since it can set this property
            // when it creates the provider and fall back to the credentials' default value if no security binding element is present.
            KeyEntropyMode = SecurityKeyEntropyMode.CombinedEntropy;
            SecurityBindingElement securityBindingElement = IssuerBinding?.CreateBindingElements().Find <SecurityBindingElement>();

            if (securityBindingElement != null)
            {
                KeyEntropyMode = securityBindingElement.KeyEntropyMode;
            }
        }
        private TrustVersion GetTrustVersion()
        {
            TrustVersion trustVersion = _trustVersion;

            if (trustVersion == null)
            {
                BindingElementCollection elements = Endpoint.Binding.CreateBindingElements();
                SecurityBindingElement   sbe      = elements.Find <SecurityBindingElement>();
                if (null == sbe)
                {
                    throw IM.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID3269)));
                }
                trustVersion = sbe.MessageSecurityVersion.TrustVersion;
            }

            return(trustVersion);
        }
Exemplo n.º 32
0
        private void CreateBinding()
        {
            //<snippet8>
            CustomBinding binding = new CustomBinding();

            // The following binding exposes a DNS identity.
            binding.Elements.Add(SecurityBindingElement.
                                 CreateSecureConversationBindingElement(
                                     SecurityBindingElement.
                                     CreateIssuedTokenForSslBindingElement(
                                         new IssuedSecurityTokenParameters())));

            // The following element requires a UPN or SPN identity.
            binding.Elements.Add(new WindowsStreamSecurityBindingElement());
            binding.Elements.Add(new TcpTransportBindingElement());
            //</snippet8>
        }
 public SecureConversationSecurityTokenParameters(SecurityBindingElement bootstrapSecurityBindingElement, bool requireCancellation, bool canRenewSession, ChannelProtectionRequirements bootstrapProtectionRequirements)
     : base()
 {
     this.bootstrapSecurityBindingElement = bootstrapSecurityBindingElement;
     this.canRenewSession = canRenewSession;
     if (bootstrapProtectionRequirements != null)
         this.bootstrapProtectionRequirements = new ChannelProtectionRequirements(bootstrapProtectionRequirements);
     else
     {
         this.bootstrapProtectionRequirements = new ChannelProtectionRequirements();
         this.bootstrapProtectionRequirements.IncomingEncryptionParts.AddParts(new MessagePartSpecification(true));
         this.bootstrapProtectionRequirements.IncomingSignatureParts.AddParts(new MessagePartSpecification(true));
         this.bootstrapProtectionRequirements.OutgoingEncryptionParts.AddParts(new MessagePartSpecification(true));
         this.bootstrapProtectionRequirements.OutgoingSignatureParts.AddParts(new MessagePartSpecification(true));
     }
     this.requireCancellation = requireCancellation;
 }
 internal static bool TryCreate(SecurityBindingElement sbe, out BasicHttpMessageSecurity security, out bool isSecureTransportMode)
 {
     BasicHttpMessageCredentialType userName;
     security = null;
     isSecureTransportMode = false;
     if (!sbe.DoNotEmitTrust)
     {
         return false;
     }
     if (!sbe.IsSetKeyDerivation(false))
     {
         return false;
     }
     if (sbe.SecurityHeaderLayout != SecurityHeaderLayout.Lax)
     {
         return false;
     }
     if (sbe.MessageSecurityVersion != MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10)
     {
         return false;
     }
     if (!SecurityBindingElement.IsMutualCertificateBinding(sbe, true))
     {
         isSecureTransportMode = true;
         if (!SecurityBindingElement.IsCertificateOverTransportBinding(sbe))
         {
             if (!SecurityBindingElement.IsUserNameOverTransportBinding(sbe))
             {
                 return false;
             }
             userName = BasicHttpMessageCredentialType.UserName;
         }
         else
         {
             userName = BasicHttpMessageCredentialType.Certificate;
         }
     }
     else
     {
         userName = BasicHttpMessageCredentialType.Certificate;
     }
     security = new BasicHttpMessageSecurity();
     security.ClientCredentialType = userName;
     security.AlgorithmSuite = sbe.DefaultAlgorithmSuite;
     return true;
 }
Exemplo n.º 35
0
        /// <summary>
        /// Initializes the binding.
        /// </summary>
        /// <param name="namespaceUris">The namespace uris.</param>
        /// <param name="factory">The factory.</param>
        /// <param name="configuration">The configuration.</param>
        /// <param name="description">The description.</param>
        public UaHttpsSoapBinding(
            NamespaceTable namespaceUris,
            EncodeableFactory factory,
            EndpointConfiguration configuration,
            EndpointDescription description)
            :
            base(namespaceUris, factory, configuration)
        {
            if (description != null && description.SecurityMode != MessageSecurityMode.None)
            {
                TransportSecurityBindingElement bootstrap = SecurityBindingElement.CreateUserNameOverTransportBindingElement();
                bootstrap.IncludeTimestamp       = true;
                bootstrap.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
                bootstrap.SecurityHeaderLayout   = SecurityHeaderLayout.Strict;

                m_security = SecurityBindingElement.CreateSecureConversationBindingElement(bootstrap);
                m_security.IncludeTimestamp       = true;
                m_security.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
                m_security.SecurityHeaderLayout   = SecurityHeaderLayout.Strict;
            }

            m_encoding = new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressing10, Encoding.UTF8);

            // WCF does not distinguish between arrays and byte string.
            int maxArrayLength = configuration.MaxArrayLength;

            if (configuration.MaxArrayLength < configuration.MaxByteStringLength)
            {
                maxArrayLength = configuration.MaxByteStringLength;
            }

            m_encoding.ReaderQuotas.MaxArrayLength         = maxArrayLength;
            m_encoding.ReaderQuotas.MaxStringContentLength = configuration.MaxStringLength;
            m_encoding.ReaderQuotas.MaxBytesPerRead        = Int32.MaxValue;
            m_encoding.ReaderQuotas.MaxDepth = Int32.MaxValue;
            m_encoding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;

            m_transport = new HttpsTransportBindingElement();

            m_transport.AllowCookies           = false;
            m_transport.AuthenticationScheme   = System.Net.AuthenticationSchemes.Anonymous;
            m_transport.ManualAddressing       = false;
            m_transport.MaxBufferSize          = configuration.MaxMessageSize;
            m_transport.MaxReceivedMessageSize = configuration.MaxMessageSize;
            m_transport.TransferMode           = TransferMode.Buffered;
        }
        protected override SecurityBindingElement CreateSecurityBindingElement()
        {
            SecurityBindingElement element;

            IssuedSecurityTokenParameters issuedParameters = new IssuedSecurityTokenParameters(this._tokenType, this._issuerAddress, this._issuerBinding)
            {
                KeyType = this._keyType,
                IssuerMetadataAddress = this._issuerMetadataAddress
            };

            if (this._keyType == SecurityKeyType.SymmetricKey)
            {
                issuedParameters.KeySize = this._algorithmSuite.DefaultSymmetricKeyLength;
            }
            else
            {
                issuedParameters.KeySize = 0;
            }

            if (this._claimTypeRequirements != null)
            {
                foreach (ClaimTypeRequirement requirement in this._claimTypeRequirements)
                {
                    issuedParameters.ClaimTypeRequirements.Add(requirement);
                }
            }

            this.AddAlgorithmParameters(this._algorithmSuite, base.TrustVersion, this._keyType, ref issuedParameters);
            if (SecurityMode.Message == base.SecurityMode)
            {
                element = SecurityBindingElement.CreateIssuedTokenForCertificateBindingElement(issuedParameters);
            }
            else
            {
                if (SecurityMode.TransportWithMessageCredential != base.SecurityMode)
                {
                    throw new InvalidOperationException("ID3226");
                }
                element = SecurityBindingElement.CreateIssuedTokenOverTransportBindingElement(issuedParameters);
            }

            element.DefaultAlgorithmSuite = this._algorithmSuite;
            element.IncludeTimestamp      = true;

            return(element);
        }
Exemplo n.º 37
0
        protected static T GetClient <T>(string endpoint, SecureString password)
        {
            //Create binding element for security
            var asymmetricSecurityBindingElement = (AsymmetricSecurityBindingElement)SecurityBindingElement.CreateMutualCertificateBindingElement(MessageSecurityVersion.
                                                                                                                                                  WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10
                                                                                                                                                  );

            asymmetricSecurityBindingElement.MessageSecurityVersion  = MessageSecurityVersion.WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;
            asymmetricSecurityBindingElement.EnableUnsecuredResponse = true;
            asymmetricSecurityBindingElement.MessageProtectionOrder  = MessageProtectionOrder.EncryptBeforeSign;
            asymmetricSecurityBindingElement.IncludeTimestamp        = true;
            asymmetricSecurityBindingElement.DefaultAlgorithmSuite   = SecurityAlgorithmSuite.TripleDesRsa15;

            //Explicit accept secured answers from endpoint
            asymmetricSecurityBindingElement.AllowSerializedSigningTokenOnReply = true;

            //Create binding element for encoding
            var encodingBindingElement = new TextMessageEncodingBindingElement(MessageVersion.Soap11WSAddressing10, Encoding.UTF8);

            //Create binding element for transport
            var httpsTransportBindingElement = new HttpsTransportBindingElement
            {
                RequireClientCertificate = true,
                AuthenticationScheme     = System.Net.AuthenticationSchemes.Anonymous
            };

            var cbinding = new CustomBinding();

            cbinding.Elements.Add(asymmetricSecurityBindingElement);
            cbinding.Elements.Add(encodingBindingElement);
            cbinding.Elements.Add(httpsTransportBindingElement);

            var endPointUri = new Uri(EndPointUrl);

            var address     = new EndpointAddress(new Uri(endPointUri, endpoint));
            var factory     = new ChannelFactory <T>(cbinding, address);
            var certClient  = GetEmbeddedCertificate(ClientCertPath, password);
            var certService = GetEmbeddedCertificate(ServerCertPath);

            //Explicit prevent check on chain of trust
            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
            factory.Credentials.ClientCertificate.Certificate         = certClient;
            factory.Credentials.ServiceCertificate.DefaultCertificate = certService;

            return(factory.CreateChannel());
        }
Exemplo n.º 38
0
        private static SecurityBindingElement CreateSecurityBindingElement()
        {
            SymmetricSecurityBindingElement sbe = SecurityBindingElement.CreateUserNameForSslBindingElement();

            //sbe.IncludeTimestamp = false;
            //sbe.LocalServiceSettings.DetectReplays = false;
            sbe.ProtectionTokenParameters = new X509SecurityTokenParameters();
            // This "Never" is somehow mandatory (though I wonder why ...)
            sbe.ProtectionTokenParameters.InclusionMode = SecurityTokenInclusionMode.Never;
            sbe.MessageSecurityVersion = MessageSecurityVersion.Default;
            //sbe.RequireSignatureConfirmation = true;
            //sbe.KeyEntropyMode = SecurityKeyEntropyMode.ServerEntropy;

            sbe.SetKeyDerivation(false);
            sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
            return(sbe);
        }
Exemplo n.º 39
0
        internal SecurityBindingElement CreateSecurityBindingElement()
        {
            SymmetricSecurityBindingElement element;
            bool flag = false;

            switch (this.clientCredentialType)
            {
            case MessageCredentialType.None:
                element = SecurityBindingElement.CreateAnonymousForCertificateBindingElement();
                break;

            case MessageCredentialType.Windows:
                element = SecurityBindingElement.CreateKerberosBindingElement();
                flag    = true;
                break;

            case MessageCredentialType.UserName:
                element = SecurityBindingElement.CreateUserNameForCertificateBindingElement();
                break;

            case MessageCredentialType.Certificate:
                element = (SymmetricSecurityBindingElement)SecurityBindingElement.CreateMutualCertificateBindingElement();
                break;

            case MessageCredentialType.IssuedToken:
                element = SecurityBindingElement.CreateIssuedTokenForCertificateBindingElement(IssuedSecurityTokenParameters.CreateInfoCardParameters(new SecurityStandardsManager(), this.algorithmSuite));
                break;

            default:
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
            }
            element.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11;
            if (this.wasAlgorithmSuiteSet || !flag)
            {
                element.DefaultAlgorithmSuite = this.AlgorithmSuite;
            }
            else if (flag)
            {
                element.DefaultAlgorithmSuite = SecurityAlgorithmSuite.KerberosDefault;
            }
            element.IncludeTimestamp = false;
            element.LocalServiceSettings.DetectReplays = false;
            element.LocalClientSettings.DetectReplays  = false;
            return(element);
        }
Exemplo n.º 40
0
 internal static bool TryCreate(SecurityBindingElement sbe, out WSDualHttpSecurity security)
 {
     security = null;
     if (sbe == null)
     {
         security = new WSDualHttpSecurity(WSDualHttpSecurityMode.None, null);
     }
     else
     {
         MessageSecurityOverHttp http;
         if (!MessageSecurityOverHttp.TryCreate <MessageSecurityOverHttp>(sbe, false, true, out http))
         {
             return(false);
         }
         security = new WSDualHttpSecurity(WSDualHttpSecurityMode.Message, http);
     }
     return(SecurityElementBase.AreBindingsMatching(security.CreateMessageSecurity(), sbe));
 }
Exemplo n.º 41
0
 public SecureConversationSecurityTokenParameters(SecurityBindingElement bootstrapSecurityBindingElement, bool requireCancellation, bool canRenewSession, ChannelProtectionRequirements bootstrapProtectionRequirements) : base()
 {
     BootstrapSecurityBindingElement = bootstrapSecurityBindingElement;
     CanRenewSession = canRenewSession;
     if (bootstrapProtectionRequirements != null)
     {
         _bootstrapProtectionRequirements = new ChannelProtectionRequirements(bootstrapProtectionRequirements);
     }
     else
     {
         _bootstrapProtectionRequirements = new ChannelProtectionRequirements();
         _bootstrapProtectionRequirements.IncomingEncryptionParts.AddParts(new MessagePartSpecification(true));
         _bootstrapProtectionRequirements.IncomingSignatureParts.AddParts(new MessagePartSpecification(true));
         _bootstrapProtectionRequirements.OutgoingEncryptionParts.AddParts(new MessagePartSpecification(true));
         _bootstrapProtectionRequirements.OutgoingSignatureParts.AddParts(new MessagePartSpecification(true));
     }
     RequireCancellation = requireCancellation;
 }
Exemplo n.º 42
0
        public override BindingElementCollection CreateBindingElements()
        {   // return collection of BindingElements
            BindingElementCollection bindingElements = new BindingElementCollection();
            // order of BindingElements is important
            // add security
            SecurityBindingElement wsSecurity = CreateMessageSecurity();

            if (wsSecurity != null)
            {
                bindingElements.Add(wsSecurity);
            }
            // add encoding (text or mtom)
            bindingElements.Add(encoding);
            // add transport
            bindingElements.Add(GetTransport());

            return(bindingElements.Clone());
        }
 internal static bool TryCreate(SecurityBindingElement sbe, out WSDualHttpSecurity security)
 {
     security = null;
     if (sbe == null)
     {
         security = new WSDualHttpSecurity(WSDualHttpSecurityMode.None, null);
     }
     else
     {
         MessageSecurityOverHttp http;
         if (!MessageSecurityOverHttp.TryCreate<MessageSecurityOverHttp>(sbe, false, true, out http))
         {
             return false;
         }
         security = new WSDualHttpSecurity(WSDualHttpSecurityMode.Message, http);
     }
     return SecurityElementBase.AreBindingsMatching(security.CreateMessageSecurity(), sbe);
 }
Exemplo n.º 44
0
        // Summary:
        //  Searches a security binding element for a single IssuedSecurityTokenParameters.  This method will throw an
        //  argument exception if more than one is found.
        //
        // Parameters:
        //  securityBindingEle   -  The SecurityBindingElement to search.
        //
        // Return Value:
        //  Returns an IssuedSecurityTokenParameters if one is found, otherwise null.
        //
        static IssuedSecurityTokenParameters TryGetNextStsIssuedTokenParameters(SecurityBindingElement securityBindingEle)
        {
            if (securityBindingEle == null)
            {
                return(null);
            }

            //
            // This object can have a value assigned to it exactly once.  After one assignment of a non-null value
            // any other non-null assignment will cause the object to throw an argument excaption.
            //
            ThrowOnMultipleAssignment <IssuedSecurityTokenParameters> issuedTokenParameters =
                new ThrowOnMultipleAssignment <IssuedSecurityTokenParameters>(SR.GetString(SR.TooManyIssuedSecurityTokenParameters));

            FindInfoCardIssuerBinding(securityBindingEle, issuedTokenParameters);

            return(issuedTokenParameters.Value);
        }
Exemplo n.º 45
0
 protected SecureConversationSecurityTokenParameters(SecureConversationSecurityTokenParameters other)
     : base(other)
 {
     this.requireCancellation = other.requireCancellation;
     this.canRenewSession     = other.canRenewSession;
     if (other.bootstrapSecurityBindingElement != null)
     {
         this.bootstrapSecurityBindingElement = (SecurityBindingElement)other.bootstrapSecurityBindingElement.Clone();
     }
     if (other.bootstrapProtectionRequirements != null)
     {
         this.bootstrapProtectionRequirements = new ChannelProtectionRequirements(other.bootstrapProtectionRequirements);
     }
     if (other.issuerBindingContext != null)
     {
         this.issuerBindingContext = other.issuerBindingContext.Clone();
     }
 }
Exemplo n.º 46
0
        private static ChannelFactory <WebApiNetTerrain.INetTerrainWebApi> CreateConnectionFactory(string url, string username, string password)
        {
            var security = SecurityBindingElement.CreateUserNameOverTransportBindingElement();

            security.EnableUnsecuredResponse = true;
            security.AllowInsecureTransport  = true;
            var customBinding = new CustomBinding(security,
                                                  new TextMessageEncodingBindingElement(),
                                                  new HttpTransportBindingElement());
            EndpointAddress endpointAddress = new EndpointAddress(new Uri(url));
            ChannelFactory <WebApiNetTerrain.INetTerrainWebApi> factory =
                new ChannelFactory <WebApiNetTerrain.INetTerrainWebApi>(customBinding,
                                                                        endpointAddress);

            factory.Credentials.UserName.UserName = username;
            factory.Credentials.UserName.Password = password;
            return(factory);
        }
Exemplo n.º 47
0
 //<snippet1>
 // This method returns a custom binding created from a WSHttpBinding. Alter the method 
 // to use the appropriate binding for your service, with the appropriate settings.
 public static Binding CreateCustomBinding(TimeSpan clockSkew)
 {
     WSHttpBinding standardBinding = new WSHttpBinding(SecurityMode.Message, true);
     CustomBinding myCustomBinding = new CustomBinding(standardBinding);
     SymmetricSecurityBindingElement security =
         myCustomBinding.Elements.Find<SymmetricSecurityBindingElement>();
     security.LocalClientSettings.MaxClockSkew = clockSkew;
     security.LocalServiceSettings.MaxClockSkew = clockSkew;
     // Get the System.ServiceModel.Security.Tokens.SecureConversationSecurityTokenParameters 
     SecureConversationSecurityTokenParameters secureTokenParams =
         (SecureConversationSecurityTokenParameters)security.ProtectionTokenParameters;
     // From the collection, get the bootstrap element.
     SecurityBindingElement bootstrap = secureTokenParams.BootstrapSecurityBindingElement;
     // Set the MaxClockSkew on the bootstrap element.
     bootstrap.LocalClientSettings.MaxClockSkew = clockSkew;
     bootstrap.LocalServiceSettings.MaxClockSkew = clockSkew;
     return myCustomBinding;
 }
 internal static bool TryCreate(SecurityBindingElement wsSecurity, SecurityMode mode, bool isReliableSessionEnabled, BindingElement transportSecurity, TcpTransportSecurity tcpTransportSecurity, out NetTcpSecurity security)
 {
     security = null;
     MessageSecurityOverTcp messageSecurity = null;
     if (mode == SecurityMode.Message)
     {
         if (!MessageSecurityOverTcp.TryCreate(wsSecurity, isReliableSessionEnabled, null, out messageSecurity))
         {
             return false;
         }
     }
     else if ((mode == SecurityMode.TransportWithMessageCredential) && !MessageSecurityOverTcp.TryCreate(wsSecurity, isReliableSessionEnabled, transportSecurity, out messageSecurity))
     {
         return false;
     }
     security = new NetTcpSecurity(mode, tcpTransportSecurity, messageSecurity);
     return SecurityElementBase.AreBindingsMatching(security.CreateMessageSecurity(isReliableSessionEnabled), wsSecurity, false);
 }
Exemplo n.º 49
0
        SecurityBindingElement CreateSecurityBindingElement()
        {
            SecurityBindingElement element;

            switch (Security.Mode)
            {
            case BasicHttpSecurityMode.Message:
#if MOBILE || XAMMAC_4_5
                throw new NotImplementedException();
#else
                if (Security.Message.ClientCredentialType != BasicHttpMessageCredentialType.Certificate)
                {
                    throw new InvalidOperationException("When Message security is enabled in a BasicHttpBinding, the message security credential type must be BasicHttpMessageCredentialType.Certificate.");
                }
                element = SecurityBindingElement.CreateMutualCertificateBindingElement(
                    MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10);
                break;
#endif

            case BasicHttpSecurityMode.TransportWithMessageCredential:
#if MOBILE || XAMMAC_4_5
                throw new NotImplementedException();
#else
                if (Security.Message.ClientCredentialType != BasicHttpMessageCredentialType.Certificate)
                {
                    // FIXME: pass proper security token parameters.
                    element = SecurityBindingElement.CreateCertificateOverTransportBindingElement();
                }
                else
                {
                    element = new AsymmetricSecurityBindingElement();
                }
                break;
#endif
            default:
                return(null);
            }

#if !MOBILE && !XAMMAC_4_5
            element.SetKeyDerivation(false);
            element.SecurityHeaderLayout = SecurityHeaderLayout.Lax;
#endif
            return(element);
        }
        internal new static bool TryCreate(SecurityBindingElement sbe, TransportBindingElement transport, PrivacyNoticeBindingElement privacy, ReliableSessionBindingElement rsbe, TransactionFlowBindingElement tfbe, out Binding binding)
        {
            bool isReliableSession = (rsbe != null);

            binding = null;

            // reverse GetTransport
            HttpTransportSecurity        transportSecurity = new HttpTransportSecurity();
            WSFederationHttpSecurityMode mode;

            if (!WSFederationHttpBinding.GetSecurityModeFromTransport(transport, transportSecurity, out mode))
            {
                return(false);
            }

            HttpsTransportBindingElement httpsBinding = transport as HttpsTransportBindingElement;

            if (httpsBinding != null && httpsBinding.MessageSecurityVersion != null)
            {
                if (httpsBinding.MessageSecurityVersion.SecurityPolicyVersion != s_WS2007MessageSecurityVersion.SecurityPolicyVersion)
                {
                    return(false);
                }
            }

            WSFederationHttpSecurity security;

            if (WS2007FederationHttpBinding.TryCreateSecurity(sbe, mode, transportSecurity, isReliableSession, out security))
            {
                binding = new WS2007FederationHttpBinding(security, privacy, isReliableSession);
            }

            if (rsbe != null && rsbe.ReliableMessagingVersion != ReliableMessagingVersion.WSReliableMessaging11)
            {
                return(false);
            }

            if (tfbe != null && tfbe.TransactionProtocol != TransactionProtocol.WSAtomicTransaction11)
            {
                return(false);
            }

            return(binding != null);
        }
 internal static bool TryCreate(SecurityBindingElement sbe, WSFederationHttpSecurityMode mode, HttpTransportSecurity transportSecurity, bool isReliableSessionEnabled, MessageSecurityVersion version, out WSFederationHttpSecurity security)
 {
     security = null;
     FederatedMessageSecurityOverHttp messageSecurity = null;
     if (sbe == null)
     {
         mode = WSFederationHttpSecurityMode.None;
     }
     else
     {
         mode &= WSFederationHttpSecurityMode.TransportWithMessageCredential | WSFederationHttpSecurityMode.Message;
         if (!FederatedMessageSecurityOverHttp.TryCreate(sbe, mode == WSFederationHttpSecurityMode.TransportWithMessageCredential, isReliableSessionEnabled, version, out messageSecurity))
         {
             return false;
         }
     }
     security = new WSFederationHttpSecurity(mode, messageSecurity);
     return true;
 }
 private void ImportEndpointScopeMessageBindingAssertions(MetadataImporter importer, PolicyConversionContext policyContext, SecurityBindingElement binding)
 {
     XmlElement assertion = null;
     WSSecurityPolicy policy;
     this.ImportSupportingTokenAssertions(importer, policyContext, policyContext.GetBindingAssertions(), binding.EndpointSupportingTokenParameters, binding.OptionalEndpointSupportingTokenParameters);
     if (WSSecurityPolicy.TryGetSecurityPolicyDriver(policyContext.GetBindingAssertions(), out policy))
     {
         if (!policy.TryImportWsspWssAssertion(importer, policyContext.GetBindingAssertions(), binding, out assertion) && (assertion != null))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("UnsupportedSecurityPolicyAssertion", new object[] { assertion.OuterXml })));
         }
         if (!policy.TryImportWsspTrustAssertion(importer, policyContext.GetBindingAssertions(), binding, out assertion) && (assertion != null))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("UnsupportedSecurityPolicyAssertion", new object[] { assertion.OuterXml })));
         }
     }
     if (assertion == null)
     {
         binding.DoNotEmitTrust = true;
     }
 }
        internal new static bool TryCreate(SecurityBindingElement sbe, TransportBindingElement transport, PrivacyNoticeBindingElement privacy, ReliableSessionBindingElement rsbe, TransactionFlowBindingElement tfbe, out Binding binding)
        {
            bool isReliableSession = (rsbe != null);
            binding = null;

            // reverse GetTransport
            HttpTransportSecurity transportSecurity = new HttpTransportSecurity();
            WSFederationHttpSecurityMode mode;
            if (!WSFederationHttpBinding.GetSecurityModeFromTransport(transport, transportSecurity, out mode))
            {
                return false;
            }

            HttpsTransportBindingElement httpsBinding = transport as HttpsTransportBindingElement;
            if (httpsBinding != null && httpsBinding.MessageSecurityVersion != null)
            {
                if (httpsBinding.MessageSecurityVersion.SecurityPolicyVersion != WS2007MessageSecurityVersion.SecurityPolicyVersion)
                {
                    return false;
                }
            }

            WSFederationHttpSecurity security;
            if (WS2007FederationHttpBinding.TryCreateSecurity(sbe, mode, transportSecurity, isReliableSession, out security))
            {
                binding = new WS2007FederationHttpBinding(security, privacy, isReliableSession);
            }

            if (rsbe != null && rsbe.ReliableMessagingVersion != ReliableMessagingVersion.WSReliableMessaging11)
            {
                return false;
            }

            if (tfbe != null && tfbe.TransactionProtocol != TransactionProtocol.WSAtomicTransaction11)
            {
                return false;
            }

            return binding != null;
        }
Exemplo n.º 54
0
        // This method reverses the CreateMessageSecurity(bool) method
        internal static bool TryCreate(SecurityBindingElement sbe, out BasicHttpMessageSecurity security, out bool isSecureTransportMode)
        {
            Fx.Assert(null != sbe, string.Empty);

            security = null;
            isSecureTransportMode = false;

            if (!sbe.IsSetKeyDerivation(false))
                return false;
            if (sbe.SecurityHeaderLayout != SecurityHeaderLayout.Lax)
                return false;
            if (sbe.MessageSecurityVersion != MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10)
                return false;

            BasicHttpMessageCredentialType credentialType;
            if (!SecurityBindingElement.IsMutualCertificateBinding(sbe, true))
            {
                isSecureTransportMode = true;
                if (SecurityBindingElement.IsCertificateOverTransportBinding(sbe))
                {
                    credentialType = BasicHttpMessageCredentialType.Certificate;
                }
                else if (SecurityBindingElement.IsUserNameOverTransportBinding(sbe))
                {
                    credentialType = BasicHttpMessageCredentialType.UserName;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                credentialType = BasicHttpMessageCredentialType.Certificate;
            }
            security = new BasicHttpMessageSecurity();
            security.ClientCredentialType = credentialType;

            return true;
        }
 internal static bool TryCreate(SecurityBindingElement sbe, TransportBindingElement transport, ReliableSessionBindingElement rsbe, TransactionFlowBindingElement tfbe, out Binding binding)
 {
     UnifiedSecurityMode mode;
     WSHttpSecurity security2;
     bool isReliableSession = rsbe != null;
     binding = null;
     HttpTransportSecurity defaultHttpTransportSecurity = WSHttpSecurity.GetDefaultHttpTransportSecurity();
     if (!WSHttpBinding.GetSecurityModeFromTransport(transport, defaultHttpTransportSecurity, out mode))
     {
         return false;
     }
     HttpsTransportBindingElement element = transport as HttpsTransportBindingElement;
     if (((element != null) && (element.MessageSecurityVersion != null)) && (element.MessageSecurityVersion.SecurityPolicyVersion != WS2007MessageSecurityVersion.SecurityPolicyVersion))
     {
         return false;
     }
     if (TryCreateSecurity(sbe, mode, defaultHttpTransportSecurity, isReliableSession, out security2))
     {
         bool flag2;
         WS2007HttpBinding binding2 = new WS2007HttpBinding(security2, isReliableSession);
         if (!WSHttpBinding.TryGetAllowCookiesFromTransport(transport, out flag2))
         {
             return false;
         }
         binding2.AllowCookies = flag2;
         binding = binding2;
     }
     if ((rsbe != null) && (rsbe.ReliableMessagingVersion != ReliableMessagingVersion.WSReliableMessaging11))
     {
         return false;
     }
     if ((tfbe != null) && (tfbe.TransactionProtocol != TransactionProtocol.WSAtomicTransaction11))
     {
         return false;
     }
     return (binding != null);
 }
        internal static bool TryCreate(SecurityBindingElement sbe,
                                       WSFederationHttpSecurityMode mode,
                                       HttpTransportSecurity transportSecurity,
                                       bool isReliableSessionEnabled,
                                       MessageSecurityVersion version,
                                       out WSFederationHttpSecurity security)
        {
            security = null;
            FederatedMessageSecurityOverHttp messageSecurity = null;
            if (sbe == null)
            {
                mode = WSFederationHttpSecurityMode.None;
            }
            else
            {
                mode &= WSFederationHttpSecurityMode.Message | WSFederationHttpSecurityMode.TransportWithMessageCredential;
                Fx.Assert(WSFederationHttpSecurityModeHelper.IsDefined(mode), string.Format("Invalid WSFederationHttpSecurityMode value: {0}", mode.ToString()));

                if (!FederatedMessageSecurityOverHttp.TryCreate(sbe, mode == WSFederationHttpSecurityMode.TransportWithMessageCredential, isReliableSessionEnabled, version, out messageSecurity))
                    return false;
            }
            security = new WSFederationHttpSecurity(mode, messageSecurity);
            return true;
        }
        protected bool TryImportWsspTrustAssertion(string trustName, MetadataImporter importer, ICollection<XmlElement> assertions, SecurityBindingElement binding, out XmlElement assertion)
        {
            if (binding == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("binding");
            }
            if (assertions == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("assertions");
            }

            bool result = true;
            Collection<Collection<XmlElement>> alternatives;

            if (TryImportWsspAssertion(assertions, trustName, out assertion)
                && TryGetNestedPolicyAlternatives(importer, assertion, out alternatives))
            {
                foreach (Collection<XmlElement> alternative in alternatives)
                {
                    TryImportWsspAssertion(alternative, MustSupportIssuedTokensName);
                    bool requireClientEntropy = TryImportWsspAssertion(alternative, RequireClientEntropyName);
                    bool requireServerEntropy = TryImportWsspAssertion(alternative, RequireServerEntropyName);
                    if (trustName == Trust13Name)
                    {
                        // We are just reading this optional element.
                        TryImportWsspAssertion(alternative, RequireAppliesTo);
                    }
                    if (alternative.Count == 0)
                    {
                        if (requireClientEntropy)
                        {
                            if (requireServerEntropy)
                            {
                                binding.KeyEntropyMode = SecurityKeyEntropyMode.CombinedEntropy;
                            }
                            else
                            {
                                binding.KeyEntropyMode = SecurityKeyEntropyMode.ClientEntropy;
                            }
                        }
                        else if (requireServerEntropy)
                        {
                            binding.KeyEntropyMode = SecurityKeyEntropyMode.ServerEntropy;
                        }

                        result = true;
                        break;
                    }
                    else
                    {
                        result = false;
                    }
                }
            }

            return result;
        }
 public abstract bool TryImportWsspTrustAssertion(MetadataImporter importer, ICollection<XmlElement> assertions, SecurityBindingElement binding, out XmlElement assertion);
        public virtual bool TryImportWsspWssAssertion(MetadataImporter importer, ICollection<XmlElement> assertions, SecurityBindingElement binding, out XmlElement assertion)
        {
            if (binding == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("binding");
            }
            if (assertions == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("assertions");
            }

            bool result = true;
            Collection<Collection<XmlElement>> alternatives;

            if (TryImportWsspAssertion(assertions, Wss10Name, out assertion))
            {
                if (TryGetNestedPolicyAlternatives(importer, assertion, out alternatives))
                {
                    foreach (Collection<XmlElement> alternative in alternatives)
                    {
                        TryImportWsspAssertion(alternative, MustSupportRefKeyIdentifierName);
                        TryImportWsspAssertion(alternative, MustSupportRefIssuerSerialName);
                        if (alternative.Count == 0)
                        {
                            binding.MessageSecurityVersion = this.GetSupportedMessageSecurityVersion(SecurityVersion.WSSecurity10);
                            result = true;
                            break;
                        }
                        else
                        {
                            result = false;
                        }
                    }
                }
            }
            else if (TryImportWsspAssertion(assertions, Wss11Name, out assertion))
            {
                if (TryGetNestedPolicyAlternatives(importer, assertion, out alternatives))
                {
                    foreach (Collection<XmlElement> alternative in alternatives)
                    {
                        TryImportWsspAssertion(alternative, MustSupportRefKeyIdentifierName);
                        TryImportWsspAssertion(alternative, MustSupportRefIssuerSerialName);
                        TryImportWsspAssertion(alternative, MustSupportRefThumbprintName);
                        TryImportWsspAssertion(alternative, MustSupportRefEncryptedKeyName);
                        bool requireSignatureConfirmation = TryImportWsspAssertion(alternative, RequireSignatureConfirmationName);
                        if (alternative.Count == 0)
                        {
                            binding.MessageSecurityVersion = this.GetSupportedMessageSecurityVersion(SecurityVersion.WSSecurity11);
                            if (binding is SymmetricSecurityBindingElement)
                            {
                                ((SymmetricSecurityBindingElement)binding).RequireSignatureConfirmation = requireSignatureConfirmation;
                            }
                            else if (binding is AsymmetricSecurityBindingElement)
                            {
                                ((AsymmetricSecurityBindingElement)binding).RequireSignatureConfirmation = requireSignatureConfirmation;
                            }
                            result = true;
                            break;
                        }
                        else
                        {
                            result = false;
                        }
                    }
                }
            }

            return result;
        }
        public virtual XmlElement CreateWsspWssAssertion(MetadataExporter exporter, SecurityBindingElement binding)
        {
            if (binding == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("binding");
            }

            if (binding.MessageSecurityVersion.SecurityVersion == SecurityVersion.WSSecurity10)
            {
                return CreateWsspWss10Assertion(exporter);
            }
            else if (binding.MessageSecurityVersion.SecurityVersion == SecurityVersion.WSSecurity11)
            {
                if (binding is SymmetricSecurityBindingElement)
                {
                    return CreateWsspWss11Assertion(exporter, ((SymmetricSecurityBindingElement)binding).RequireSignatureConfirmation);
                }
                else if (binding is AsymmetricSecurityBindingElement)
                {
                    return CreateWsspWss11Assertion(exporter, ((AsymmetricSecurityBindingElement)binding).RequireSignatureConfirmation);
                }
                else
                {
                    return CreateWsspWss11Assertion(exporter, false);
                }
            }
            else
            {
                return null;
            }
        }