Пример #1
0
    public static void ServerCertificateValidationUsingIdentity_Throws_EchoString()
    {
        EndpointAddress endpointAddress      = null;
        string          testString           = "Hello";
        ChannelFactory <IWcfService> factory = null;
        IWcfService serviceProxy             = null;

        try
        {
            // *** SETUP *** \\
            CustomBinding binding = new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8), new HttpsTransportBindingElement());

            // This is intentionally the wrong certificate
            var identity = new X509CertificateEndpointIdentity(ServiceUtilHelper.ClientCertificate);
            endpointAddress = new EndpointAddress(new Uri(Endpoints.Https_DefaultBinding_Address_Text), identity);

            factory      = new ChannelFactory <IWcfService>(binding, endpointAddress);
            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            Assert.Throws <SecurityNegotiationException>(() => { _ = serviceProxy.Echo(testString); });

            // *** CLEANUP *** \\
            ((ICommunicationObject)serviceProxy).Close();
            factory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
        EndpointAddress CreateX509EndpointAddress(string uri)
        {
            EndpointIdentity identity =
                new X509CertificateEndpointIdentity(new X509Certificate2(TestResourceHelper.GetFullPathOfResource("Test/Resources/test.pfx"), "mono"));

            return(new EndpointAddress(new Uri(uri), identity));
        }
        public void FullRequest()
        {
            EndpointIdentity identity =
                new X509CertificateEndpointIdentity(new X509Certificate2("Test/Resources/test.pfx", "mono"));
            EndpointAddress address =
                new EndpointAddress(new Uri("stream:dummy"), identity);

            Message mreq   = Message.CreateMessage(MessageVersion.Default, "myAction");
            Message mreply = null;

            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent = true;

            // listener setup
            ReplyHandler replyHandler = delegate(Message rinput)
            {
                mreply = rinput;
            };
            RequestReceiver receiver = delegate()
            {
                return(mreq);
            };
            IChannelListener <IReplyChannel> listener = CreateListener(replyHandler, receiver);

            listener.Open();
            IReplyChannel reply = listener.AcceptChannel();

            reply.Open();

            RequestSender reqHandler = delegate(Message input)
            {
                try
                {
                    // sync version somehow causes an infinite loop (!?)
                    RequestContext ctx = reply.EndReceiveRequest(reply.BeginReceiveRequest(TimeSpan.FromSeconds(5), null, null));
//					RequestContext ctx = reply.ReceiveRequest (TimeSpan.FromSeconds (5));
                    Console.Error.WriteLine("Acquired RequestContext.");
                    ctx.Reply(input);
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine("ERROR during processing a request in FullRequest()");
                    Console.Error.WriteLine(ex);
                    Console.Error.Flush();
                    throw;
                }
                return(mreply);
            };
            CustomBinding b = CreateBinding(reqHandler);

            IRequestChannel ch = ChannelFactory <IRequestChannel> .CreateChannel(b, address);

            ch.Open();
            Console.Error.WriteLine("**** starting a request  ****");
            IAsyncResult async = ch.BeginRequest(mreq, null, null);

            Console.Error.WriteLine("**** request started. ****");
            Message res = ch.EndRequest(async);
        }
Пример #4
0
        protected override void ValidateCreateChannelParameters(EndpointAddress remoteAddress, Uri via)
        {
            if (remoteAddress.Identity != null)
            {
                X509CertificateEndpointIdentity certificateIdentity =
                    remoteAddress.Identity as X509CertificateEndpointIdentity;
                if (certificateIdentity != null)
                {
                    if (certificateIdentity.Certificates.Count > 1)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("remoteAddress", SR.GetString(
                                                                                         SR.HttpsIdentityMultipleCerts, remoteAddress.Uri));
                    }
                }

                EndpointIdentity identity      = remoteAddress.Identity;
                bool             validIdentity = (certificateIdentity != null) ||
                                                 ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType) ||
                                                 ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType) ||
                                                 ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType);

                if (!HttpChannelFactory <TChannel> .IsWindowsAuth(this.AuthenticationScheme) &&
                    !validIdentity)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("remoteAddress", SR.GetString(
                                                                                     SR.HttpsExplicitIdentity));
                }
            }
            base.ValidateCreateChannelParameters(remoteAddress, via);
        }
        public void ClientAcceptUpgrade()
        {
            ServiceCredentials cred = new ServiceCredentials();
            X509Certificate2   cert =
                new X509Certificate2("Test/Resources/test.cer");

            cred.ServiceCertificate.Certificate = cert;
            X509CertificateEndpointIdentity ident =
                new X509CertificateEndpointIdentity(cert);
            StreamSecurityUpgradeProvider p = CreateClientProvider(cred, ident);

            p.Open();
            try
            {
                StreamSecurityUpgradeAcceptor a =
                    p.CreateUpgradeAcceptor()
                    as StreamSecurityUpgradeAcceptor;
                Assert.IsNotNull(a, "#1");
                SecurityMessageProperty prop =
                    a.GetRemoteSecurity();
                Assert.IsNull(prop, "#2"); // hmm
                Stream s = a.AcceptUpgrade(new MemoryStream(new byte [] { 1, 2, 3, 4, 5 }));
            }
            finally
            {
                p.Close();
            }
        }
