public void DefaultValues ()
		{
			SymmetricSecurityBindingElement be =
				new SymmetricSecurityBindingElement ();

			SecurityAssert.AssertSymmetricSecurityBindingElement (
				SecurityAlgorithmSuite.Default,
				true, // IncludeTimestamp
				SecurityKeyEntropyMode.CombinedEntropy,
				MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature,
				MessageSecurityVersion.Default,
				false, // RequireSignatureConfirmation
				SecurityHeaderLayout.Strict,
				// EndpointSupportingTokenParameters: endorsing, signed, signedEncrypted, signedEndorsing (by count)
				0, 0, 0, 0,
				// ProtectionTokenParameters
				false,
				default (SecurityTokenInclusionMode),
				default (SecurityTokenReferenceStyle),
				default (bool),
				// LocalClientSettings
				true, 60, true,

				be, "");
		}
        public UserNameCertificateBinding()
        {
            //add  security
               // var securityElement =
            //   SecurityBindingElement.CreateUserNameForCertificateBindingElement();

            var securityElement = new SymmetricSecurityBindingElement();

            var x509TokenParameters = new X509SecurityTokenParameters();
            // how to find certificate
            // this will be used by securitymanager to find the certificate when create x509security tokens
            //x509TokenParameters.X509ReferenceStyle = X509KeyIdentifierClauseType.Thumbprint;

            //The token is never included in messages but is referenced. The token must be known to the recipient out of band
            x509TokenParameters.InclusionMode = SecurityTokenInclusionMode.Never;
            securityElement.ProtectionTokenParameters = x509TokenParameters;

            securityElement.EndpointSupportingTokenParameters.
                SignedEncrypted.Add(new UserNameSecurityTokenParameters());

            securityElement.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11;

            securityElement.RequireSignatureConfirmation = true;

            Elements.Add(securityElement);

            // Message Encoding
            var textEncoding = new GZipMessageEncodingBindingElement();
            textEncoding.MessageVersion = MessageVersion.Soap12WSAddressing10;
            Elements.Add(textEncoding);

            // Transport
            Elements.Add(new HttpTransportBindingElement());
        }
Exemplo n.º 3
0
	public static void Main ()
	{
		SymmetricSecurityBindingElement sbe =
			new SymmetricSecurityBindingElement ();
		sbe.ProtectionTokenParameters =
			new SslSecurityTokenParameters ();
		ServiceHost host = new ServiceHost (typeof (Foo));
		HttpTransportBindingElement hbe =
			new HttpTransportBindingElement ();
		CustomBinding binding = new CustomBinding (sbe, hbe);
		binding.ReceiveTimeout = TimeSpan.FromSeconds (5);
		host.AddServiceEndpoint ("IFoo",
			binding, new Uri ("http://localhost:8080"));
		ServiceCredentials cred = new ServiceCredentials ();
		cred.SecureConversationAuthentication.SecurityStateEncoder =
			new MyEncoder ();
		cred.ServiceCertificate.Certificate =
			new X509Certificate2 ("test.pfx", "mono");
		cred.ClientCertificate.Authentication.CertificateValidationMode =
			X509CertificateValidationMode.None;
		host.Description.Behaviors.Add (cred);
		host.Description.Behaviors.Find<ServiceDebugBehavior> ()
			.IncludeExceptionDetailInFaults = true;
//		foreach (ServiceEndpoint se in host.Description.Endpoints)
//			se.Behaviors.Add (new StdErrInspectionBehavior ());
		ServiceMetadataBehavior smb = new ServiceMetadataBehavior ();
		smb.HttpGetEnabled = true;
		smb.HttpGetUrl = new Uri ("http://localhost:8080/wsdl");
		host.Description.Behaviors.Add (smb);
		host.Open ();
		Console.WriteLine ("Hit [CR] key to close ...");
		Console.ReadLine ();
		host.Close ();
	}
Exemplo n.º 4
0
        public static Binding CreateCreditCardBinding()
        {
            HttpTransportBindingElement httpTransport = new HttpTransportBindingElement();

            // the message security binding element will be configured to require a credit card
            // token that is encrypted with the service's certificate 
            SymmetricSecurityBindingElement messageSecurity = new SymmetricSecurityBindingElement();
            messageSecurity.EndpointSupportingTokenParameters.SignedEncrypted.Add(new CreditCardTokenParameters());
            X509SecurityTokenParameters x509ProtectionParameters = new X509SecurityTokenParameters();
            x509ProtectionParameters.InclusionMode = SecurityTokenInclusionMode.Never;
            messageSecurity.ProtectionTokenParameters = x509ProtectionParameters;
            return new CustomBinding(messageSecurity, httpTransport);
        }
Exemplo n.º 5
0
        public void NonEndorsibleParameterInEndorsingSupport()
        {
            SymmetricSecurityBindingElement be =
                new SymmetricSecurityBindingElement();

            be.ProtectionTokenParameters =
                new X509SecurityTokenParameters();
            be.EndpointSupportingTokenParameters.Endorsing.Add(
                new UserNameSecurityTokenParameters());
            Binding          b      = new CustomBinding(be, new HttpTransportBindingElement());
            X509Certificate2 cert   = new X509Certificate2(TestResourceHelper.GetFullPathOfResource("Test/Resources/test.pfx"), "mono");
            EndpointAddress  ea     = new EndpointAddress(new Uri("http://localhost:" + NetworkHelpers.FindFreePort()), new X509CertificateEndpointIdentity(cert));
            CalcProxy        client = new CalcProxy(b, ea);

            client.ClientCredentials.UserName.UserName = "******";
            client.Sum(1, 2);
        }
Exemplo n.º 6
0
        private void ShowUse()
        {
            //<snippet17>
            // Create an instance of the binding to use.
            WSHttpBinding b = new WSHttpBinding();

            // Get the binding element collection.
            BindingElementCollection bec = b.CreateBindingElements();

            // Find the SymmetricSecurityBindingElement in the colllection.
            // Important: Cast to the SymmetricSecurityBindingElement when using the Find
            // method.
            SymmetricSecurityBindingElement sbe = (SymmetricSecurityBindingElement)
                                                  bec.Find <SecurityBindingElement>();

            // Get the LocalServiceSettings from the binding element.
            LocalServiceSecuritySettings lss = sbe.LocalServiceSettings;

            // Print out values.
            Console.WriteLine("DetectReplays: {0} days", lss.DetectReplays);
            Console.WriteLine("ReplayWindow: {0} minutes", lss.ReplayWindow.Minutes);
            Console.WriteLine("MaxClockSkew: {0} minutes", lss.MaxClockSkew.Minutes);

            Console.ReadLine();
            Console.WriteLine("Press Enter to Continue");
            // Change the MaxClockSkew to 3 minutes.
            lss.MaxClockSkew = new TimeSpan(0, 0, 3, 0);

            // Print the new value.
            Console.WriteLine("New MaxClockSkew: {0} minutes", lss.MaxClockSkew.Minutes);
            Console.WriteLine("Press Enter to End");
            Console.ReadLine();

            // Create a URI for the service.
            Uri httpUri = new Uri("http://localhost/calculator");

            // Create a ServiceHost. The binding has the changed MaxClockSkew.
            ServiceHost sh = new ServiceHost(typeof(Calculator), httpUri);

            sh.AddServiceEndpoint(typeof(ICalculator), b, "");
            // sh.Open();
            // Console.WriteLine("Listening");
            // Console.ReadLine();
            // sh.Close();
            //</snippet17>
        }
Exemplo n.º 7
0
        public void OtherParameterInEndorsingSupport()
        {
            SymmetricSecurityBindingElement be =
                new SymmetricSecurityBindingElement();

            be.ProtectionTokenParameters =
                new X509SecurityTokenParameters();
            be.EndpointSupportingTokenParameters.Endorsing.Add(
                new MyEndorsingTokenParameters());
            Binding         b      = new CustomBinding(be, new HttpTransportBindingElement());
            EndpointAddress ea     = new EndpointAddress(new Uri("http://localhost:" + NetworkHelpers.FindFreePort()), new X509CertificateEndpointIdentity(cert));
            CalcProxy       client = new CalcProxy(b, ea);

            client.Endpoint.Behaviors.RemoveAll <ClientCredentials> ();
            client.Endpoint.Behaviors.Add(new MyClientCredentials());
            client.Sum(1, 2);
        }
        public Binding CreateHttpsBinding()
        {
            var httpTransport = new HttpsTransportBindingElement
            {
                MaxReceivedMessageSize = 10000000
            };

            var messageSecurity = new SymmetricSecurityBindingElement();

            var x509ProtectionParameters = new X509SecurityTokenParameters
            {
                InclusionMode = SecurityTokenInclusionMode.Never
            };

            messageSecurity.ProtectionTokenParameters = x509ProtectionParameters;
            return(new CustomBinding(messageSecurity, httpTransport));
        }
Exemplo n.º 9
0
        public CustomBinding CreateCustomTokenBinding()
        {
            HttpTransportBindingElement httpTransport = new HttpTransportBindingElement();

            // the message security binding element will be configured to require a credit card
            // token that is encrypted with the service's certificate
            SymmetricSecurityBindingElement messageSecurity = new SymmetricSecurityBindingElement();

            messageSecurity.EndpointSupportingTokenParameters.SignedEncrypted.Add(new CustomTokenParameters());

            X509SecurityTokenParameters x509ProtectionParameters = new X509SecurityTokenParameters();

            x509ProtectionParameters.InclusionMode    = SecurityTokenInclusionMode.Never;
            messageSecurity.ProtectionTokenParameters = x509ProtectionParameters;

            return(new CustomBinding(messageSecurity, httpTransport));
        }