Пример #6
0
        public static void AddServerCertIdentityValidation(HttpClientHandler httpClientHandler, EndpointAddress to)
        {
            X509CertificateEndpointIdentity remoteCertificateIdentity = to.Identity as X509CertificateEndpointIdentity;

            if (remoteCertificateIdentity != null)
            {
                // The following condition should have been validated when the channel was created.
                Fx.Assert(remoteCertificateIdentity.Certificates.Count <= 1,
                          "HTTPS server certificate identity contains multiple certificates");
                var rawData    = remoteCertificateIdentity.Certificates[0].GetRawCertData();
                var thumbprint = remoteCertificateIdentity.Certificates[0].Thumbprint;
                bool identityValidator(HttpRequestMessage requestMessage, X509Certificate2 cert, X509Chain chain, SslPolicyErrors policyErrors)
                {
                    try
                    {
                        ValidateServerCertificate(cert, rawData, thumbprint);
                    }
                    catch (SecurityNegotiationException e)
                    {
                        DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                        return(false);
                    }

                    return(policyErrors == SslPolicyErrors.None);
                }

                SetServerCertificateValidationCallback(httpClientHandler, identityValidator);
            }
        }
        EndpointAddress CreateX509EndpointAddress(string uri)
        {
            EndpointIdentity identity =
                new X509CertificateEndpointIdentity(new X509Certificate2("Test/Resources/test.pfx", "mono"));

            return(new EndpointAddress(new Uri(uri), identity));
        }
        public static void AddServerCertMapping(HttpWebRequest request, EndpointAddress to)
        {
            X509CertificateEndpointIdentity identity = to.Identity as X509CertificateEndpointIdentity;

            if (identity != null)
            {
                AddServerCertMapping(request, identity.Certificates[0].Thumbprint);
            }
        }
Пример #9
0
        public static void AddServerCertMapping(HttpRequestMessage request, EndpointAddress to)
        {
            Fx.Assert(request.RequestUri.Scheme == UriEx.UriSchemeHttps,
                      "Wrong URI scheme for AddServerCertMapping().");
            X509CertificateEndpointIdentity remoteCertificateIdentity = to.Identity as X509CertificateEndpointIdentity;

            if (remoteCertificateIdentity != null)
            {
                // The following condition should have been validated when the channel was created.
                Fx.Assert(remoteCertificateIdentity.Certificates.Count <= 1,
                          "HTTPS server certificate identity contains multiple certificates");
                AddServerCertMapping(request, remoteCertificateIdentity.Certificates[0].Thumbprint);
            }
        }
Пример #10
0
        public static NCIServiceWCFClient CreateNCIServiceClient(Uri uri)
        {
            UCCProxyFactory.ClientCertificatePath     = HostingEnvironment.MapPath(@"~/App_Data/isbank_test_private.pfx");
            UCCProxyFactory.ServiceCertificatePath    = HostingEnvironment.MapPath(@"~/App_Data/ucc_test_public.cer");
            UCCProxyFactory.ClientCertificatePassword = "******";

            System.Net.ServicePointManager.Expect100Continue = false;

            if (string.IsNullOrEmpty(ClientCertificatePath) || string.IsNullOrEmpty(ServiceCertificatePath))
            {
                throw new InvalidOperationException("You should specify certificates path first");
            }

            if (string.IsNullOrEmpty(ClientCertificatePassword))
            {
                throw new InvalidOperationException("You should specify ClientCertificatePassword");
            }

            clientCertificate  = new X509Certificate2(ClientCertificatePath, ClientCertificatePassword);
            serviceCertificate = new X509Certificate2(ServiceCertificatePath);

            endpointIdentity = new X509CertificateEndpointIdentity(serviceCertificate, new X509Certificate2Collection(clientCertificate));
            EndpointAddress ea = new EndpointAddress(uri, endpointIdentity);

            CustomBinding cb = new CustomBinding();

            cb.CloseTimeout = new TimeSpan(50000000);
            TextMessageEncodingBindingElement messageBindingElement = new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8);
            HttpTransportBindingElement       nciTransport          = new HttpTransportBindingElement();

            nciTransport.MaxReceivedMessageSize = 5000000;                       //115000000;
            messageBindingElement.ReaderQuotas.MaxStringContentLength = 1200000; //11200000;
            AsymmetricSecurityBindingElement abe = SecurityBindingElement.CreateMutualCertificateDuplexBindingElement(MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10);;

            abe.AllowSerializedSigningTokenOnReply = true;
            abe.MessageProtectionOrder             = System.ServiceModel.Security.MessageProtectionOrder.SignBeforeEncrypt;
            abe.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Basic128Rsa15;
            abe.SetKeyDerivation(false);
            cb.Elements.Add(abe);
            cb.Elements.Add(messageBindingElement);
            cb.Elements.Add(nciTransport);
            NCIServiceWCFClient nciClient = new NCIServiceWCFClient(cb, ea);

            nciClient.ClientCredentials.ServiceCertificate.DefaultCertificate = serviceCertificate;
            nciClient.ClientCredentials.ClientCertificate.Certificate         = clientCertificate;
            nciClient.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;

            return(nciClient);
        }
Пример #11
0
        private static EndpointAddress ReadFrom(System.ServiceModel.Channels.AddressingVersion addressingVersion, XmlReader xreader)
        {
            string           xml      = xreader.ReadOuterXml();
            StringReader     sreader  = new StringReader(xml);
            XmlReader        reader   = XmlReader.Create(sreader);
            Uri              uri      = null;
            EndpointIdentity identity = null;

            reader.MoveToContent();
            List <AddressHeader> header = new List <AddressHeader> ();

            while (reader.NodeType == XmlNodeType.Element && !reader.IsEmptyElement)
            {
                if (reader.LocalName == "EndpointReference")
                {
                    reader.Read();
                }
                else if (reader.LocalName == "Address" &&
                         reader.NodeType == XmlNodeType.Element &&
                         !reader.IsEmptyElement)
                {
                    uri = new Uri(reader.ReadElementContentAsString());
                }
                else if (reader.LocalName == "Identity" &&
                         reader.NodeType == XmlNodeType.Element &&
                         !reader.IsEmptyElement)
                {
                    //How can key re-empact Identity
                    identity = new X509CertificateEndpointIdentity(new System.Security.Cryptography.X509Certificates.X509Certificate2("powershell.pfx", "mono"));
                    break;
                }
                else
                {
                    var headerName      = reader.LocalName;
                    var headerNamespace = reader.NamespaceURI;
                    reader.MoveToContent();
                    reader.ReadStartElement();
                    var obj = reader.ReadElementContentAs(GetTypeFromLocalName(reader.LocalName), new XmlNamespaceManager(reader.NameTable));
                    header.Add(AddressHeader.CreateAddressHeader(headerName, headerNamespace, obj));
                    reader.MoveToContent();
                    reader.ReadEndElement();
                }
            }
            return(identity == null ? new EndpointAddress(uri, header.ToArray()) : new EndpointAddress(uri, identity, header.ToArray()));
        }