Exemplo n.º 10
0
        public void MessageSecuritySPNego()
        {
            WSHttpBinding binding = new WSHttpBinding();
            SymmetricSecurityBindingElement sbe =
                binding.CreateBindingElements().Find <SymmetricSecurityBindingElement> ();

            Assert.IsNotNull(sbe, "#1");
            Assert.AreEqual(false, sbe.RequireSignatureConfirmation, "#1-2");

            SecureConversationSecurityTokenParameters sp =
                sbe.ProtectionTokenParameters
                as SecureConversationSecurityTokenParameters;

            Assert.IsNotNull(sp, "#2");
            SymmetricSecurityBindingElement spbe =
                sp.BootstrapSecurityBindingElement
                as SymmetricSecurityBindingElement;

            Assert.IsNotNull(spbe, "#3");
            SspiSecurityTokenParameters p =
                spbe.ProtectionTokenParameters
                as SspiSecurityTokenParameters;

            Assert.IsNotNull(p, "#4");
            Assert.AreEqual(SecurityTokenReferenceStyle.Internal,
                            p.ReferenceStyle, "#5");
            Assert.AreEqual(SecurityTokenInclusionMode.AlwaysToRecipient,
                            p.InclusionMode, "#6");
            Assert.AreEqual(0, sbe.EndpointSupportingTokenParameters.Signed.Count, "#7");
            Assert.AreEqual(0, sbe.EndpointSupportingTokenParameters.SignedEncrypted.Count, "#8");
            Assert.AreEqual(0, sbe.EndpointSupportingTokenParameters.Endorsing.Count, "#9");
            Assert.AreEqual(0, sbe.EndpointSupportingTokenParameters.SignedEndorsing.Count, "#10");
            Assert.AreEqual(0, spbe.EndpointSupportingTokenParameters.Signed.Count, "#11");
            Assert.AreEqual(0, spbe.EndpointSupportingTokenParameters.SignedEncrypted.Count, "#12");
            Assert.AreEqual(0, spbe.EndpointSupportingTokenParameters.Endorsing.Count, "#13");
            Assert.AreEqual(0, spbe.EndpointSupportingTokenParameters.SignedEndorsing.Count, "#14");

            Assert.AreEqual(0, sbe.OptionalEndpointSupportingTokenParameters.Signed.Count, "#17");
            Assert.AreEqual(0, sbe.OptionalEndpointSupportingTokenParameters.SignedEncrypted.Count, "#18");
            Assert.AreEqual(0, sbe.OptionalEndpointSupportingTokenParameters.Endorsing.Count, "#19");
            Assert.AreEqual(0, sbe.OptionalEndpointSupportingTokenParameters.SignedEndorsing.Count, "#110");
            Assert.AreEqual(0, spbe.OptionalEndpointSupportingTokenParameters.Signed.Count, "#21");
            Assert.AreEqual(0, spbe.OptionalEndpointSupportingTokenParameters.SignedEncrypted.Count, "#22");
            Assert.AreEqual(0, spbe.OptionalEndpointSupportingTokenParameters.Endorsing.Count, "#23");
            Assert.AreEqual(0, spbe.OptionalEndpointSupportingTokenParameters.SignedEndorsing.Count, "#24");
        }
        // not sure how "good" this test is ... if it fails at
        // service side, it just results in timeout error.
        // The assertion makes sure that it passes all the tests, but
        // in case it failed, there is almost no hint ...
        public void GetOrCreateSecureMessage()
        {
            bool        passed = false;
            ServiceHost host   = new ServiceHost(typeof(CalcService));
            InterceptorRequestContextHandler handler = delegate(MessageBuffer src)
            {
                Message msg = src.CreateMessage();
                GetOrCreateSecureMessageAtService(msg);
                passed = true;
            };

            try
            {
                SymmetricSecurityBindingElement clisbe =
                    new SymmetricSecurityBindingElement();
                clisbe.ProtectionTokenParameters =
                    new X509SecurityTokenParameters(X509KeyIdentifierClauseType.Thumbprint, SecurityTokenInclusionMode.Never);
                BindingElement transport  = new HttpTransportBindingElement();
                BindingElement sintercept = new InterceptorBindingElement(handler);
                CustomBinding  b_res      = new CustomBinding(clisbe,
                                                              sintercept,
                                                              transport);
                b_res.ReceiveTimeout = b_res.SendTimeout = TimeSpan.FromSeconds(5);
                host.AddServiceEndpoint(typeof(ICalc), b_res, "http://localhost:37564");

                ServiceCredentials cred = new ServiceCredentials();
                cred.ServiceCertificate.Certificate = cert;
                cred.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
                host.Description.Behaviors.Add(cred);

                host.Open();

                ProcessClient();
            }
            finally
            {
                if (host.State == CommunicationState.Opened)
                {
                    host.Close();
                }
            }
            if (!passed)
            {
                Assert.Fail("Didn't pass the interceptor.");
            }
        }
Exemplo n.º 12
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);
        }
        public void SetKeyDerivation()
        {
            SymmetricSecurityBindingElement be;
            X509SecurityTokenParameters     p;

            be = new SymmetricSecurityBindingElement();
            p  = new X509SecurityTokenParameters();
            be.ProtectionTokenParameters = p;
            be.SetKeyDerivation(false);
            Assert.AreEqual(false, p.RequireDerivedKeys, "#1");

            be = new SymmetricSecurityBindingElement();
            p  = new X509SecurityTokenParameters();
            be.SetKeyDerivation(false);              // set in prior - makes no sense
            be.ProtectionTokenParameters = p;
            Assert.AreEqual(true, p.RequireDerivedKeys, "#2");
        }
Exemplo n.º 14
0
    public static void Main()
    {
        SymmetricSecurityBindingElement sbe =
            new SymmetricSecurityBindingElement();

        //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.SetKeyDerivation(false);
        sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
        ServiceHost host = new ServiceHost(typeof(Foo));
        HttpTransportBindingElement hbe =
            new HttpTransportBindingElement();
        CustomBinding binding = new CustomBinding(sbe, hbe);

        binding.ReceiveTimeout = TimeSpan.FromSeconds(5);
        host.AddServiceEndpoint("IFoo",
                                binding, new Uri("http://localhost:8080"));
        ServiceCredentials cred = new ServiceCredentials();

        cred.ServiceCertificate.Certificate =
            new X509Certificate2("test.pfx", "mono");
        cred.ClientCertificate.Authentication.CertificateValidationMode =
            X509CertificateValidationMode.None;
        host.Description.Behaviors.Add(cred);
        host.Description.Behaviors.Find <ServiceDebugBehavior> ()
        .IncludeExceptionDetailInFaults = true;
        foreach (ServiceEndpoint se in host.Description.Endpoints)
        {
            se.Behaviors.Add(new StdErrInspectionBehavior());
        }
        ServiceMetadataBehavior smb = new ServiceMetadataBehavior();

        smb.HttpGetEnabled = true;
        smb.HttpGetUrl     = new Uri("http://localhost:8080/wsdl");
        host.Description.Behaviors.Add(smb);
        host.Open();
        Console.WriteLine("Hit [CR] key to close ...");
        Console.ReadLine();
        host.Close();
    }
Exemplo n.º 15
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;
 }
 void IServiceBehavior.ApplyDispatchBehavior(System.ServiceModel.Description.ServiceDescription service, ServiceHostBase serviceHostBase)
 {
     foreach (ServiceEndpoint endpoint in service.Endpoints)
     {
         foreach (BindingElement element in endpoint.Binding.CreateBindingElements())
         {
             SymmetricSecurityBindingElement element2 = element as SymmetricSecurityBindingElement;
             if (element2 != null)
             {
                 this.CheckForCookie(element2.ProtectionTokenParameters, endpoint);
                 foreach (SecurityTokenParameters parameters in element2.EndpointSupportingTokenParameters.Endorsing)
                 {
                     this.CheckForCookie(parameters, endpoint);
                 }
                 break;
             }
         }
     }
 }
        public Binding CreateBinding()
        {
            var httpTransport = new HttpTransportBindingElement
            {
                MaxReceivedMessageSize = 10000000
            };

            var messageSecurity = new SymmetricSecurityBindingElement();

            messageSecurity.EndpointSupportingTokenParameters.SignedEncrypted.Add(new ConnectTokenParameters());

            var x509ProtectionParameters = new X509SecurityTokenParameters
            {
                InclusionMode = SecurityTokenInclusionMode.Never
            };

            messageSecurity.ProtectionTokenParameters = x509ProtectionParameters;
            return(new CustomBinding(messageSecurity, httpTransport));
        }
Exemplo n.º 18
0
    static void Run()
    {
        SymmetricSecurityBindingElement sbe =
            new SymmetricSecurityBindingElement();

        sbe.ProtectionTokenParameters =
            new SspiSecurityTokenParameters();
        HttpTransportBindingElement hbe =
            new HttpTransportBindingElement();
        CustomBinding    binding = new CustomBinding(sbe, hbe);
        X509Certificate2 cert    = new X509Certificate2("test.cer");
        FooProxy         proxy   = new FooProxy(binding,
                                                //new EndpointAddress (new Uri ("http://localhost:8080")));
                                                new EndpointAddress(new Uri("http://localhost:8080"), new UpnEndpointIdentity("PC\\atsushi")));

        //new EndpointAddress (new Uri ("http://localhost:8080"), new SpnEndpointIdentity ("PC/atsushi")));
        proxy.Open();
        Console.WriteLine(proxy.Echo("TEST FOR ECHO"));
    }