Пример #12
0
 protected override void ValidateCreateChannelParameters(EndpointAddress remoteAddress, Uri via)
 {
     if (remoteAddress.Identity != null)
     {
         X509CertificateEndpointIdentity identity = remoteAddress.Identity as X509CertificateEndpointIdentity;
         if ((identity != null) && (identity.Certificates.Count > 1))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("remoteAddress", System.ServiceModel.SR.GetString("HttpsIdentityMultipleCerts", new object[] { remoteAddress.Uri }));
         }
         EndpointIdentity identity2 = remoteAddress.Identity;
         bool             flag      = (((identity != null) || ClaimTypes.Spn.Equals(identity2.IdentityClaim.ClaimType)) || ClaimTypes.Upn.Equals(identity2.IdentityClaim.ClaimType)) || ClaimTypes.Dns.Equals(identity2.IdentityClaim.ClaimType);
         if (!AuthenticationSchemesHelper.IsWindowsAuth(base.AuthenticationScheme) && !flag)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("remoteAddress", System.ServiceModel.SR.GetString("HttpsExplicitIdentity"));
         }
     }
     base.ValidateCreateChannelParameters(remoteAddress, via);
 }
        public void CreateX509CertificateIdentity()
        {
            X509CertificateEndpointIdentity identity =
                EndpointIdentity.CreateX509CertificateIdentity(cert)
                as X509CertificateEndpointIdentity;
            Claim c = identity.IdentityClaim;

            Assert.IsNotNull(c, "#1");
            Assert.AreEqual(ClaimTypes.Thumbprint, c.ClaimType, "#2");
            DataContractSerializer ser = new DataContractSerializer(c.GetType());
            StringWriter           sw  = new StringWriter();
            XmlWriter xw = XmlWriter.Create(sw);

            ser.WriteObject(xw, c);
            xw.Close();
            string xml = @"<?xml version=""1.0"" encoding=""utf-16""?><Claim xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.xmlsoap.org/ws/2005/05/identity""><ClaimType>http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint</ClaimType><Resource xmlns:d2p1=""http://www.w3.org/2001/XMLSchema"" i:type=""d2p1:base64Binary"">GQ3YHlGQhDF1bvMixHliX4uLjlY=</Resource><Right>http://schemas.xmlsoap.org/ws/2005/05/identity/right/possessproperty</Right></Claim>";

            Assert.AreEqual(C14N(xml), C14N(sw.ToString()), "#3");
            Assert.AreEqual("identity(" + c + ")", identity.ToString(), "#4");
        }
        /// <summary>
        /// Finds the leaf certificate on an X509EndpointIdentity
        /// </summary>
        /// <param name="epi">The epi.</param>
        /// <returns>The target site X509 certificate</returns>
        public static X509Certificate2 GetEndCertificate(this X509CertificateEndpointIdentity epi)
        {
            Contract.Requires(epi != null);
            Contract.Requires(epi.IdentityClaim != null);
            Contract.Requires(epi.IdentityClaim.Resource != null);
            Contract.Ensures(Contract.Result <X509Certificate2>() != null);


            string primaryHash64 = Convert.ToBase64String((byte[])epi.IdentityClaim.Resource);

            foreach (var certificate in epi.Certificates)
            {
                string certHash64 = Convert.ToBase64String(certificate.GetCertHash());
                if (string.Equals(primaryHash64, certHash64, StringComparison.OrdinalIgnoreCase))
                {
                    return(certificate);
                }
            }

            throw new InvalidOperationException("No leaf certificate found");
        }
Пример #15
0
        protected override void ValidateCreateChannelParameters(EndpointAddress remoteAddress, Uri via)
        {
            if (remoteAddress.Identity != null)
            {
                X509CertificateEndpointIdentity certificateIdentity =
                    remoteAddress.Identity as X509CertificateEndpointIdentity;
                if (certificateIdentity != null)
                {
                    if (certificateIdentity.Certificates.Count > 1)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(nameof(remoteAddress), SR.Format(
                                                                                         SR.HttpsIdentityMultipleCerts, remoteAddress.Uri));
                    }
                }

                EndpointIdentity identity      = remoteAddress.Identity;
                bool             validIdentity = (certificateIdentity != null) ||
                                                 ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType) ||
                                                 ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType) ||
                                                 ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType);

                if (!IsWindowsAuth(AuthenticationScheme) &&
                    !validIdentity)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(nameof(remoteAddress), SR.HttpsExplicitIdentity);
                }
            }

            if (string.Compare(via.Scheme, "wss", StringComparison.OrdinalIgnoreCase) != 0)
            {
                ValidateScheme(via);
            }

            if (MessageVersion.Addressing == AddressingVersion.None && remoteAddress.Uri != via)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateToMustEqualViaException(remoteAddress.Uri, via));
            }
        }
Пример #16
0
        /// <summary>
        /// This method returns the configuration for the token issuance request. The configuration
        /// is represented by the Scope class. In our case, we are only capable of issuing a token to a
        /// single RP identity represented by CN=localhost.
        /// </summary>
        /// <param name="principal">The caller's principal</param>
        /// <param name="request">The incoming RST</param>
        /// <returns>The configuration for the token issuance request.</returns>
        protected override Scope GetScope(IClaimsPrincipal principal, RequestSecurityToken request)
        {
            // Validate the AppliesTo on the incoming request
            ValidateAppliesTo(request.AppliesTo);

            // Normally the STS will have a trust relationship with the RP and can look up a trusted encrypting certficate
            // using the AppliesTo endpoint. This is necessary to ensure that only the RP will be able to read the claims.
            //
            // In this sample the certificate of the AppliesTo Identity is used to encrypt the contents, so there is no
            // validation of any trust relationship with the RP. Since the certificate is not validated,
            // a malicious client can provide a known certificate allowing it to read the returned claims.
            // For this reason, THIS APPROACH SHOULD NOT BE USED if the claims should be kept private. It may be reasonable,
            // though, if the STS is simply verifying public information such as the client's email address.

            // Get RP certificate
            X509CertificateEndpointIdentity appliesToIdentity = (X509CertificateEndpointIdentity)request.AppliesTo.Identity;

            X509EncryptingCredentials encryptingCredentials = new X509EncryptingCredentials(appliesToIdentity.Certificates[0]);
            // Create the scope using the request AppliesTo address and the STS signing certificate
            Scope scope = new Scope(request.AppliesTo.Uri.AbsoluteUri, SecurityTokenServiceConfiguration.SigningCredentials, encryptingCredentials);

            return(scope);
        }