Exemplo n.º 19
0
        //Create a custom binding using a WsHttpBinding
        public static Binding CreateCustomSecurityBinding()
        {
            WSHttpBinding binding = new WSHttpBinding(SecurityMode.Message);

            //Clients are anonymous to the service
            binding.Security.Message.ClientCredentialType = MessageCredentialType.None;
            //Secure conversation is turned off for simplification. If secure conversation is turned on then
            //you also need to set the IdentityVerifier on the secureconversation bootstrap binding.
            binding.Security.Message.EstablishSecurityContext = false;

            //Get the SecurityBindingElement and cast to a SymmetricSecurityBindingElement to set the IdentityVerifier
            BindingElementCollection        outputBec = binding.CreateBindingElements();
            SymmetricSecurityBindingElement ssbe      = (SymmetricSecurityBindingElement)outputBec.Find <SecurityBindingElement>();

            //Set the Custom IdentityVerifier
            ssbe.LocalClientSettings.IdentityVerifier = new CustomIdentityVerifier();

            return(new CustomBinding(outputBec));
        }
Exemplo n.º 20
0
    public static void Main(string [] args)
    {
        SymmetricSecurityBindingElement sbe =
            new SymmetricSecurityBindingElement();
        IssuedSecurityTokenParameters ip =
            new IssuedSecurityTokenParameters();

        sbe.ProtectionTokenParameters = ip;
        ip.ClaimTypeRequirements.Add(new ClaimTypeRequirement(
                                         ClaimTypes.Email));
        if (args.Length > 0)
        {
            ip.IssuerAddress = new EndpointAddress(new Uri(args [0]),
                                                   new X509CertificateEndpointIdentity(new X509Certificate2(args [1])));
        }
        ServiceHost host = new ServiceHost(typeof(Foo));
        HttpTransportBindingElement hbe =
            new HttpTransportBindingElement();
        CustomBinding binding = new CustomBinding(sbe, hbe);

        binding.ReceiveTimeout = TimeSpan.FromSeconds(5);
        host.AddServiceEndpoint("IFoo",
                                binding, new Uri("http://localhost:8080"));
        ServiceCredentials cred = new ServiceCredentials();

        cred.ServiceCertificate.Certificate =
            new X509Certificate2("test.pfx", "mono");
        cred.ClientCertificate.Authentication.CertificateValidationMode =
            X509CertificateValidationMode.None;
        cred.IssuedTokenAuthentication.AllowUntrustedRsaIssuers = true;
        host.Description.Behaviors.Add(cred);
        host.Description.Behaviors.Find <ServiceDebugBehavior> ()
        .IncludeExceptionDetailInFaults = true;
        ServiceMetadataBehavior smb = new ServiceMetadataBehavior();

        smb.HttpGetEnabled = true;
        smb.HttpGetUrl     = new Uri("http://localhost:8080/wsdl");
        host.Description.Behaviors.Add(smb);
        host.Open();
        Console.WriteLine("Hit [CR] key to close ...");
        Console.ReadLine();
        host.Close();
    }
Exemplo n.º 21
0
	public static void Main ()
	{
		SymmetricSecurityBindingElement sbe =
			new SymmetricSecurityBindingElement ();
		sbe.SecurityHeaderLayout = SecurityHeaderLayout.Lax;
		sbe.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11;
		sbe.RequireSignatureConfirmation = true;

		sbe.LocalServiceSettings.DetectReplays = false;
		sbe.IncludeTimestamp = false;

		sbe.ProtectionTokenParameters =
			new X509SecurityTokenParameters (X509KeyIdentifierClauseType.Thumbprint, SecurityTokenInclusionMode.Never);
		X509SecurityTokenParameters p =
			new X509SecurityTokenParameters (X509KeyIdentifierClauseType.IssuerSerial, SecurityTokenInclusionMode.AlwaysToRecipient);
		p.RequireDerivedKeys = false;
		//sbe.EndpointSupportingTokenParameters.Endorsing.Add (p);
		sbe.SetKeyDerivation (false);
		sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
		ServiceHost host = new ServiceHost (typeof (Foo));
		HttpTransportBindingElement hbe =
			new HttpTransportBindingElement ();
		CustomBinding binding = new CustomBinding (sbe, hbe);
		binding.ReceiveTimeout = TimeSpan.FromSeconds (5);
		host.AddServiceEndpoint ("IFoo",
			binding, new Uri ("http://localhost:8080"));
		ServiceCredentials cred = new ServiceCredentials ();
		cred.ServiceCertificate.Certificate =
			new X509Certificate2 ("test.pfx", "mono");
		host.Description.Behaviors.Add (cred);
		host.Description.Behaviors.Find<ServiceDebugBehavior> ()
			.IncludeExceptionDetailInFaults = true;
		foreach (ServiceEndpoint se in host.Description.Endpoints)
			se.Behaviors.Add (new StdErrInspectionBehavior ());
		ServiceMetadataBehavior smb = new ServiceMetadataBehavior ();
		smb.HttpGetEnabled = true;
		smb.HttpGetUrl = new Uri ("http://localhost:8080/wsdl");
		host.Description.Behaviors.Add (smb);
		host.Open ();
		Console.WriteLine ("Hit [CR] key to close ...");
		Console.ReadLine ();
		host.Close ();
	}
Exemplo n.º 22
0
	public static void Main ()
	{
		SymmetricSecurityBindingElement sbe =
			new SymmetricSecurityBindingElement ();
		//sbe.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
		//sbe.RequireSignatureConfirmation = true;

		sbe.ProtectionTokenParameters =
			new X509SecurityTokenParameters (X509KeyIdentifierClauseType.Thumbprint, SecurityTokenInclusionMode.Never);
		UserNameSecurityTokenParameters p =
			new UserNameSecurityTokenParameters ();
		p.RequireDerivedKeys = false;
		sbe.EndpointSupportingTokenParameters.SignedEncrypted.Add (p);
		//sbe.EndpointSupportingTokenParameters.Signed.Add (p);
		ServiceHost host = new ServiceHost (typeof (Foo));
		HttpTransportBindingElement hbe =
			new HttpTransportBindingElement ();
		CustomBinding binding = new CustomBinding (sbe, hbe);
		binding.ReceiveTimeout = TimeSpan.FromSeconds (5);
		host.AddServiceEndpoint ("IFoo",
			binding, new Uri ("http://localhost:8080"));
		ServiceCredentials cred = new ServiceCredentials ();
		cred.ServiceCertificate.Certificate =
			new X509Certificate2 ("test.pfx", "mono");
		cred.UserNameAuthentication.UserNamePasswordValidationMode =
			UserNamePasswordValidationMode.Custom;
		cred.UserNameAuthentication.CustomUserNamePasswordValidator =
			new GodUserNamePasswordValidator ();
		host.Description.Behaviors.Add (cred);
		host.Description.Behaviors.Find<ServiceDebugBehavior> ()
			.IncludeExceptionDetailInFaults = true;
		foreach (ServiceEndpoint se in host.Description.Endpoints)
			se.Behaviors.Add (new StdErrInspectionBehavior ());
		ServiceMetadataBehavior smb = new ServiceMetadataBehavior ();
		smb.HttpGetEnabled = true;
		smb.HttpGetUrl = new Uri ("http://localhost:8080/wsdl");
		host.Description.Behaviors.Add (smb);
		host.Open ();
		Console.WriteLine ("Hit [CR] key to close ...");
		Console.ReadLine ();
		host.Close ();
	}
Exemplo n.º 23
0
	public static void Main ()
	{
Console.WriteLine ("WARNING!! This test is not configured enought to work fine on .NET either.");

		SymmetricSecurityBindingElement sbe =
			new SymmetricSecurityBindingElement ();
		sbe.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
		sbe.RequireSignatureConfirmation = true;
		//sbe.IncludeTimestamp = false;

		sbe.ProtectionTokenParameters =
			new X509SecurityTokenParameters (X509KeyIdentifierClauseType.Thumbprint, SecurityTokenInclusionMode.Never);
		X509SecurityTokenParameters p =
			new X509SecurityTokenParameters (X509KeyIdentifierClauseType.Thumbprint, SecurityTokenInclusionMode.AlwaysToRecipient);
		p.RequireDerivedKeys = false;
		sbe.EndpointSupportingTokenParameters.Endorsing.Add (p);
		//sbe.SetKeyDerivation (false);
		//sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
		ServiceHost host = new ServiceHost (typeof (Foo));
		var mbe = new BinaryMessageEncodingBindingElement ();
		var tbe = new TcpTransportBindingElement ();
		CustomBinding binding = new CustomBinding (sbe, mbe, tbe);
		binding.ReceiveTimeout = TimeSpan.FromSeconds (5);
		host.AddServiceEndpoint ("IFoo",
			binding, new Uri ("http://localhost:8080"));
		ServiceCredentials cred = new ServiceCredentials ();
		cred.ServiceCertificate.Certificate =
			new X509Certificate2 ("test.pfx", "mono");
		cred.ClientCertificate.Authentication.CertificateValidationMode =
			X509CertificateValidationMode.None;
		host.Description.Behaviors.Add (cred);
		host.Description.Behaviors.Find<ServiceDebugBehavior> ()
			.IncludeExceptionDetailInFaults = true;
		ServiceMetadataBehavior smb = new ServiceMetadataBehavior ();
		smb.HttpGetEnabled = true;
		smb.HttpGetUrl = new Uri ("http://localhost:8080/wsdl");
		host.Description.Behaviors.Add (smb);
		host.Open ();
		Console.WriteLine ("Hit [CR] key to close ...");
		Console.ReadLine ();
		host.Close ();
	}
Exemplo n.º 24
0
        private Guid CreateService(string url, string username, string password)
        {
            Guid sessionId;
            SymmetricSecurityBindingElement sbe = SecurityBindingElement.CreateUserNameForCertificateBindingElement();

            //sbe.IncludeTimestamp = false;
            //sbe.LocalClientSettings.DetectReplays = false;

            sbe.ProtectionTokenParameters = new X509SecurityTokenParameters();
            sbe.ProtectionTokenParameters.InclusionMode = SecurityTokenInclusionMode.Never;
            sbe.SetKeyDerivation(false);
            sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
            HttpTransportBindingElement hbe = new HttpTransportBindingElement();

            CustomBinding binding = new CustomBinding(sbe, hbe);

            X509Certificate2 cert = new X509Certificate2("powershell.pfx", "mono");

            if (url.IndexOf("://") == -1)
            {
                //Default to http connection
                url = "http://" + url;
            }
            UriBuilder builder = new UriBuilder(url);

            if (builder.Port == 80 || builder.Port == 443)
            {
                builder.Port = 5985;
            }
            WSManHttpServiceProxy proxy = new WSManHttpServiceProxy(binding,
                                                                    new EndpointAddress(builder.Uri, new X509CertificateEndpointIdentity(cert)));

            proxy.ClientCredentials.UserName.UserName = username;
            proxy.ClientCredentials.UserName.Password = password;
            proxy.Open();
            sessionId       = proxy.CreateSession();
            proxy.SessionId = sessionId;

            _services.Add(sessionId, proxy);
            return(sessionId);
        }
Exemplo n.º 25
0
        private void LocalClient()
        {
            //<snippet15>
            // Create an instance of the binding to use.
            WSHttpBinding b = new WSHttpBinding();

            // Get the binding element collection.
            BindingElementCollection bec = b.CreateBindingElements();

            // Find the SymmetricSecurityBindingElement in the collection.
            // Important: Cast to the SymmetricSecurityBindingElement when using the Find
            // method.
            SymmetricSecurityBindingElement sbe = (SymmetricSecurityBindingElement)
                                                  bec.Find <SecurityBindingElement>();

            // Get the LocalSecuritySettings from the binding element.
            LocalClientSecuritySettings lc = sbe.LocalClientSettings;

            // Print out values.
            Console.WriteLine("Maximum cookie caching time: {0} days", lc.MaxCookieCachingTime.Days);
            Console.WriteLine("Replay Cache Size: {0}", lc.ReplayCacheSize);
            Console.WriteLine("ReplayWindow: {0} minutes", lc.ReplayWindow.Minutes);
            Console.WriteLine("MaxClockSkew: {0} minutes", lc.MaxClockSkew.Minutes);
            Console.ReadLine();

            // Change the MaxClockSkew to 3 minutes.
            lc.MaxClockSkew = new TimeSpan(0, 0, 3, 0);

            // Print the new value.
            Console.WriteLine("New MaxClockSkew: {0} minutes", lc.MaxClockSkew.Minutes);
            Console.ReadLine();

            // Create an EndpointAddress for the service.
            EndpointAddress ea = new EndpointAddress("http://localhost/calculator");

            // Create a client. The binding has the changed MaxClockSkew.
            // CalculatorClient cc = new CalculatorClient(b, ea);
            // Use the new client. (Not shown.)
            // cc.Close();
            //</snippet15>
        }
Exemplo n.º 26
0
    static void Run()
    {
        SymmetricSecurityBindingElement sbe =
            new SymmetricSecurityBindingElement();

        sbe.ProtectionTokenParameters =
            new SslSecurityTokenParameters();
        HttpTransportBindingElement hbe =
            new HttpTransportBindingElement();
        CustomBinding    binding = new CustomBinding(sbe, hbe);
        X509Certificate2 cert    = new X509Certificate2("test.cer");
        FooProxy         proxy   = new FooProxy(binding,
                                                new EndpointAddress(new Uri("http://localhost:8080"), new X509CertificateEndpointIdentity(cert)));

        proxy.ClientCredentials.ServiceCertificate.Authentication
        .CertificateValidationMode =
            X509CertificateValidationMode.None;
//		proxy.Endpoint.Behaviors.Add (new StdErrInspectionBehavior ());
        proxy.Open();
        Console.WriteLine(proxy.Echo("TEST FOR ECHO"));
    }
        CustomBinding CreateBinding(RequestSender sender,
                                    SecurityTokenParameters protectionTokenParameters,
                                    bool isOneWay)
        {
            SymmetricSecurityBindingElement sbe =
                new SymmetricSecurityBindingElement();

            sbe.ProtectionTokenParameters = protectionTokenParameters;
            List <BindingElement> l = new List <BindingElement> ();

            l.Add(sbe);
            l.Add(new TextMessageEncodingBindingElement());
            if (isOneWay)
            {
                l.Add(new OneWayBindingElement());
            }
            l.Add(new HandlerTransportBindingElement(sender));
            CustomBinding b = new CustomBinding(l);

            return(b);
        }
Exemplo n.º 28
0
        //<snippet1>
        private Binding CreateBinding()
        {
            BindingElementCollection        bindings = new BindingElementCollection();
            KerberosSecurityTokenParameters tokens   = new KerberosSecurityTokenParameters();
            SymmetricSecurityBindingElement security =
                new SymmetricSecurityBindingElement(tokens);

            // Require that every request and return be correlated.
            security.RequireSignatureConfirmation = true;

            bindings.Add(security);
            TextMessageEncodingBindingElement encoding = new TextMessageEncodingBindingElement();

            bindings.Add(encoding);
            HttpTransportBindingElement transport = new HttpTransportBindingElement();

            bindings.Add(transport);
            CustomBinding myBinding = new CustomBinding(bindings);

            return(myBinding);
        }
Exemplo n.º 29
0
        public void DefaultMessageSecurity()
        {
            WSHttpBinding b = new WSHttpBinding();
            SymmetricSecurityBindingElement sbe = b.CreateBindingElements().Find <SymmetricSecurityBindingElement> ();

            Assert.IsNotNull(sbe, "#0");

            SecureConversationSecurityTokenParameters p =
                sbe.ProtectionTokenParameters as SecureConversationSecurityTokenParameters;

            Assert.IsNotNull(p, "#1");
            SymmetricSecurityBindingElement scbe =
                p.BootstrapSecurityBindingElement as SymmetricSecurityBindingElement;

            Assert.IsNotNull(scbe, "#1.1");
            // since the default w/o SecureConv is SSPI ...
            Assert.IsTrue(scbe.ProtectionTokenParameters is SspiSecurityTokenParameters, "#1.2");

            Assert.AreEqual(SecurityAlgorithmSuite.Default,
                            sbe.DefaultAlgorithmSuite, "#2");

            SupportingTokenParameters s =
                sbe.EndpointSupportingTokenParameters;

            Assert.IsNotNull(s, "#3");
            Assert.AreEqual(0, s.Endorsing.Count, "#3-1");
            Assert.AreEqual(0, s.Signed.Count, "#3-2");
            Assert.AreEqual(0, s.SignedEndorsing.Count, "#3-3");
            Assert.AreEqual(0, s.SignedEncrypted.Count, "#3-4");

            Assert.AreEqual(0, sbe.OperationSupportingTokenParameters.Count, "#4");

            s = sbe.OptionalEndpointSupportingTokenParameters;
            Assert.IsNotNull(s, "#5");
            Assert.AreEqual(0, s.Endorsing.Count, "#5-1");
            Assert.AreEqual(0, s.Signed.Count, "#5-2");
            Assert.AreEqual(0, s.SignedEndorsing.Count, "#5-3");
            Assert.AreEqual(0, s.SignedEncrypted.Count, "#5-4");
            Assert.AreEqual(0, sbe.OptionalOperationSupportingTokenParameters.Count, "#6");
        }
Exemplo n.º 30
0
	public static void Main ()
	{
		SymmetricSecurityBindingElement sbe =
			new SymmetricSecurityBindingElement ();
		//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.SetKeyDerivation (false);
		sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
		ServiceHost host = new ServiceHost (typeof (Foo));
		HttpTransportBindingElement hbe =
			new HttpTransportBindingElement ();
		CustomBinding binding = new CustomBinding (sbe, hbe);
		binding.ReceiveTimeout = TimeSpan.FromSeconds (5);
		host.AddServiceEndpoint ("IFoo",
			binding, new Uri ("http://localhost:8080"));
		ServiceCredentials cred = new ServiceCredentials ();
		cred.ServiceCertificate.Certificate =
			new X509Certificate2 ("test.pfx", "mono");
		cred.ClientCertificate.Authentication.CertificateValidationMode =
			X509CertificateValidationMode.None;
		host.Description.Behaviors.Add (cred);
		host.Description.Behaviors.Find<ServiceDebugBehavior> ()
			.IncludeExceptionDetailInFaults = true;
		foreach (ServiceEndpoint se in host.Description.Endpoints)
			se.Behaviors.Add (new StdErrInspectionBehavior ());
		ServiceMetadataBehavior smb = new ServiceMetadataBehavior ();
		smb.HttpGetEnabled = true;
		smb.HttpGetUrl = new Uri ("http://localhost:8080/wsdl");
		host.Description.Behaviors.Add (smb);
		host.Open ();
		Console.WriteLine ("Hit [CR] key to close ...");
		Console.ReadLine ();
		host.Close ();
	}