Пример #17
0
    public static async Task ServerCertificateValidationUsingIdentity_EchoString()
    {
        EndpointAddress              endpointAddress    = null;
        X509Certificate2             serviceCertificate = null;
        string                       testString         = "Hello";
        ChannelFactory <IWcfService> factory            = null;
        IWcfService                  serviceProxy       = null;

        try
        {
            // *** SETUP *** \\
            CustomBinding binding = new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8), new HttpsTransportBindingElement());

            serviceCertificate = await ServiceUtilHelper.GetServiceMacineCertFromServerAsync();

            var identity = new X509CertificateEndpointIdentity(serviceCertificate);
            endpointAddress = new EndpointAddress(new Uri(Endpoints.Https_DefaultBinding_Address_Text), identity);

            factory      = new ChannelFactory <IWcfService>(binding, endpointAddress);
            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            string result = serviceProxy.Echo(testString);

            // *** VALIDATE *** \\
            Assert.Equal(testString, result);

            // *** CLEANUP *** \\
            ((ICommunicationObject)serviceProxy).Close();
            factory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
Пример #18
0
        public CardspacePolicyInfo(CardSpacePolicyElement[] policyElements)
        {
            if (policyElements.Length > 0)
            {
                System.IO.TextReader tr              = new System.IO.StringReader(policyElements[0].Target.OuterXml.ToString());
                XmlTextReader        xmltr           = new XmlTextReader(tr);
                XmlDictionaryReader  xmldr           = XmlDictionaryReader.CreateDictionaryReader(xmltr);
                EndpointAddress      endpointAddress = EndpointAddress.ReadFrom(xmldr);
                _relyingParty = endpointAddress.Uri.Host;

                X509CertificateEndpointIdentity endpointIdentity = (X509CertificateEndpointIdentity)endpointAddress.Identity;
                _certificate = endpointIdentity.Certificates[0].GetCertHashString();


                if (policyElements[0].Issuer != null)
                {
                    tr                = new System.IO.StringReader(policyElements[0].Issuer.OuterXml.ToString());
                    xmltr             = new XmlTextReader(tr);
                    xmldr             = XmlDictionaryReader.CreateDictionaryReader(xmltr);
                    endpointAddress   = EndpointAddress.ReadFrom(xmldr);
                    _identityProvider = endpointAddress.Uri.ToString();
                }
            }
        }
Пример #19
0
        public CardspacePolicyInfo(CardSpacePolicyElement[] policyElements)
        {
            _requiredClaims = new List <string>();

            if (policyElements.Length > 0)
            {
                System.IO.TextReader tr              = new System.IO.StringReader(policyElements[0].Target.OuterXml.ToString());
                XmlTextReader        xmltr           = new XmlTextReader(tr);
                XmlDictionaryReader  xmldr           = XmlDictionaryReader.CreateDictionaryReader(xmltr);
                EndpointAddress      endpointAddress = EndpointAddress.ReadFrom(xmldr);
                _relyingParty = endpointAddress.Uri.Host;
                foreach (XmlElement xmlPolicyElement in policyElements[0].Parameters)
                {
                    if (xmlPolicyElement.Name == "t:Claims")
                    {
                        XmlNode claimsNode = xmlPolicyElement;
                        foreach (XmlNode claimNode in claimsNode.ChildNodes)
                        {
                            _requiredClaims.Add(claimNode.Attributes["Uri"].Value);
                        }
                    }
                }
                X509CertificateEndpointIdentity endpointIdentity = (X509CertificateEndpointIdentity)endpointAddress.Identity;
                _certificate = endpointIdentity.Certificates[0].GetCertHashString();


                if (policyElements[0].Issuer != null)
                {
                    tr                = new System.IO.StringReader(policyElements[0].Issuer.OuterXml.ToString());
                    xmltr             = new XmlTextReader(tr);
                    xmldr             = XmlDictionaryReader.CreateDictionaryReader(xmltr);
                    endpointAddress   = EndpointAddress.ReadFrom(xmldr);
                    _identityProvider = endpointAddress.Uri.ToString();
                }
            }
        }