Exemplo n.º 31
0
        public WSManServiceHost()
        {
            try
            {
                //localhost:5985/wsman
                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.SetKeyDerivation(false);
                sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
                _host = new ServiceHost(typeof(WSManHttpService));
                HttpTransportBindingElement hbe = new HttpTransportBindingElement();
                CustomBinding binding           = new CustomBinding(sbe, hbe);
                binding.ReceiveTimeout = TimeSpan.FromSeconds(5);
                _host.AddServiceEndpoint(typeof(IWSManHttpService),
                                         binding, new Uri("http://localhost:5985/wsman"));

                ServiceCredentials cred = new ServiceCredentials();
                cred.ServiceCertificate.Certificate = new X509Certificate2("powershell.pfx", "mono");
                cred.ClientCertificate.Authentication.CertificateValidationMode =
                    X509CertificateValidationMode.None;
                cred.UserNameAuthentication.UserNamePasswordValidationMode  = UserNamePasswordValidationMode.Custom;
                cred.UserNameAuthentication.CustomUserNamePasswordValidator = new WSManUserNamePasswordValidator();
                _host.Description.Behaviors.Add(cred);
                _host.Description.Behaviors.Find <ServiceDebugBehavior> ()
                .IncludeExceptionDetailInFaults = false;
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.HttpGetUrl     = new Uri("http://localhost:5985/wsman/wsdl");
                _host.Description.Behaviors.Add(smb);
            } catch (Exception ex) {
                Console.WriteLine("Could not create service...");
                Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 32
0
    static void Run(string issuerUri, string issuerCertFile)
    {
        SymmetricSecurityBindingElement sbe =
            new SymmetricSecurityBindingElement();
        IssuedSecurityTokenParameters ip =
            new IssuedSecurityTokenParameters();

        ip.ClaimTypeRequirements.Add(new ClaimTypeRequirement(
                                         ClaimTypes.PPID));
        //ClaimTypes.Email));
        if (issuerUri != null)
        {
            // if exists, then a managed card is required.
            ip.IssuerAddress = new EndpointAddress(new Uri(issuerUri),
                                                   new X509CertificateEndpointIdentity(new X509Certificate2(issuerCertFile)));
        }
        X509Certificate2 cert2  = new X509Certificate2("test.cer");
        EndpointAddress  target =
            new EndpointAddress(new Uri("http://localhost:8080"),
                                new X509CertificateEndpointIdentity(cert2));

        sbe.ProtectionTokenParameters            = ip;
        sbe.LocalClientSettings.IdentityVerifier =
            new MyVerifier();
        HttpTransportBindingElement hbe =
            new HttpTransportBindingElement();
        CustomBinding binding = new CustomBinding(sbe, hbe);
        // DefaultCertificate does not work here...
        FooProxy proxy = new FooProxy(binding, target);

        proxy.ClientCredentials.ServiceCertificate.Authentication
        .CertificateValidationMode =
            X509CertificateValidationMode.None;
        proxy.ClientCredentials.ServiceCertificate.Authentication
        .RevocationMode = X509RevocationMode.NoCheck;
        //proxy.ClientCredentials.IssuedToken.LocalIssuerAddress = ip.IssuerAddress;
        //proxy.ClientCredentials.IssuedToken.LocalIssuerBinding = ip.IssuerBinding;
        Console.WriteLine(proxy.Echo("TEST FOR ECHO"));
    }
Exemplo n.º 33
0
	public static void Main (string [] args)
	{
		SymmetricSecurityBindingElement sbe =
			new SymmetricSecurityBindingElement ();
		IssuedSecurityTokenParameters ip =
			new IssuedSecurityTokenParameters ();
		sbe.ProtectionTokenParameters = ip;
		ip.ClaimTypeRequirements.Add (new ClaimTypeRequirement (
			ClaimTypes.Email));
		if (args.Length > 0) {
			ip.IssuerAddress = new EndpointAddress (new Uri (args [0]),
				new X509CertificateEndpointIdentity (new X509Certificate2 (args [1])));
		}
		ServiceHost host = new ServiceHost (typeof (Foo));
		HttpTransportBindingElement hbe =
			new HttpTransportBindingElement ();
		CustomBinding binding = new CustomBinding (sbe, hbe);
		binding.ReceiveTimeout = TimeSpan.FromSeconds (5);
		host.AddServiceEndpoint ("IFoo",
			binding, new Uri ("http://localhost:8080"));
		ServiceCredentials cred = new ServiceCredentials ();
		cred.ServiceCertificate.Certificate =
			new X509Certificate2 ("test.pfx", "mono");
		cred.ClientCertificate.Authentication.CertificateValidationMode =
			X509CertificateValidationMode.None;
		cred.IssuedTokenAuthentication.AllowUntrustedRsaIssuers = true;
		host.Description.Behaviors.Add (cred);
		host.Description.Behaviors.Find<ServiceDebugBehavior> ()
			.IncludeExceptionDetailInFaults = true;
		ServiceMetadataBehavior smb = new ServiceMetadataBehavior ();
		smb.HttpGetEnabled = true;
		smb.HttpGetUrl = new Uri ("http://localhost:8080/wsdl");
		host.Description.Behaviors.Add (smb);
		host.Open ();
		Console.WriteLine ("Hit [CR] key to close ...");
		Console.ReadLine ();
		host.Close ();
	}
Exemplo n.º 34
0
        public void CreateIssuedTokenForCertificateBindingElement1()
        {
            IssuedSecurityTokenParameters tp =
                new IssuedSecurityTokenParameters();
            SymmetricSecurityBindingElement be =
                SecurityBindingElement.CreateIssuedTokenForCertificateBindingElement(tp);

            SecurityAssert.AssertSymmetricSecurityBindingElement(
                SecurityAlgorithmSuite.Default,
                true,                 // IncludeTimestamp
                SecurityKeyEntropyMode.CombinedEntropy,
                MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature,
                MessageSecurityVersion.Default,
                true,                 // RequireSignatureConfirmation
                SecurityHeaderLayout.Strict,
                // EndpointSupportingTokenParameters: endorsing, signed, signedEncrypted, signedEndorsing (by count)
                1, 0, 0, 0,
                // ProtectionTokenParameters
                true, SecurityTokenInclusionMode.Never, SecurityTokenReferenceStyle.Internal, true,
                // LocalClientSettings
                true, 60, true,

                be, "");

            // test ProtectionTokenParameters
            X509SecurityTokenParameters ptp =
                be.ProtectionTokenParameters
                as X509SecurityTokenParameters;

            Assert.IsNotNull(ptp, "#2-1");
            SecurityAssert.AssertSecurityTokenParameters(
                SecurityTokenInclusionMode.Never,
                SecurityTokenReferenceStyle.Internal,
                true, ptp, "Protection");
            Assert.AreEqual(X509KeyIdentifierClauseType.Thumbprint, ptp.X509ReferenceStyle, "#2-2");

            Assert.AreEqual(tp, be.EndpointSupportingTokenParameters.Endorsing [0], "EndpointParams.Endorsing[0]");
        }
Exemplo n.º 35
0
    public static void Main()
    {
        SymmetricSecurityBindingElement sbe =
            new SymmetricSecurityBindingElement();

        sbe.ProtectionTokenParameters =
            new SslSecurityTokenParameters();
        ServiceHost host = new ServiceHost(typeof(Foo));
        HttpTransportBindingElement hbe =
            new HttpTransportBindingElement();
        CustomBinding binding = new CustomBinding(sbe, hbe);

        binding.ReceiveTimeout = TimeSpan.FromSeconds(5);
        host.AddServiceEndpoint("IFoo",
                                binding, new Uri("http://localhost:8080"));
        ServiceCredentials cred = new ServiceCredentials();

        cred.SecureConversationAuthentication.SecurityStateEncoder =
            new MyEncoder();
        cred.ServiceCertificate.Certificate =
            new X509Certificate2("test.pfx", "mono");
        cred.ClientCertificate.Authentication.CertificateValidationMode =
            X509CertificateValidationMode.None;
        host.Description.Behaviors.Add(cred);
        host.Description.Behaviors.Find <ServiceDebugBehavior> ()
        .IncludeExceptionDetailInFaults = true;
//		foreach (ServiceEndpoint se in host.Description.Endpoints)
//			se.Behaviors.Add (new StdErrInspectionBehavior ());
        ServiceMetadataBehavior smb = new ServiceMetadataBehavior();

        smb.HttpGetEnabled = true;
        smb.HttpGetUrl     = new Uri("http://localhost:8080/wsdl");
        host.Description.Behaviors.Add(smb);
        host.Open();
        Console.WriteLine("Hit [CR] key to close ...");
        Console.ReadLine();
        host.Close();
    }
Exemplo n.º 36
0
    static void Run()
    {
        SymmetricSecurityBindingElement sbe =
            new SymmetricSecurityBindingElement();

        //sbe.IncludeTimestamp = false;
        //sbe.LocalClientSettings.DetectReplays = false;

        sbe.ProtectionTokenParameters = new X509SecurityTokenParameters();
        sbe.ProtectionTokenParameters.InclusionMode = SecurityTokenInclusionMode.Never;
        sbe.SetKeyDerivation(false);
        sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
        HttpTransportBindingElement hbe =
            new HttpTransportBindingElement();
        CustomBinding    binding = new CustomBinding(new XBE(), sbe, hbe);
        X509Certificate2 cert    = new X509Certificate2("test.cer");
        FooProxy         proxy   = new FooProxy(binding,
                                                new EndpointAddress(new Uri("http://localhost:8080"), new X509CertificateEndpointIdentity(cert)));

        proxy.Endpoint.Behaviors.Add(new StdErrInspectionBehavior());
        proxy.Open();
        Console.WriteLine(proxy.Echo("TEST FOR ECHO"));
    }
Exemplo n.º 37
0
        Binding CreateIssuerBinding(RequestSender handler, bool tokenParams)
        {
            SymmetricSecurityBindingElement sbe =
                new SymmetricSecurityBindingElement();

            if (tokenParams)
            {
                sbe.ProtectionTokenParameters = new X509SecurityTokenParameters();
            }
            sbe.LocalServiceSettings.NegotiationTimeout = TimeSpan.FromSeconds(5);
            sbe.KeyEntropyMode = SecurityKeyEntropyMode.ClientEntropy;
            //sbe.IncludeTimestamp = false;
            //sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;

            // for ease of decryption, let's remove DerivedKeyToken.
            sbe.SetKeyDerivation(false);

            return(new CustomBinding(
//				new DebugBindingElement (),
                       sbe,
                       new TextMessageEncodingBindingElement(),
                       new HandlerTransportBindingElement(handler)));
        }
Exemplo n.º 38
0
        void ProcessClient()
        {
            SymmetricSecurityBindingElement svcsbe =
                new SymmetricSecurityBindingElement();

            svcsbe.ProtectionTokenParameters =
                new X509SecurityTokenParameters(X509KeyIdentifierClauseType.Thumbprint, SecurityTokenInclusionMode.Never);

            BindingElement cintercept = new InterceptorBindingElement(null);
            CustomBinding  b_req      = new CustomBinding(svcsbe,
                                                          cintercept,
                                                          new HttpTransportBindingElement());

            b_req.ReceiveTimeout = b_req.SendTimeout = TimeSpan.FromSeconds(5);
            EndpointAddress remaddr = new EndpointAddress(
                new Uri("http://localhost:" + NetworkHelpers.FindFreePort()),
                new X509CertificateEndpointIdentity(cert));
            CalcProxy proxy = new CalcProxy(b_req, remaddr);

            proxy.ClientCredentials.ClientCertificate.Certificate = cert2;

            proxy.Sum(1, 2);
            proxy.Close();
        }
Exemplo n.º 39
0
        public void CreateKerberosBindingElement()
        {
            SymmetricSecurityBindingElement be =
                SecurityBindingElement.CreateKerberosBindingElement();

            SecurityAssert.AssertSymmetricSecurityBindingElement(
                SecurityAlgorithmSuite.Basic128,
                true,                 // IncludeTimestamp
                SecurityKeyEntropyMode.CombinedEntropy,
                MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature,
                MessageSecurityVersion.Default,
                false,                 // RequireSignatureConfirmation
                SecurityHeaderLayout.Strict,
                // EndpointSupportingTokenParameters: endorsing, signed, signedEncrypted, signedEndorsing (by count)
                0, 0, 0, 0,
                // ProtectionTokenParameters
                true, SecurityTokenInclusionMode.Once, SecurityTokenReferenceStyle.Internal, true,
                // LocalClientSettings
                true, 60, true,

                be, "");

            // FIXME: test ProtectionTokenParameters
        }
		Binding CreateIssuerBinding (RequestSender handler, bool tokenParams)
		{
			SymmetricSecurityBindingElement sbe =
				new SymmetricSecurityBindingElement ();
			if (tokenParams)
				sbe.ProtectionTokenParameters = new X509SecurityTokenParameters ();
			sbe.LocalServiceSettings.NegotiationTimeout = TimeSpan.FromSeconds (5);
			sbe.KeyEntropyMode = SecurityKeyEntropyMode.ClientEntropy;
			//sbe.IncludeTimestamp = false;
			//sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;

			// for ease of decryption, let's remove DerivedKeyToken.
			sbe.SetKeyDerivation (false);

			return new CustomBinding (
//				new DebugBindingElement (),
				sbe,
				new TextMessageEncodingBindingElement (),
				new HandlerTransportBindingElement (handler));
		}
 public virtual bool TryImportWsspProtectionTokenAssertion(MetadataImporter importer, PolicyConversionContext policyContext, ICollection<XmlElement> assertions, SymmetricSecurityBindingElement binding)
 {
     XmlElement element;
     Collection<Collection<XmlElement>> collection;
     bool flag = false;
     if (this.TryImportWsspAssertion(assertions, "ProtectionToken", out element) && this.TryGetNestedPolicyAlternatives(importer, element, out collection))
     {
         foreach (Collection<XmlElement> collection2 in collection)
         {
             SecurityTokenParameters parameters;
             bool flag2;
             if (this.TryImportTokenAssertion(importer, policyContext, collection2, out parameters, out flag2) && (collection2.Count == 0))
             {
                 flag = true;
                 binding.ProtectionTokenParameters = parameters;
                 return flag;
             }
         }
     }
     return flag;
 }
		public void SetKeyDerivation ()
		{
			SymmetricSecurityBindingElement be;
			X509SecurityTokenParameters p;

			be = new SymmetricSecurityBindingElement ();
			p = new X509SecurityTokenParameters ();
			be.ProtectionTokenParameters = p;
			be.SetKeyDerivation (false);
			Assert.AreEqual (false, p.RequireDerivedKeys, "#1");

			be = new SymmetricSecurityBindingElement ();
			p = new X509SecurityTokenParameters ();
			be.SetKeyDerivation (false); // set in prior - makes no sense
			be.ProtectionTokenParameters = p;
			Assert.AreEqual (true, p.RequireDerivedKeys, "#2");
		}
        public virtual bool TryImportWsspSymmetricBindingAssertion(MetadataImporter importer, PolicyConversionContext policyContext, ICollection<XmlElement> assertions, out SymmetricSecurityBindingElement binding, out XmlElement assertion)
        {
            binding = null;

            Collection<Collection<XmlElement>> alternatives;

            if (TryImportWsspAssertion(assertions, SymmetricBindingName, out assertion)
                && TryGetNestedPolicyAlternatives(importer, assertion, out alternatives))
            {
                foreach (Collection<XmlElement> alternative in alternatives)
                {
                    MessageProtectionOrder order;
                    bool protectTokens;
                    binding = new SymmetricSecurityBindingElement();
                    if (TryImportWsspProtectionTokenAssertion(importer, policyContext, alternative, binding)
                        && TryImportWsspAlgorithmSuiteAssertion(importer, alternative, binding)
                        && TryImportWsspLayoutAssertion(importer, alternative, binding)
                        && TryImportWsspIncludeTimestampAssertion(alternative, binding)
                        && TryImportMessageProtectionOrderAssertions(alternative, out order)
                        && TryImportWsspProtectTokensAssertion(alternative, out protectTokens)
                        && TryImportWsspAssertion(alternative, OnlySignEntireHeadersAndBodyName, true)
                        && alternative.Count == 0)
                    {
                        binding.MessageProtectionOrder = order;
                        binding.ProtectTokens = protectTokens;
                        break;
                    }
                    else
                    {
                        binding = null;
                    }
                }
            }

            return binding != null;
        }
        public virtual bool TryImportWsspProtectionTokenAssertion(MetadataImporter importer, PolicyConversionContext policyContext, ICollection<XmlElement> assertions, SymmetricSecurityBindingElement binding)
        {
            bool result = false;

            XmlElement assertion;
            Collection<Collection<XmlElement>> alternatives;
            if (TryImportWsspAssertion(assertions, ProtectionTokenName, out assertion)
                && TryGetNestedPolicyAlternatives(importer, assertion, out alternatives))
            {
                foreach (Collection<XmlElement> alternative in alternatives)
                {
                    SecurityTokenParameters tokenParameters;
                    bool isOptional;
                    if (TryImportTokenAssertion(importer, policyContext, alternative, out tokenParameters, out isOptional)
                        && alternative.Count == 0)
                    {
                        result = true;
                        binding.ProtectionTokenParameters = tokenParameters;
                        break;
                    }
                }
            }

            return result;
        }
		public void MessageSecurityManualProtection ()
		{
			SymmetricSecurityBindingElement sbe =
				new SymmetricSecurityBindingElement ();
			sbe.ProtectionTokenParameters =
				new X509SecurityTokenParameters ();
			RequestSender sender = delegate (Message input) {
				MessageBuffer buf = input.CreateBufferedCopy (0x10000);
				using (XmlWriter w = XmlWriter.Create (Console.Error)) {
					buf.CreateMessage ().WriteMessage (w);
				}
				return buf.CreateMessage ();
			};

			CustomBinding binding = new CustomBinding (
				sbe,
				new TextMessageEncodingBindingElement (),
				new HandlerTransportBindingElement (sender));

			EndpointAddress address = new EndpointAddress (
				new Uri ("http://localhost:8080"),
				new X509CertificateEndpointIdentity (new X509Certificate2 ("Test/Resources/test.pfx", "mono")));

			ChannelProtectionRequirements reqs =
				new ChannelProtectionRequirements ();
			reqs.OutgoingSignatureParts.AddParts (
				new MessagePartSpecification (new XmlQualifiedName ("SampleValue", "urn:foo")), "urn:myaction");
			BindingParameterCollection parameters =
				new BindingParameterCollection ();
			parameters.Add (reqs);
/*
			SymmetricSecurityBindingElement innersbe =
				new SymmetricSecurityBindingElement ();
			innersbe.ProtectionTokenParameters =
				new X509SecurityTokenParameters ();
			sbe.ProtectionTokenParameters =
				new SecureConversationSecurityTokenParameters (
					innersbe, false, reqs);
*/

			IChannelFactory<IRequestChannel> cf =
				binding.BuildChannelFactory<IRequestChannel> (parameters);
			cf.Open ();
			IRequestChannel ch = cf.CreateChannel (address);

			ch.Open ();
			try {
				ch.Request (Message.CreateMessage (MessageVersion.None, "urn:myaction", new SampleValue ()));
			} finally {
				ch.Close ();
			}
		}
Exemplo n.º 46
0
		public void NonEndorsibleParameterInEndorsingSupport ()
		{
			SymmetricSecurityBindingElement be =
				new SymmetricSecurityBindingElement ();
			be.ProtectionTokenParameters =
				new X509SecurityTokenParameters ();
			be.EndpointSupportingTokenParameters.Endorsing.Add (
				new UserNameSecurityTokenParameters ());
			Binding b = new CustomBinding (be, new HttpTransportBindingElement ());
			X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.pfx", "mono");
			EndpointAddress ea = new EndpointAddress (new Uri ("http://localhost:" + NetworkHelpers.FindFreePort ()), new X509CertificateEndpointIdentity (cert));
			CalcProxy client = new CalcProxy (b, ea);
			client.ClientCredentials.UserName.UserName = "******";
			client.Sum (1, 2);
		}
Exemplo n.º 47
0
		public void CheckDuplicateAuthenticatorTypesService ()
		{
			SymmetricSecurityBindingElement be =
				new SymmetricSecurityBindingElement ();
			be.ProtectionTokenParameters =
				new X509SecurityTokenParameters ();
			be.EndpointSupportingTokenParameters.Endorsing.Add (
				new X509SecurityTokenParameters ());
			// This causes multiple supporting token authenticator
			// of the same type.
			be.OptionalEndpointSupportingTokenParameters.Endorsing.Add (
				new X509SecurityTokenParameters ());
			Binding b = new CustomBinding (be, new HttpTransportBindingElement ());
			ServiceCredentials cred = new ServiceCredentials ();
			cred.ServiceCertificate.Certificate =
				new X509Certificate2 ("Test/Resources/test.pfx", "mono");
			IChannelListener<IReplyChannel> ch = b.BuildChannelListener<IReplyChannel> (new Uri ("http://localhost:" + NetworkHelpers.FindFreePort ()), cred);
			try {
				ch.Open ();
			} finally {
				if (ch.State == CommunicationState.Closed)
					ch.Close ();
			}
		}
Exemplo n.º 48
0
		public static void AssertSymmetricSecurityBindingElement (
			SecurityAlgorithmSuite algorithm,
			bool includeTimestamp,
			SecurityKeyEntropyMode keyEntropyMode,
			MessageProtectionOrder messageProtectionOrder,
			MessageSecurityVersion messageSecurityVersion,
			bool requireSignatureConfirmation,
			SecurityHeaderLayout securityHeaderLayout,
			// EndpointSupportingTokenParameters
			int endorsing, int signed, int signedEncrypted, int signedEndorsing,
			// ProtectionTokenParameters
			bool hasProtectionTokenParameters,
			SecurityTokenInclusionMode protectionTokenInclusionMode,
			SecurityTokenReferenceStyle protectionTokenReferenceStyle,
			bool protectionTokenRequireDerivedKeys,
			// LocalClientSettings
			bool cacheCookies,
			int renewalThresholdPercentage,
			bool detectReplays,
			SymmetricSecurityBindingElement be, string label)
		{
			AssertSecurityBindingElement (
				algorithm,
				includeTimestamp,
				keyEntropyMode,
				messageSecurityVersion,
				securityHeaderLayout,
				// EndpointSupportingTokenParameters
				endorsing, signed, signedEncrypted, signedEndorsing,
				// LocalClientSettings
				cacheCookies,
				renewalThresholdPercentage,
				detectReplays,
				be, label);

			Assert.AreEqual (messageProtectionOrder, be.MessageProtectionOrder, label + ".MessageProtectionOrder");
			Assert.AreEqual (requireSignatureConfirmation, be.RequireSignatureConfirmation, label + ".RequireSignatureConfirmation");

			if (!hasProtectionTokenParameters)
				Assert.IsNull (be.ProtectionTokenParameters, label + ".ProtectionTokenParameters (null)");
			else
				AssertSecurityTokenParameters (
					protectionTokenInclusionMode,
					protectionTokenReferenceStyle,
					protectionTokenRequireDerivedKeys,
					be.ProtectionTokenParameters, label + ".ProtectionTokenParameters");
		}
		CustomBinding CreateBinding (RequestSender sender,
			SecurityTokenParameters protectionTokenParameters,
			bool isOneWay)
		{
			SymmetricSecurityBindingElement sbe =
				new SymmetricSecurityBindingElement ();
			sbe.ProtectionTokenParameters = protectionTokenParameters;
			List<BindingElement> l = new List<BindingElement> ();
			l.Add (sbe);
			l.Add (new TextMessageEncodingBindingElement ());
			if (isOneWay)
				l.Add (new OneWayBindingElement ());
			l.Add (new HandlerTransportBindingElement (sender));
			CustomBinding b = new CustomBinding (l);
			return b;
		}
		public void OpenRequestNonAuthenticatable ()
		{
			SymmetricSecurityBindingElement sbe = 
				new SymmetricSecurityBindingElement ();
			sbe.ProtectionTokenParameters =
				new UserNameSecurityTokenParameters ();
			Binding binding = new CustomBinding (sbe, new HandlerTransportBindingElement (null));
			BindingParameterCollection pl =
				new BindingParameterCollection ();
			ClientCredentials cred = new ClientCredentials ();
			cred.UserName.UserName = "******";
			pl.Add (cred);
			IChannelFactory<IRequestChannel> f =
				binding.BuildChannelFactory<IRequestChannel> (pl);
			f.Open ();
			IRequestChannel ch = f.CreateChannel (new EndpointAddress ("stream:dummy"));
			try {
				ch.Open ();
				Assert.Fail ("NotSupportedException is expected.");
			} catch (NotSupportedException) {
			}
		}
Exemplo n.º 51
0
		protected override SecurityBindingElement CreateMessageSecurity ()
		{
			if (Security.Mode == SecurityMode.Transport ||
			    Security.Mode == SecurityMode.None)
				return null;

			SymmetricSecurityBindingElement element =
				new SymmetricSecurityBindingElement ();

			element.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
			element.RequireSignatureConfirmation = true;

			switch (Security.Message.ClientCredentialType) {
			case MessageCredentialType.Certificate:
				X509SecurityTokenParameters p =
					new X509SecurityTokenParameters (X509KeyIdentifierClauseType.Thumbprint);
				p.RequireDerivedKeys = false;
				element.EndpointSupportingTokenParameters.Endorsing.Add (p);
				goto default;
			case MessageCredentialType.IssuedToken:
				IssuedSecurityTokenParameters istp =
					new IssuedSecurityTokenParameters ();
				// FIXME: issuer binding must be secure.
				istp.IssuerBinding = new CustomBinding (
					new TextMessageEncodingBindingElement (),
					GetTransport ());
				element.EndpointSupportingTokenParameters.Endorsing.Add (istp);
				goto default;
			case MessageCredentialType.UserName:
				element.EndpointSupportingTokenParameters.SignedEncrypted.Add (
					new UserNameSecurityTokenParameters ());
				element.RequireSignatureConfirmation = false;
				goto default;
			case MessageCredentialType.Windows:
				if (Security.Message.NegotiateServiceCredential) {
					// No SSPI on Linux though...
					element.ProtectionTokenParameters =
						// FIXME: fill proper parameters
						new SspiSecurityTokenParameters ();
				} else {
					// and no Kerberos ...
					element.ProtectionTokenParameters =
						new KerberosSecurityTokenParameters ();
				}
				break;
			default: // including .None
				if (Security.Message.NegotiateServiceCredential) {
					element.ProtectionTokenParameters =
						// FIXME: fill proper parameters
						new SslSecurityTokenParameters (false, true);
				} else {
					element.ProtectionTokenParameters =
						new X509SecurityTokenParameters (X509KeyIdentifierClauseType.Thumbprint, SecurityTokenInclusionMode.Never);
					element.ProtectionTokenParameters.RequireDerivedKeys = true;
				}
				break;
			}

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

			// SecureConversation enabled

			ChannelProtectionRequirements reqs =
				new ChannelProtectionRequirements ();
			// FIXME: fill the reqs

			return SecurityBindingElement.CreateSecureConversationBindingElement (
				// FIXME: requireCancellation
				element, true, reqs);
		}
		public void OtherParameterInEndorsingSupport ()
		{
			SymmetricSecurityBindingElement be =
				new SymmetricSecurityBindingElement ();
			be.ProtectionTokenParameters =
				new X509SecurityTokenParameters ();
			be.EndpointSupportingTokenParameters.Endorsing.Add (
				new MyEndorsingTokenParameters ());
			Binding b = new CustomBinding (be, new HttpTransportBindingElement ());
			EndpointAddress ea = new EndpointAddress (new Uri ("http://localhost:37564"), new X509CertificateEndpointIdentity (cert));
			CalcProxy client = new CalcProxy (b, ea);
			client.Endpoint.Behaviors.RemoveAll<ClientCredentials> ();
			client.Endpoint.Behaviors.Add (new MyClientCredentials ());
			client.Sum (1, 2);
		}
        private SecurityBindingElement CreateSecurityBindingElement()
        {
            SymmetricSecurityBindingElement secBindingElement = new SymmetricSecurityBindingElement();

            secBindingElement.SecurityHeaderLayout = SecurityHeaderLayout.Strict;

            // TEST
            //secBindingElement.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Basic256Rsa15;
            secBindingElement.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Basic256;

            secBindingElement.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
            secBindingElement.IncludeTimestamp = true;
            secBindingElement.SetKeyDerivation(false);
            //secBindingElement.RequireSignatureConfirmation = true;
            //secBindingElement.AllowInsecureTransport = true;

            //////////////////////////////////////////////////////////
            SecurityBindingElement ssbe = (SecurityBindingElement)secBindingElement;

            // Set the Custom IdentityVerifier
            //ssbe.LocalClientSettings.IdentityVerifier = new Common.CustomIdentityVerifier();
            //////////////////////////////////////////////////////////


            X509SecurityTokenParameters protectTokenParameters = new X509SecurityTokenParameters(X509KeyIdentifierClauseType.Thumbprint,
                SecurityTokenInclusionMode.Never);

            protectTokenParameters.X509ReferenceStyle = X509KeyIdentifierClauseType.Thumbprint;

            //X509SecurityTokenParameters protectTokenParameters = new X509SecurityTokenParameters(X509KeyIdentifierClauseType.IssuerSerial,
            //    SecurityTokenInclusionMode.Never);

            protectTokenParameters.RequireDerivedKeys = false;

            //protectTokenParameters.InclusionMode = SecurityTokenInclusionMode.Never;
            //protectTokenParameters.InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient;

            secBindingElement.ProtectionTokenParameters = protectTokenParameters;

            UserNameSecurityTokenParameters userNameToken = new UserNameSecurityTokenParameters();
            userNameToken.InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient;

            secBindingElement.EndpointSupportingTokenParameters.SignedEncrypted.Add(userNameToken);
            //secBindingElement.EndpointSupportingTokenParameters.Signed.Add(userNameToken);


            //secBindingElement.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12;
            secBindingElement.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;


            return secBindingElement;
        }
Exemplo n.º 54
0
		// based on WSHttpBinding.CreateMessageSecurity()
		SecurityBindingElement CreateMessageSecurity ()
		{
			if (Security.Mode == SecurityMode.Transport ||
			    Security.Mode == SecurityMode.None)
				return null;

			SymmetricSecurityBindingElement element =
				new SymmetricSecurityBindingElement ();

			element.MessageSecurityVersion = MessageSecurityVersion.Default;

			element.SetKeyDerivation (false);

			switch (Security.Message.ClientCredentialType) {
			case MessageCredentialType.Certificate:
				element.EndpointSupportingTokenParameters.Endorsing.Add (
					new X509SecurityTokenParameters ());
				goto default;
			case MessageCredentialType.IssuedToken:
				IssuedSecurityTokenParameters istp =
					new IssuedSecurityTokenParameters ();
				// FIXME: issuer binding must be secure.
				istp.IssuerBinding = new CustomBinding (
					new TextMessageEncodingBindingElement (),
					GetTransport ());
				element.EndpointSupportingTokenParameters.Endorsing.Add (istp);
				goto default;
			case MessageCredentialType.UserName:
				element.EndpointSupportingTokenParameters.SignedEncrypted.Add (
					new UserNameSecurityTokenParameters ());
				goto default;
			case MessageCredentialType.Windows:
				element.ProtectionTokenParameters =
					new KerberosSecurityTokenParameters ();
				break;
			default: // including .None
				X509SecurityTokenParameters p =
					new X509SecurityTokenParameters ();
				p.X509ReferenceStyle = X509KeyIdentifierClauseType.Thumbprint;
				element.ProtectionTokenParameters = p;
				break;
			}

			return element;
		}
		//  Envelope Version 'EnvelopeNone (http://schemas.microsoft.com/ws/2005/05/envelope/none)'
		// does not support adding Message Headers.
		public void MessageSecurityPOX ()
		{
			SymmetricSecurityBindingElement sbe =
				new SymmetricSecurityBindingElement ();
			sbe.ProtectionTokenParameters =
				new X509SecurityTokenParameters ();
			RequestSender sender = delegate (Message input) {
				MessageBuffer buf = input.CreateBufferedCopy (0x10000);
				using (XmlWriter w = XmlWriter.Create (Console.Error)) {
					buf.CreateMessage ().WriteMessage (w);
				}
				return buf.CreateMessage ();
			};

			CustomBinding binding = new CustomBinding (
				sbe,
				new TextMessageEncodingBindingElement (
					MessageVersion.None, Encoding.UTF8),
				new HandlerTransportBindingElement (sender));

			EndpointAddress address = new EndpointAddress (
				new Uri ("http://localhost:8080"),
				new X509CertificateEndpointIdentity (new X509Certificate2 ("Test/Resources/test.pfx", "mono")));

			ChannelFactory<IRequestChannel> cf =
				new ChannelFactory<IRequestChannel> (binding, address);
			IRequestChannel ch = cf.CreateChannel ();
/*
			// neither of Endpoint, Contract nor its Operation seems
			// to have applicable behaviors (except for
			// ClientCredentials)
			Assert.AreEqual (1, cf.Endpoint.Behaviors.Count, "EndpointBehavior");
			Assert.AreEqual (0, cf.Endpoint.Contract.Behaviors.Count, "ContractBehavior");
			Assert.AreEqual (1, cf.Endpoint.Contract.Operations.Count, "Operations");
			OperationDescription od = cf.Endpoint.Contract.Operations [0];
			Assert.AreEqual (0, od.Behaviors.Count, "OperationBehavior");
*/

			ch.Open ();
			try {
				ch.Request (Message.CreateMessage (MessageVersion.None, "urn:myaction"));
			} finally {
				ch.Close ();
			}
		}
Exemplo n.º 56
0
		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);
		}
        public virtual XmlElement CreateWsspSymmetricBindingAssertion(MetadataExporter exporter, PolicyConversionContext policyContext, SymmetricSecurityBindingElement binding)
        {
            if (binding == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("binding");
            }

            XmlElement result = CreateWsspAssertion(SymmetricBindingName);
            result.AppendChild(
                CreateWspPolicyWrapper(
                    exporter,
                    CreateWsspProtectionTokenAssertion(exporter, binding.ProtectionTokenParameters),
                    CreateWsspAlgorithmSuiteAssertion(exporter, binding.DefaultAlgorithmSuite),
                    CreateWsspLayoutAssertion(exporter, binding.SecurityHeaderLayout),
                    CreateWsspIncludeTimestampAssertion(binding.IncludeTimestamp),
                    CreateWsspEncryptBeforeSigningAssertion(binding.MessageProtectionOrder),
                    CreateWsspEncryptSignatureAssertion(policyContext, binding),
                    CreateWsspProtectTokensAssertion(binding),
                    CreateWsspAssertion(OnlySignEntireHeadersAndBodyName)
            ));

            return result;
        }
 public virtual bool TryImportWsspSymmetricBindingAssertion(MetadataImporter importer, PolicyConversionContext policyContext, ICollection<XmlElement> assertions, out SymmetricSecurityBindingElement binding, out XmlElement assertion)
 {
     Collection<Collection<XmlElement>> collection;
     binding = null;
     if (this.TryImportWsspAssertion(assertions, "SymmetricBinding", out assertion) && this.TryGetNestedPolicyAlternatives(importer, assertion, out collection))
     {
         foreach (Collection<XmlElement> collection2 in collection)
         {
             MessageProtectionOrder order;
             binding = new SymmetricSecurityBindingElement();
             if (((this.TryImportWsspProtectionTokenAssertion(importer, policyContext, collection2, binding) && this.TryImportWsspAlgorithmSuiteAssertion(importer, collection2, binding)) && (this.TryImportWsspLayoutAssertion(importer, collection2, binding) && this.TryImportWsspIncludeTimestampAssertion(collection2, binding))) && ((this.TryImportMessageProtectionOrderAssertions(collection2, out order) && this.TryImportWsspAssertion(collection2, "OnlySignEntireHeadersAndBody", true)) && (collection2.Count == 0)))
             {
                 binding.MessageProtectionOrder = order;
                 break;
             }
             binding = null;
         }
     }
     return (binding != null);
 }
		CustomBinding CreateBinding (ReplyHandler replier, RequestReceiver receiver)
		{
			SymmetricSecurityBindingElement sbe =
				new SymmetricSecurityBindingElement ();
			sbe.ProtectionTokenParameters =
				new X509SecurityTokenParameters ();
			CustomBinding b = new CustomBinding (
				sbe,
				new TextMessageEncodingBindingElement (),
				new HandlerTransportBindingElement (replier, receiver));
			return b;
		}
		// It is problematic, but there is no option to disable establishing security context in this binding unlike WSHttpBinding...
		SecurityBindingElement CreateMessageSecurity ()
		{
			if (Security.Mode == SecurityMode.Transport ||
			    Security.Mode == SecurityMode.None)
				return null;

			// FIXME: this is wrong. Could be Asymmetric, depends on Security.Message.AlgorithmSuite value.
			SymmetricSecurityBindingElement element =
				new SymmetricSecurityBindingElement ();

			element.MessageSecurityVersion = MessageSecurityVersion.Default;

			element.SetKeyDerivation (false);

			switch (Security.Message.ClientCredentialType) {
			case MessageCredentialType.Certificate:
				element.EndpointSupportingTokenParameters.Endorsing.Add (
					new X509SecurityTokenParameters ());
				goto default;
			case MessageCredentialType.IssuedToken:
				IssuedSecurityTokenParameters istp =
					new IssuedSecurityTokenParameters ();
				// FIXME: issuer binding must be secure.
				istp.IssuerBinding = new CustomBinding (
					new TextMessageEncodingBindingElement (),
					GetTransport ());
				element.EndpointSupportingTokenParameters.Endorsing.Add (istp);
				goto default;
			case MessageCredentialType.UserName:
				element.EndpointSupportingTokenParameters.SignedEncrypted.Add (
					new UserNameSecurityTokenParameters ());
				goto default;
			case MessageCredentialType.Windows:
				element.ProtectionTokenParameters =
					new KerberosSecurityTokenParameters ();
				break;
			default: // including .None
				X509SecurityTokenParameters p =
					new X509SecurityTokenParameters ();
				p.X509ReferenceStyle = X509KeyIdentifierClauseType.Thumbprint;
				element.ProtectionTokenParameters = p;
				break;
			}

			// SecureConversation enabled

			ChannelProtectionRequirements reqs =
				new ChannelProtectionRequirements ();
			// FIXME: fill the reqs

			return SecurityBindingElement.CreateSecureConversationBindingElement (
				// FIXME: requireCancellation
				element, true, reqs);
		}