Beispiel #1
0
 public abstract bool TryGetIdentity(EndpointAddress reference, out EndpointIdentity identity);
Beispiel #2
0
        /// <summary>
        /// Get endpoint address from uri
        /// </summary>
        /// <param name="uri">target service uri</param>
        /// <returns>endpoint address of target service</returns>
        private static EndpointAddress GetEndpoint(Uri uri)
        {
            EndpointIdentity identity = EndpointIdentity.CreateSpnIdentity("HOST/" + uri.Host);

            return(new EndpointAddress(uri, identity));
        }
Beispiel #3
0
 public override bool TryGetIdentity(EndpointAddress reference, out EndpointIdentity identity)
 {
     throw new Exception("The method or operation is not implemented.");
 }
Beispiel #4
0
            public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext)
            {
                EventTraceActivity eventTraceActivity = null;

                if (identity == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identity");
                }

                if (authContext == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authContext");
                }


                if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled)
                {
                    eventTraceActivity = EventTraceActivityHelper.TryExtractActivity((OperationContext.Current != null) ? OperationContext.Current.IncomingMessage : null);
                }

                for (int i = 0; i < authContext.ClaimSets.Count; ++i)
                {
                    ClaimSet claimSet = authContext.ClaimSets[i];
                    if (claimSet.ContainsClaim(identity.IdentityClaim))
                    {
                        SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, identity.IdentityClaim, this.GetType());
                        return(true);
                    }

                    // try Claim equivalence
                    string expectedSpn = null;
                    if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
                    {
                        expectedSpn = string.Format(CultureInfo.InvariantCulture, "host/{0}", (string)identity.IdentityClaim.Resource);
                        Claim claim = CheckDnsEquivalence(claimSet, expectedSpn);
                        if (claim != null)
                        {
                            SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, this.GetType());
                            return(true);
                        }
                    }

                    // Allow a Sid claim to support UPN, and SPN identities

                    // SID claims not available yet
                    //SecurityIdentifier identitySid = null;
                    //if (ClaimTypes.Sid.Equals(identity.IdentityClaim.ClaimType))
                    //{
                    //    throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Sid");
                    //}
                    //else if (ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType))
                    //{
                    //    throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Upn");
                    //}
                    //else if (ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType))
                    //{
                    //    throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Spn");
                    //}
                    //else if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
                    //{
                    //    throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Dns");
                    //}
                    //if (identitySid != null)
                    //{
                    //    Claim claim = CheckSidEquivalence(identitySid, claimSet);
                    //    if (claim != null)
                    //    {
                    //        SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, this.GetType());
                    //        return true;
                    //    }
                    //}
                }
                SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authContext, this.GetType());
                if (TD.SecurityIdentityVerificationFailureIsEnabled())
                {
                    TD.SecurityIdentityVerificationFailure(eventTraceActivity);
                }

                return(false);
            }
Beispiel #5
0
        static void Main(string[] args)
        {
            NetTcpBinding binding = new NetTcpBinding();
            string        address = "net.tcp://localhost:9999/DomainControllerClient";

            binding.Security.Mode = SecurityMode.Transport;
            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
            binding.Security.Transport.ProtectionLevel      = System.Net.Security.ProtectionLevel.EncryptAndSign;
            EndpointAddress endpointAddressDC = new EndpointAddress(new Uri(address), EndpointIdentity.CreateUpnIdentity("DomainController"));

            SHA256            sha256Hash = SHA256.Create();
            ChallengeResponse cr         = new ChallengeResponse();
            ClientSessionData sessionData;

            string username = Environment.UserName;
            string password;

            Console.WriteLine("Logging in as " + username);

            //user account password
            Console.WriteLine("Enter password:"******"Enter service name: ");
            string serviceName = Console.ReadLine();


            byte[] pwBytes = Encoding.ASCII.GetBytes(password);
            byte[] secret;

            try
            {
                using (DCProxy proxy = new DCProxy(binding, endpointAddressDC))
                {
                    secret = sha256Hash.ComputeHash(pwBytes);

                    short  salt     = proxy.StartClientAuthentication(serviceName);
                    byte[] response = cr.Encrypt(secret, salt);

                    sessionData = proxy.SendResponse(response);
                    Console.WriteLine($"Found service address: {sessionData.ServiceAddress}");
                    Console.WriteLine("--------------------------------------------------------------------------------");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Press return to exit.");
                Console.ReadLine();
                return;
            }

            NetTcpBinding bindingService = new NetTcpBinding();

            try
            {
                using (ServiceProxy proxy = new ServiceProxy(bindingService, sessionData.ServiceAddress))
                {
                    char   c;
                    string key;
                    byte[] encryptedKey;
                    string value;
                    byte[] encryptedValue;
                    byte[] sessionKey = _3DESAlgorithm.Decrypt(sessionData.SessionKey, secret);

                    do
                    {
                        Console.WriteLine();
                        Console.WriteLine("Choose an action:");
                        Console.WriteLine("\t- 'w' to write");
                        Console.WriteLine("\t- 'r' to read");
                        Console.WriteLine("\t- 'x' to exit");
                        c = char.ToLower(Console.ReadKey().KeyChar);
                        Console.WriteLine();

                        switch (c)
                        {
                        case 'r':
                            Console.WriteLine("Key of value to read:");
                            key = Console.ReadLine();

                            Console.WriteLine("Encrypting and sending READ request...");
                            encryptedKey   = _3DESAlgorithm.Encrypt(key, sessionKey);
                            encryptedValue = proxy.Read(encryptedKey);
                            if (encryptedValue == null)
                            {
                                Console.WriteLine("Encryption error...");
                                break;
                            }
                            value = Encoding.ASCII.GetString(_3DESAlgorithm.Decrypt(encryptedValue, sessionKey));
                            Console.WriteLine("Received value: " + value);
                            break;

                        case 'w':
                            Console.WriteLine("Key of value to write:");
                            key = Console.ReadLine();
                            Console.WriteLine("Value to write:");
                            value = Console.ReadLine();

                            Console.WriteLine("Encrypting and sending WRITE request...");
                            encryptedKey   = _3DESAlgorithm.Encrypt(key, sessionKey);
                            encryptedValue = _3DESAlgorithm.Encrypt(value, sessionKey);
                            if (encryptedValue == null || encryptedKey == null)
                            {
                                Console.WriteLine("Encryption error...");
                                break;
                            }

                            if (proxy.Write(encryptedKey, encryptedValue))
                            {
                                Console.WriteLine("Value written successfully.");
                            }

                            break;

                        default:
                            break;
                        }
                        Console.WriteLine("--------------------------------------------------------------------------------");
                    } while (c != 'x');
                }
            }
            catch (CommunicationException e)
            {
                Console.WriteLine($"Communication error. Please restart. ");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error: {e.Message}");
                Console.WriteLine("Please restart.");
                Console.ReadLine();
            }
        }
Beispiel #6
0
        //</snippet1>

        //<snippet2>
        public override bool TryGetIdentity(EndpointAddress reference, out EndpointIdentity identity)
        {
            return(IdentityVerifier.CreateDefault().TryGetIdentity(reference, out identity));
        }
Beispiel #7
0
        internal static void InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost)
        {
            if (serviceHost.ImplementedContracts != null && serviceHost.ImplementedContracts.Count > 0)
            {
                EnsureThereAreApplicationEndpoints(description);
            }
            ValidateDescription(description, serviceHost);

            Dictionary <ListenUriInfo, StuffPerListenUriInfo> stuffPerListenUriInfo
                = new Dictionary <ListenUriInfo, StuffPerListenUriInfo>();
            Dictionary <EndpointAddress, Collection <EndpointInfo> > endpointInfosPerEndpointAddress
                = new Dictionary <EndpointAddress, Collection <EndpointInfo> >();

            // Ensure ListenUri and group endpoints per ListenUri
            for (int i = 0; i < description.Endpoints.Count; i++)
            {
                ServiceEndpoint endpoint = description.Endpoints[i];

                ListenUriInfo listenUriInfo = GetListenUriInfoForEndpoint(serviceHost, endpoint);
                if (!stuffPerListenUriInfo.ContainsKey(listenUriInfo))
                {
                    stuffPerListenUriInfo.Add(listenUriInfo, new StuffPerListenUriInfo());
                }
                stuffPerListenUriInfo[listenUriInfo].Endpoints.Add(endpoint);
            }

            foreach (KeyValuePair <ListenUriInfo, StuffPerListenUriInfo> stuff in stuffPerListenUriInfo)
            {
                Uri listenUri = stuff.Key.ListenUri;
                BindingParameterCollection parameters = stuff.Value.Parameters;
                Binding          binding  = stuff.Value.Endpoints[0].Binding;
                EndpointIdentity identity = stuff.Value.Endpoints[0].Address.Identity;
                // same EndpointAddressTable instance must be shared between channelDispatcher and parameters
                //ThreadSafeMessageFilterTable<EndpointAddress> endpointAddressTable = new ThreadSafeMessageFilterTable<EndpointAddress>();
                //parameters.Add(endpointAddressTable);

                // add service-level binding parameters
                foreach (IServiceBehavior behavior in description.Behaviors)
                {
                    behavior.AddBindingParameters(description, serviceHost, stuff.Value.Endpoints, parameters);
                }
                for (int i = 0; i < stuff.Value.Endpoints.Count; i++)
                {
                    ServiceEndpoint endpoint  = stuff.Value.Endpoints[i];
                    string          viaString = listenUri.AbsoluteUri;

                    // ensure all endpoints with this ListenUriInfo have same binding
                    if (endpoint.Binding != binding)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ABindingInstanceHasAlreadyBeenAssociatedTo1, viaString)));
                    }

                    // ensure all endpoints with this ListenUriInfo have same identity
                    if (!object.Equals(endpoint.Address.Identity, identity))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                                                                                      SR.Format(SR.SFxWhenMultipleEndpointsShareAListenUriTheyMustHaveSameIdentity, viaString)));
                    }

                    // add binding parameters (endpoint scope and below)
                    AddBindingParametersForSecurityContractInformation(endpoint, parameters);
                    AddBindingParameters(endpoint, parameters);
                }

                // build IChannelListener and ChannelDispatcher
                //IChannelListener listener;
                //Type channelType = BuildChannelListener(stuff.Value,
                //                                             serviceHost,
                //                                             listenUri,
                //                                             listenUriMode,
                //                                             out listener);

                XmlQualifiedName  bindingQname      = new XmlQualifiedName(binding.Name, binding.Namespace);
                ChannelDispatcher channelDispatcher = new ChannelDispatcher(listenUri, binding, bindingQname.ToString(), binding);
                //channelDispatcher.SetEndpointAddressTable(endpointAddressTable);
                stuff.Value.ChannelDispatcher = channelDispatcher;

                for (int i = 0; i < stuff.Value.Endpoints.Count; i++)
                {
                    ServiceEndpoint endpoint  = stuff.Value.Endpoints[i];
                    string          viaString = listenUri.AbsoluteUri;

                    //EndpointFilterProvider provider = new EndpointFilterProvider();
                    EndpointDispatcher dispatcher = BuildEndpointDispatcher(description, endpoint);

                    if (!endpointInfosPerEndpointAddress.ContainsKey(endpoint.Address))
                    {
                        endpointInfosPerEndpointAddress.Add(endpoint.Address, new Collection <EndpointInfo>());
                    }
                    endpointInfosPerEndpointAddress[endpoint.Address].Add(new EndpointInfo(endpoint, dispatcher, /*provider*/ null));

                    channelDispatcher.Endpoints.Add(dispatcher);
                } // end foreach "endpoint"

                serviceHost.ChannelDispatchers.Add(channelDispatcher);
            } // end foreach "ListenUri/ChannelDispatcher" group

            // run service behaviors
            for (int i = 0; i < description.Behaviors.Count; i++)
            {
                IServiceBehavior serviceBehavior = description.Behaviors[i];
                serviceBehavior.ApplyDispatchBehavior(description, serviceHost);
            }

            foreach (KeyValuePair <ListenUriInfo, StuffPerListenUriInfo> stuff in stuffPerListenUriInfo)
            {
                for (int i = 0; i < stuff.Value.Endpoints.Count; i++)
                {
                    ServiceEndpoint endpoint = stuff.Value.Endpoints[i];
                    // rediscover which dispatcher goes with this endpoint
                    Collection <EndpointInfo> infos = endpointInfosPerEndpointAddress[endpoint.Address];
                    EndpointInfo info = null;
                    foreach (EndpointInfo ei in infos)
                    {
                        if (ei.Endpoint == endpoint)
                        {
                            info = ei;
                            break;
                        }
                    }
                    EndpointDispatcher dispatcher = info.EndpointDispatcher;
                    // run contract behaviors
                    for (int k = 0; k < endpoint.Contract.Behaviors.Count; k++)
                    {
                        IContractBehavior behavior = endpoint.Contract.Behaviors[k];
                        behavior.ApplyDispatchBehavior(endpoint.Contract, endpoint, dispatcher.DispatchRuntime);
                    }
                    // run endpoint behaviors
                    ApplyBindingInformationFromEndpointToDispatcher(endpoint, dispatcher);
                    for (int j = 0; j < endpoint.Behaviors.Count; j++)
                    {
                        IEndpointBehavior eb = endpoint.Behaviors[j];
                        eb.ApplyDispatchBehavior(endpoint, dispatcher);
                    }
                    // run operation behaviors
                    BindOperations(endpoint.Contract, null, dispatcher.DispatchRuntime);
                }
            }

            EnsureRequiredRuntimeProperties(endpointInfosPerEndpointAddress);

            // Warn about obvious demux conflicts
            foreach (Collection <EndpointInfo> endpointInfos in endpointInfosPerEndpointAddress.Values)
            {
                // all elements of endpointInfos share the same Address (and thus EndpointListener.AddressFilter)
                if (endpointInfos.Count > 1)
                {
                    for (int i = 0; i < endpointInfos.Count; i++)
                    {
                        for (int j = i + 1; j < endpointInfos.Count; j++)
                        {
                            // if not same ListenUri, won't conflict
                            // if not same ChannelType, may not conflict (some transports demux based on this)
                            // if they share a ChannelDispatcher, this means same ListenUri and same ChannelType
                            if (endpointInfos[i].EndpointDispatcher.ChannelDispatcher ==
                                endpointInfos[j].EndpointDispatcher.ChannelDispatcher)
                            {
                                EndpointFilterProvider iProvider = endpointInfos[i].FilterProvider;
                                EndpointFilterProvider jProvider = endpointInfos[j].FilterProvider;
                                // if not default EndpointFilterProvider, we won't try to throw, you're on your own
                                string commonAction;
                                if (iProvider != null && jProvider != null &&
                                    HaveCommonInitiatingActions(iProvider, jProvider, out commonAction))
                                {
                                    // you will definitely get a MultipleFiltersMatchedException at runtime,
                                    // so let's go ahead and throw now
                                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                              new InvalidOperationException(
                                                  SR.Format(SR.SFxDuplicateInitiatingActionAtSameVia, endpointInfos[i].Endpoint.ListenUri, commonAction)));
                                }
                            }
                        }
                    }
                }
            }
        }
Beispiel #8
0
 public abstract bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext);
        private void DoMex()
        {
            string           str;
            string           str2;
            string           str3;
            string           str4;
            string           str5;
            string           str6;
            string           str7;
            string           str8;
            string           str9      = null;
            string           str10     = null;
            string           str11     = null;
            string           str12     = null;
            string           str13     = null;
            string           str14     = null;
            string           str15     = null;
            EndpointIdentity identity  = null;
            EndpointIdentity identity2 = null;
            WsdlImporter     importer;

            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Contract, out str4);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.ContractNamespace, out str5);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.BindingNamespace, out str7);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Binding, out str6);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexAddress, out str);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexBinding, out str2);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexBindingConfiguration, out str3);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Address, out str8);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.SpnIdentity, out str9);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.UpnIdentity, out str10);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.DnsIdentity, out str11);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexSpnIdentity, out str12);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexUpnIdentity, out str13);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexDnsIdentity, out str14);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Serializer, out str15);
            if (string.IsNullOrEmpty(str))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerMexAddressNotSpecified")));
            }
            if (!string.IsNullOrEmpty(str12))
            {
                if (!string.IsNullOrEmpty(str13) || !string.IsNullOrEmpty(str14))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorrectServerIdentityForMex")));
                }
                identity2 = EndpointIdentity.CreateSpnIdentity(str12);
            }
            else if (!string.IsNullOrEmpty(str13))
            {
                if (!string.IsNullOrEmpty(str12) || !string.IsNullOrEmpty(str14))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorrectServerIdentityForMex")));
                }
                identity2 = EndpointIdentity.CreateUpnIdentity(str13);
            }
            else if (!string.IsNullOrEmpty(str14))
            {
                if (!string.IsNullOrEmpty(str12) || !string.IsNullOrEmpty(str13))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorrectServerIdentityForMex")));
                }
                identity2 = EndpointIdentity.CreateDnsIdentity(str14);
            }
            else
            {
                identity2 = null;
            }
            if (string.IsNullOrEmpty(str8))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerAddressNotSpecified")));
            }
            if (string.IsNullOrEmpty(str4))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerContractNotSpecified")));
            }
            if (string.IsNullOrEmpty(str6))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerBindingNotSpecified")));
            }
            if (string.IsNullOrEmpty(str7))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerBindingNamespacetNotSpecified")));
            }
            if (!string.IsNullOrEmpty(str9))
            {
                if (!string.IsNullOrEmpty(str10) || !string.IsNullOrEmpty(str11))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorrectServerIdentity")));
                }
                identity = EndpointIdentity.CreateSpnIdentity(str9);
            }
            else if (!string.IsNullOrEmpty(str10))
            {
                if (!string.IsNullOrEmpty(str9) || !string.IsNullOrEmpty(str11))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorrectServerIdentity")));
                }
                identity = EndpointIdentity.CreateUpnIdentity(str10);
            }
            else if (!string.IsNullOrEmpty(str11))
            {
                if (!string.IsNullOrEmpty(str9) || !string.IsNullOrEmpty(str10))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorrectServerIdentity")));
                }
                identity = EndpointIdentity.CreateDnsIdentity(str11);
            }
            else
            {
                identity = null;
            }
            MetadataExchangeClient client  = null;
            EndpointAddress        address = new EndpointAddress(new Uri(str), identity2, new AddressHeader[0]);

            if (!string.IsNullOrEmpty(str2))
            {
                System.ServiceModel.Channels.Binding mexBinding = null;
                try
                {
                    mexBinding = ConfigLoader.LookupBinding(str2, str3);
                }
                catch (ConfigurationErrorsException)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MexBindingNotFoundInConfig", new object[] { str2 })));
                }
                if (mexBinding == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MexBindingNotFoundInConfig", new object[] { str2 })));
                }
                client = new MetadataExchangeClient(mexBinding);
            }
            else
            {
                if (!string.IsNullOrEmpty(str3))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerMexBindingSectionNameNotSpecified")));
                }
                client = new MetadataExchangeClient(address);
            }
            if (identity2 != null)
            {
                client.SoapCredentials.Windows.AllowNtlm = false;
            }
            bool flag = false;

            if (!string.IsNullOrEmpty(str15))
            {
                if (("xml" != str15) && ("datacontract" != str15))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorectSerializer")));
                }
                if ("xml" == str15)
                {
                    this.useXmlSerializer = true;
                }
                else
                {
                    flag = true;
                }
            }
            ServiceEndpoint           endpoint = null;
            ServiceEndpointCollection serviceEndpointsRetrieved = null;

            try
            {
                MetadataSet metadata = client.GetMetadata(address);
                if (this.useXmlSerializer)
                {
                    importer = this.CreateXmlSerializerImporter(metadata);
                }
                else if (flag)
                {
                    importer = this.CreateDataContractSerializerImporter(metadata);
                }
                else
                {
                    importer = new WsdlImporter(metadata);
                }
                serviceEndpointsRetrieved = this.ImportWsdlPortType(new XmlQualifiedName(str4, str5), importer);
                ComPlusMexChannelBuilderMexCompleteTrace.Trace(TraceEventType.Verbose, 0x50024, "TraceCodeComIntegrationMexMonikerMetadataExchangeComplete", serviceEndpointsRetrieved);
            }
            catch (Exception exception)
            {
                if (Fx.IsFatal(exception))
                {
                    throw;
                }
                if (UriSchemeSupportsDisco(address.Uri))
                {
                    try
                    {
                        DiscoveryClientProtocol protocol = new DiscoveryClientProtocol {
                            UseDefaultCredentials = true,
                            AllowAutoRedirect     = true
                        };
                        protocol.DiscoverAny(address.Uri.AbsoluteUri);
                        protocol.ResolveAll();
                        MetadataSet metadataSet = new MetadataSet();
                        foreach (object obj2 in protocol.Documents.Values)
                        {
                            this.AddDocumentToSet(metadataSet, obj2);
                        }
                        if (this.useXmlSerializer)
                        {
                            importer = this.CreateXmlSerializerImporter(metadataSet);
                        }
                        else if (flag)
                        {
                            importer = this.CreateDataContractSerializerImporter(metadataSet);
                        }
                        else
                        {
                            importer = new WsdlImporter(metadataSet);
                        }
                        serviceEndpointsRetrieved = this.ImportWsdlPortType(new XmlQualifiedName(str4, str5), importer);
                        ComPlusMexChannelBuilderMexCompleteTrace.Trace(TraceEventType.Verbose, 0x50024, "TraceCodeComIntegrationMexMonikerMetadataExchangeComplete", serviceEndpointsRetrieved);
                        goto Label_0634;
                    }
                    catch (Exception exception2)
                    {
                        if (Fx.IsFatal(exception2))
                        {
                            throw;
                        }
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerFailedToDoMexRetrieve", new object[] { exception2.Message })));
                    }
                }
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerFailedToDoMexRetrieve", new object[] { exception.Message })));
            }
Label_0634:
            if (serviceEndpointsRetrieved.Count == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerContractNotFoundInRetreivedMex")));
            }
            foreach (ServiceEndpoint endpoint2 in serviceEndpointsRetrieved)
            {
                System.ServiceModel.Channels.Binding binding = endpoint2.Binding;
                if ((binding.Name == str6) && (binding.Namespace == str7))
                {
                    endpoint = endpoint2;
                    break;
                }
            }
            if (endpoint == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerNoneOfTheBindingMatchedTheSpecifiedBinding")));
            }
            this.contractDescription = endpoint.Contract;
            this.serviceEndpoint     = new ServiceEndpoint(this.contractDescription, endpoint.Binding, new EndpointAddress(new Uri(str8), identity, null));
            ComPlusMexChannelBuilderTrace.Trace(TraceEventType.Verbose, 0x50025, "TraceCodeComIntegrationMexChannelBuilderLoaded", endpoint.Contract, endpoint.Binding, str8);
        }
Beispiel #10
0
        /// <summary>
        /// Sends a CyberSource transaction request.
        /// </summary>
        /// <param name="config">Configuration object to use.</param>
        /// <param name="requestMessage">RequestMessage object containing the request.</param>
        /// <returns>ReplyMessage containing the reply.</returns>
        public static ReplyMessage RunTransaction(
            Configuration config, RequestMessage requestMessage)
        {
            Logger logger = null;
            TransactionProcessorClient proc = null;

            try
            {
                DetermineEffectiveMerchantID(ref config, requestMessage);
                SetVersionInformation(requestMessage);
                logger = PrepareLog(config);
                SetConnectionLimit(config);


                CustomBinding currentBinding = getWCFCustomBinding(config);


                //Setup endpoint Address with dns identity
                AddressHeaderCollection headers         = new AddressHeaderCollection();
                EndpointAddress         endpointAddress = new EndpointAddress(new Uri(config.EffectiveServerURL), EndpointIdentity.CreateDnsIdentity(config.EffectivePassword), headers);

                //Get instance of service
                using (proc = new TransactionProcessorClient(currentBinding, endpointAddress))
                {
                    // set the timeout
                    TimeSpan timeOut = new TimeSpan(0, 0, 0, config.Timeout, 0);
                    currentBinding.SendTimeout = timeOut;

                    //add certificate credentials
                    string keyFilePath = Path.Combine(config.KeysDirectory, config.EffectiveKeyFilename);

                    X509Certificate2 merchantCert = null;
                    X509Certificate2 cybsCert     = null;
                    DateTime         dateFile     = File.GetLastWriteTime(keyFilePath);
                    if (config.CertificateCacheEnabled)
                    {
                        if (!merchantIdentities.ContainsKey(config.KeyAlias) || IsMerchantCertExpired(logger, config.KeyAlias, dateFile, merchantIdentities))
                        {
                            if (logger != null)
                            {
                                logger.LogInfo("Loading certificate for " + config.KeyAlias);
                            }

                            X509Certificate2Collection collection = new X509Certificate2Collection();
                            collection.Import(keyFilePath, config.EffectivePassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                            X509Certificate2 newMerchantCert = null;
                            X509Certificate2 newCybsCert     = null;

                            foreach (X509Certificate2 cert1 in collection)
                            {
                                if (cert1.Subject.Contains(config.KeyAlias))
                                {
                                    newMerchantCert = cert1;
                                }

                                if (cert1.Subject.Contains(CYBS_SUBJECT_NAME))
                                {
                                    newCybsCert = cert1;
                                }
                            }
                            CertificateEntry newCert = new CertificateEntry
                            {
                                ModifiedTime = dateFile,
                                CybsCert     = newCybsCert,
                                MerchantCert = newMerchantCert
                            };
                            merchantIdentities.AddOrUpdate(config.KeyAlias, newCert, (x, y) => newCert);
                        }
                        merchantCert = GetOrFindValidMerchantCertFromStore(config.KeyAlias, merchantIdentities);
                        if (config.UseSignedAndEncrypted)
                        {
                            cybsCert = GetOrFindValidCybsCertFromStore(config.KeyAlias, merchantIdentities);
                        }
                    }
                    else
                    {
                        // Changes for SHA2 certificates support
                        X509Certificate2Collection collection = new X509Certificate2Collection();
                        collection.Import(keyFilePath, config.EffectivePassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                        foreach (X509Certificate2 cert1 in collection)
                        {
                            if (cert1.Subject.Contains(config.KeyAlias))
                            {
                                merchantCert = cert1;
                                break;
                            }
                        }

                        if (config.UseSignedAndEncrypted)
                        {
                            foreach (X509Certificate2 cert2 in collection)
                            {
                                //Console.WriteLine(cert1.Subject);
                                if (cert2.Subject.Contains(CYBERSOURCE_PUBLIC_KEY))
                                {
                                    cybsCert = cert2;
                                    break;
                                }
                            }
                        }
                    }

                    if (merchantCert == null)
                    {
                        throw new ApplicationException(
                                  "CONFIGURATION OR CODE BUG:  merchant certificate is missing, check the p12 file");
                    }
                    //Set protection level to sign only
                    proc.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.Sign;
                    proc.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
                    proc.ClientCredentials.ClientCertificate.Certificate         = merchantCert;
                    proc.ClientCredentials.ServiceCertificate.DefaultCertificate = merchantCert;

                    if (config.UseSignedAndEncrypted)
                    {
                        if (cybsCert == null)
                        {
                            throw new ApplicationException(
                                      "CONFIGURATION OR CODE BUG:  cybs certificate is missing, check the p12 file");
                        }

                        //Set protection level to sign & encrypt only
                        proc.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;
                        proc.ClientCredentials.ServiceCertificate.DefaultCertificate = cybsCert;
                    }
                    // Changes for NGT-3035
                    XmlNode req = SerializeObjectToXmlNode(requestMessage);
                    if (logger != null)
                    {
                        logger.LogRequest(req, config.Demo);
                    }

                    ReplyMessage reply = proc.runTransaction(requestMessage);
                    XmlNode      rep   = SerializeObjectToXmlNode(reply);
                    if (logger != null)
                    {
                        logger.LogReply(rep, config.Demo);
                    }

                    return(reply);
                }
            }
            catch (Exception e)
            {
                if (logger != null)
                {
                    logger.LogException(e);
                }
                if (proc != null)
                {
                    proc.Abort();
                }
                throw;
            }
            finally
            {
                if (proc != null)
                {
                    proc.Close();
                }
            }
        }
 public static EndpointIdentity SpnIdentityFromUri(Uri uri)
 {
     return(EndpointIdentity.CreateSpnIdentity($"FIMService/{uri.Host}"));
 }
 public void RecordEndpointStatistics(EndpointIdentity identity, EndpointMetadata metadata, EndpointHealth stats)
 {
     _statsQueue.Add(Tuple.Create(identity, metadata, stats));
 }
Beispiel #13
0
        internal void InitializeClientProxy()
        {
            try
            {
                string uriString;
                string address = Serverport == 0 ? ServerAddress : ServerAddress + ":" + Serverport;

                if (BasicUser)
                {
                    if (Serverport == 80)
                    {
                        address = ServerAddress;
                    }
                    uriString = String.Format("https://{0}/ManagementServer/ConfigurationApiService.svc", address);
                }
                else
                {
                    uriString = String.Format("http://{0}/ManagementServer/ConfigurationApiService.svc", address);
                }

                ChannelFactory <IConfigurationService> channel = null;

                Uri uri = new UriBuilder(uriString).Uri;
                channel = new ChannelFactory <IConfigurationService>(GetBinding(BasicUser), new EndpointAddress(uri, EndpointIdentity.CreateSpnIdentity("host/localhost")));

                if (BasicUser)
                {
                    // Note the domain == [BASIC]
                    channel.Credentials.UserName.UserName = "******" + Username;
                    channel.Credentials.UserName.Password = Password;
                    channel.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication()
                    {
                        CertificateValidationMode = X509CertificateValidationMode.None,
                    };
                }
                else
                {
                    channel.Credentials.Windows.ClientCredential.UserName = Username;
                    channel.Credentials.Windows.ClientCredential.Password = Password;
                }
                _client = channel.CreateChannel();

                Connected = false;
            }
            catch (EndpointNotFoundException)
            {
            }
        }
 internal static void TraceIdentityVerificationFailure(EndpointIdentity identity, AuthorizationContext authContext, Type identityVerifier)
 {
 }
Beispiel #15
0
        /// <summary>
        /// Transport -- Certificate
        /// makecert -r -pe -ss My -sr LocalMachine -a sha1 -sky exchange -n cn=MyCA -sv "MyCAPrivate.pvk" MyCA.cer
        /// makecert -pe -ss My -sr LocalMachine -a sha1 -sky exchange -n cn=SignedClientCertificate -iv "MyCAPrivate.pvk" -ic "MyCA.cer"
        /// </summary>
        public static void ClientCertificateTransport()
        {
            string uri     = "https://localhost:44380/calcullator";
            string dnsName = "localhost";
            string ValidationCertificateThumbprint = "ca5c4e009132da4db17a5b8bbde6382eff4f3f99"; //"36da4d400065739d8c5463fa6fcdd40cf6cc08e0";


            ServiceHost host = new ServiceHost(typeof(Calculator), new Uri(uri));

            host.Description.Behaviors.Add(new ServiceMetadataBehavior()
            {
                HttpGetUrl = new Uri("http://localhost:44381/calcullator/metadata"), HttpGetEnabled = true
            });

            host.Credentials.ClientCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;
            //host.Credentials.ClientCertificate.Authentication.TrustedStoreLocation = StoreLocation.CurrentUser;
            host.Credentials.ClientCertificate.Authentication.CertificateValidationMode  = X509CertificateValidationMode.Custom;
            host.Credentials.ClientCertificate.Authentication.CustomCertificateValidator = new CustomX509CertificateValidator(ValidationCertificateThumbprint);

            WSHttpBinding binding = new WSHttpBinding();

            binding.Security.Mode = SecurityMode.Transport;
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;

            host.AddServiceEndpoint(typeof(ICalculator), binding, "");
            try
            {
                host.Opened += delegate { Console.WriteLine("host open"); };
                host.Open();

                EndpointAddress epAddress = new EndpointAddress(new Uri("https://localhost:44380/calcullator"), EndpointIdentity.CreateDnsIdentity(dnsName));

                ChannelFactory <ICalculator> factory = new ChannelFactory <ICalculator>(binding, epAddress);
                //validate the certificate of server
                ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) =>
                {
                    Console.WriteLine($"trust the server certificate: {certificate.Subject}");
                    return(true);
                };

                //set the Credentials
                factory.Credentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, ValidationCertificateThumbprint);

                var proxy = factory.CreateChannel();

                var result = proxy.Add(2, 3);

                Console.WriteLine(result);

                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Beispiel #16
0
            public override bool TryGetIdentity(EndpointAddress reference, out EndpointIdentity identity)
            {
                if (reference == null)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reference");
 
                identity = reference.Identity;
 
                if (identity == null)
                {
                    identity = this.TryCreateDnsIdentity(reference);
                }
 
                if (identity == null)
                {
                    SecurityTraceRecordHelper.TraceIdentityDeterminationFailure(reference, typeof(DefaultIdentityVerifier));
                    return false;
                }
                else
                {
                    SecurityTraceRecordHelper.TraceIdentityDeterminationSuccess(reference, identity, typeof(DefaultIdentityVerifier));
                    return true;
                }
            }
        public SPBaristaSearchServiceProxy()
        {
            var farm = SPFarm.Local;

            if (farm == null)
            {
                throw new InvalidOperationException("SharePoint farm not found.");
            }

            //Obtain the search (windows) service registered with the farm.
            var searchService =
                farm.Services.GetValue <Barista.SharePoint.ServiceManagement.BaristaSearchService>(
                    Barista.SharePoint.ServiceManagement.BaristaSearchService.NtServiceName);

            if (searchService == null)
            {
                throw new InvalidOperationException("The Barista Search Service is not registered with the farm. Please have your administrator run SetupBaristSearchService.ps1 referenced in the Barista installation documentation.");
            }

            //TODO: Make this multi-service application aware.
            var serviceAffinity = Utilities.GetFarmKeyValue("BaristaSearchServiceAffinity");
            SPServiceInstance searchServiceInstance;

            if (serviceAffinity.IsNullOrWhiteSpace())
            {
                searchServiceInstance = searchService.Instances.FirstOrDefault();

                if (searchServiceInstance == null)
                {
                    throw new InvalidOperationException("No Barista Search Service Instances are registered with the farm.");
                }
            }
            else
            {
                searchServiceInstance =
                    searchService.Instances.FirstOrDefault(ss => ss.Id.ToString() == serviceAffinity);

                if (searchServiceInstance == null)
                {
                    throw new InvalidOperationException("The current service application specifies a search service affinity, however, that search service instance cannot be located.");
                }
            }

            if (searchServiceInstance.Status != SPObjectStatus.Online)
            {
                throw new InvalidOperationException("A Barista Search Service Instance was located, however it is currently not online.");
            }

            if (searchServiceInstance.Server == null)
            {
                throw new InvalidOperationException("A Barista Search Service Instance was located, however, it is not currently associated with a server.");
            }

            var serverAddress = searchServiceInstance.Server.Address;

            m_serviceAddress = new Uri("http://" + serverAddress + ":8500/Barista/Search", UriKind.Absolute);

            if (searchService.ProcessIdentity != null && searchService.ProcessIdentity.ManagedAccount != null)
            {
                var propertyInfo = typeof(SPManagedAccount).GetProperty("UPNName",
                                                                        BindingFlags.Instance | BindingFlags.NonPublic);
                var upn = (string)propertyInfo.GetValue(searchService.ProcessIdentity.ManagedAccount, null);
                if (upn.IsNullOrWhiteSpace())
                {
                    throw new InvalidOperationException("Unable to determine service accout UPN for authentication.");
                }

                m_serviceIdentity = EndpointIdentity.CreateUpnIdentity(upn);
            }
            else
            {
                m_serviceIdentity =
                    EndpointIdentity.CreateDnsIdentity(SPServer.Local.Address.ToLowerInvariant() ==
                                                       serverAddress.ToLowerInvariant()
                                                       ? serverAddress
                                                       : "");
            }

            m_baristaSearchBinding = InitServiceBinding();
        }
Beispiel #18
0
 internal bool TryGetIdentity(EndpointAddress reference, Uri via, out EndpointIdentity identity)
 {
     AdjustAddress(ref reference, via);
     return this.TryGetIdentity(reference, out identity);
 }
Beispiel #19
0
        private void button登录_Click(object sender, EventArgs e)
        {
            try
            {
                if (textBox服务器.Text.Length == 0)
                {
                    MessageBox.Show("请输入登陆服务器IP!");
                    return;
                }

                //string server = string.IsNullOrEmpty(serverIP) ? textBox服务器.Text : serverIP;

                Program.EndpointAddress = new EndpointAddress(new Uri(string.Format("net.tcp://{0}:{1}/", textBox服务器.Text, Program.Port)), EndpointIdentity.CreateDnsIdentity("localhost"));
                //if (Program.Port == "808")
                //{

                //}
                //else
                //{
                //    Program.EndpointAddress = new EndpointAddress(new Uri(string.Format("net.tcp://{0}/", textBox服务器.Text)), EndpointIdentity.CreateDnsIdentity("localhost"));
                //}


                Program.AASServiceClient = new AASServiceReference.AASServiceClient(Program.callbackInstance, Program.NetTcpBinding, Program.EndpointAddress);

                //Program.EndpointAddress = new EndpointAddress(new Uri(string.Format("http://{0}/", server)), EndpointIdentity.CreateDnsIdentity("localhost"));
                //Program.AASServiceClient = new AASServiceReference.AASServiceClient(Program.callbackInstance, Program.WSDualHttpBinding, Program.EndpointAddress);


                Program.AASServiceClient.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
                Program.AASServiceClient.ClientCredentials.UserName.UserName = this.comboBox用户名.Text;
                Program.AASServiceClient.ClientCredentials.UserName.Password = this.textBox密码.Text + "\t" + this.MAC;


                Program.Current平台用户 = Program.AASServiceClient.QuerySingleUser(Program.Version)[0];
                Program.LoginInfoCache(textBox服务器.Text, this.comboBox用户名.Text, this.textBox密码.Text);

                ICommunicationObject ICommunicationObject1 = Program.AASServiceClient as ICommunicationObject;
                ICommunicationObject1.Faulted += ICommunicationObject1_Faulted;
                ICommunicationObject1.Closed  += ICommunicationObject1_Closed;

                if (this.checkBox记住密码.Checked)
                {
                    if (this.AppConfig.AppSettings.Settings.AllKeys.Contains(this.comboBox用户名.Text))
                    {
                        this.AppConfig.AppSettings.Settings[this.comboBox用户名.Text].Value = this.textBox服务器.Text + "," + Cryptor.MD5Encrypt(this.textBox密码.Text);
                    }
                    else
                    {
                        this.AppConfig.AppSettings.Settings.Add(this.comboBox用户名.Text, this.textBox服务器.Text + "," + Cryptor.MD5Encrypt(this.textBox密码.Text));
                    }
                    this.AppConfig.Save(ConfigurationSaveMode.Modified);
                    System.Configuration.ConfigurationManager.RefreshSection("appSettings");
                }
                else
                {
                    if (this.AppConfig.AppSettings.Settings.AllKeys.Contains(this.comboBox用户名.Text))
                    {
                        this.AppConfig.AppSettings.Settings.Remove(this.comboBox用户名.Text);
                        this.AppConfig.Save(ConfigurationSaveMode.Modified);
                        System.Configuration.ConfigurationManager.RefreshSection("appSettings");
                    }
                }

                Directory.CreateDirectory(Program.Current平台用户.用户名);

                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            catch (MessageSecurityException ex)
            {
                if (ex.InnerException == null)
                {
                    MessageBox.Show(ex.Message, "MessageSecurityException - InnerException");
                }
                else
                {
                    MessageBox.Show(ex.InnerException.Message, "MessageSecurityException");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().Name);
            }
        }
 public override bool TryGetIdentity(EndpointAddress reference, out EndpointIdentity identity)
 {
     identity = EndpointIdentity.CreateDnsIdentity(reference.Uri.Host);
     return(true);
 }
Beispiel #21
0
        /// <summary>
        /// Sends a CyberSource transaction request.
        /// </summary>
        /// <param name="config">Configuration object to use.</param>
        /// <param name="request">Hashtable containing the request fields and their values.</param>
        /// <returns>Hashtable containing the reply fields and their values.</returns>
        public static Hashtable RunTransaction(
            Configuration config, Hashtable request)
        {
            Logger logger = null;
            NVPTransactionProcessorClient proc = null;

            try
            {
                DetermineEffectiveMerchantID(ref config, request);
                SetVersionInformation(request);
                logger = PrepareLog(config);
                SetConnectionLimit(config);

                //Setup custom binding with HTTPS + Body Signing
                CustomBinding currentBinding = getWCFCustomBinding();

                //Setup endpoint Address with dns identity
                AddressHeaderCollection headers         = new AddressHeaderCollection();
                EndpointAddress         endpointAddress = new EndpointAddress(new Uri(config.EffectiveServerURL), EndpointIdentity.CreateDnsIdentity(config.EffectivePassword), headers);

                //Get instance of service
                using (proc = new NVPTransactionProcessorClient(currentBinding, endpointAddress))
                {
                    //Set protection level to sign only
                    proc.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.Sign;

                    // set the timeout
                    TimeSpan timeOut = new TimeSpan(0, 0, 0, config.Timeout, 0);
                    currentBinding.SendTimeout = timeOut;


                    string keyFilePath = Path.Combine(config.KeysDirectory, config.EffectiveKeyFilename);
                    proc.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(keyFilePath, config.EffectivePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                    proc.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;

                    // Changes for SHA2 certificates support
                    X509Certificate2Collection collection = new X509Certificate2Collection();
                    collection.Import(keyFilePath, config.EffectivePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                    foreach (X509Certificate2 cert1 in collection)
                    {
                        if (cert1.Subject.Contains(config.MerchantID))
                        {
                            proc.ClientCredentials.ClientCertificate.Certificate         = cert1;
                            proc.ClientCredentials.ServiceCertificate.DefaultCertificate = cert1;
                            break;
                        }
                    }

                    if (logger != null)
                    {
                        logger.LogRequest(request, config.Demo);
                    }

                    // send request now, converting the hashtable request into
                    // a string, and the string reply back into a hashtable.

                    string resp = proc.runTransaction(Hash2String(request));


                    Hashtable reply = String2Hash(resp);

                    if (logger != null)
                    {
                        logger.LogReply(reply, config.Demo);
                    }

                    return(reply);
                }
            }
            catch (Exception e)
            {
                if (logger != null)
                {
                    logger.LogException(e);
                }
                if (proc != null)
                {
                    proc.Abort();
                }
                throw;
            }
            finally
            {
                if (proc != null)
                {
                    proc.Close();
                }
            }
        }
Beispiel #22
0
 // Code to be added.
 public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext)
 {
     throw new Exception("The method or operation is not implemented.");
 }
        /// <summary>
        /// Calls the back end print identity service.
        /// </summary>
        /// <param name="address">The address of the back end service.</param>
        private static void CallService(string address)
        {
            ChannelFactory <IPrintIdentity> printServiceChannel = null;

            try
            {
                printServiceChannel = new ChannelFactory <IPrintIdentity>(new WindowsWSTrustBinding(),
                                                                          new EndpointAddress(new Uri(address),
                                                                                              EndpointIdentity.CreateDnsIdentity("localhost")));
                IPrintIdentity client = printServiceChannel.CreateChannel();
                (( IClientChannel )client).OperationTimeout = TimeSpan.MaxValue;

                Console.WriteLine("The access service 1 is accessing the print service.\n");
                client.Print();
            }
            finally
            {
                try
                {
                    if (printServiceChannel != null)
                    {
                        printServiceChannel.Close();
                    }
                }
                catch (CommunicationException)
                {
                }
                catch (TimeoutException)
                {
                }
            }
        }
Beispiel #24
0
        /// <summary>
        /// Sends a CyberSource transaction request.
        /// </summary>
        /// <param name="config">Configuration object to use.</param>
        /// <param name="requestMessage">RequestMessage object containing the request.</param>
        /// <returns>ReplyMessage containing the reply.</returns>
        public static ReplyMessage RunTransaction(
            Configuration config, RequestMessage requestMessage)
        {
            Logger logger = null;
            TransactionProcessorClient proc = null;

            try
            {
                DetermineEffectiveMerchantID(ref config, requestMessage);
                SetVersionInformation(requestMessage);
                logger = PrepareLog(config);
                SetConnectionLimit(config);


                CustomBinding currentBinding = getWCFCustomBinding(config);


                //Setup endpoint Address with dns identity
                AddressHeaderCollection headers         = new AddressHeaderCollection();
                EndpointAddress         endpointAddress = new EndpointAddress(new Uri(config.EffectiveServerURL), EndpointIdentity.CreateDnsIdentity(config.EffectivePassword), headers);

                //Get instance of service
                using (proc = new TransactionProcessorClient(currentBinding, endpointAddress)){
                    //Set protection level to sign & encrypt only
                    proc.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.Sign;

                    // set the timeout
                    TimeSpan timeOut = new TimeSpan(0, 0, 0, config.Timeout, 0);
                    currentBinding.SendTimeout = timeOut;

                    //add certificate credentials
                    string keyFilePath = Path.Combine(config.KeysDirectory, config.EffectiveKeyFilename);
                    proc.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(keyFilePath, config.EffectivePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                    proc.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;

                    // Changes for SHA2 certificates support
                    X509Certificate2Collection collection = new X509Certificate2Collection();
                    collection.Import(keyFilePath, config.EffectivePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                    foreach (X509Certificate2 cert1 in collection)
                    {
                        if (cert1.Subject.Contains(config.MerchantID))
                        {
                            proc.ClientCredentials.ClientCertificate.Certificate         = cert1;
                            proc.ClientCredentials.ServiceCertificate.DefaultCertificate = cert1;
                            break;
                        }
                    }

                    if (config.UseSignedAndEncrypted)
                    {
                        foreach (X509Certificate2 cert2 in collection)
                        {
                            //Console.WriteLine(cert1.Subject);
                            if (cert2.Subject.Contains(CYBERSOURCE_PUBLIC_KEY))
                            {
                                //Set protection level to sign & encrypt only
                                proc.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;
                                proc.ClientCredentials.ServiceCertificate.DefaultCertificate = cert2;
                                break;
                            }
                        }
                    }

                    // send request now
                    // Changes for NGT-3035
                    XmlNode req = SerializeObjectToXmlNode(requestMessage);
                    if (logger != null)
                    {
                        logger.LogRequest(req, config.Demo);
                    }

                    ReplyMessage reply = proc.runTransaction(requestMessage);
                    XmlNode      rep   = SerializeObjectToXmlNode(reply);
                    if (logger != null)
                    {
                        logger.LogReply(rep, config.Demo);
                    }

                    return(reply);
                }
            }
            catch (Exception e)
            {
                if (logger != null)
                {
                    logger.LogException(e);
                }
                if (proc != null)
                {
                    proc.Abort();
                }
                throw;
            }
            finally
            {
                if (proc != null)
                {
                    proc.Close();
                }
            }
        }
Beispiel #25
0
        public override void ApplyTo(ChannelFactory channelFactory)
        {
            channelFactory.Credentials.ClientCertificate.SetCertificate(StoreLocation, StoreName, X509FindType.FindBySubjectName, Subject);
            channelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust;
            channelFactory.Credentials.ServiceCertificate.Authentication.RevocationMode            = X509RevocationMode.Offline;

            channelFactory.Endpoint.Address = new EndpointAddress(channelFactory.Endpoint.Address.Uri, EndpointIdentity.CreateDnsIdentity(Subject));
        }
Beispiel #26
0
 public abstract bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext);
Beispiel #27
0
        private static void RunRemoteComponent(CompositionCommandInfo info, XmlProcessingContext xmlProcessingContext)
        {
            var remoteComponentInfo = info as RemoteComponentInfo;

            if (remoteComponentInfo == null)
            {
                throw new ArgumentException("Invalid runner input type: error in static setup.");
            }

            // Extract and load contract type

            var contractType = SimpleTypeParserUtil.ParseType(remoteComponentInfo.ContractType, xmlProcessingContext);

            if (contractType == null)
            {
                xmlProcessingContext.ReportError(
                    string.Format("Type '{0}' could not be loaded.", remoteComponentInfo.ContractType));
                return;
            }

            // Get contract name

            var contractName = remoteComponentInfo.ContractName;

            // Create end point address

            var serverAddress = remoteComponentInfo.ServerAddress ??
                                (string)
                                xmlProcessingContext.ComponentContext.GetVariable(remoteComponentInfo.ServerAddressVariableName);

            var spnIdentity = remoteComponentInfo.SpnIdentity ??
                              contractType.Name;

            var endpointAddress = new EndpointAddress(
                new Uri(serverAddress),
                EndpointIdentity.CreateSpnIdentity(spnIdentity));

            // Create binding

            var securityMode = (SecurityMode)Enum.Parse(
                typeof(SecurityMode),
                remoteComponentInfo.SecurityMode ?? "None",
                true);

            var binding = new NetTcpBinding(securityMode)
            {
                MaxBufferSize = (remoteComponentInfo.MaxBufferSizeNullable.HasValue
                                                                        ?
                                 remoteComponentInfo.MaxBufferSize
                                                                        :
                                 16777216),
                MaxReceivedMessageSize = (remoteComponentInfo.MaxReceivedMessageSizeNullable.HasValue
                                                                                ?
                                          remoteComponentInfo.MaxReceivedMessageSize
                                                                                :
                                          16777216)
            };

            // Extract list of known types

            List <Type> knownTypes = null;

            if (!string.IsNullOrEmpty(remoteComponentInfo.KnownTypesVariableName))
            {
                knownTypes =
                    xmlProcessingContext.ComponentContext.GetVariable(remoteComponentInfo.KnownTypesVariableName) as List <Type>;
            }

            // Build ComponentConfiguration

            var componentFactory = new RemoteComponentFactory
            {
                Address      = endpointAddress,
                Binding      = binding,
                ContractType = contractType,
                KnownTypes   = knownTypes
            };

            // Register the component into the component context.

            xmlProcessingContext.ComponentContext.Register(contractType, contractName, componentFactory);
        }
Beispiel #28
0
        private Exception CreateIdentityCheckException(EndpointIdentity identity, AuthorizationContext authorizationContext, string errorString, EndpointAddress serviceReference)
        {
            Exception result;

            if (identity.IdentityClaim != null &&
                identity.IdentityClaim.ClaimType == ClaimTypes.Dns &&
                identity.IdentityClaim.Right == Rights.PossessProperty &&
                identity.IdentityClaim.Resource is string)
            {
                string expectedDnsName = (string)identity.IdentityClaim.Resource;
                string actualDnsName   = null;
                for (int i = 0; i < authorizationContext.ClaimSets.Count; ++i)
                {
                    ClaimSet claimSet = authorizationContext.ClaimSets[i];
                    foreach (Claim claim in claimSet.FindClaims(ClaimTypes.Dns, Rights.PossessProperty))
                    {
                        if (claim.Resource is string)
                        {
                            actualDnsName = (string)claim.Resource;
                            break;
                        }
                    }
                    if (actualDnsName != null)
                    {
                        break;
                    }
                }
                if (SR.IdentityCheckFailedForIncomingMessage.Equals(errorString))
                {
                    if (actualDnsName == null)
                    {
                        result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForIncomingMessageLackOfDnsClaim, expectedDnsName));
                    }
                    else
                    {
                        result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForIncomingMessage, expectedDnsName, actualDnsName));
                    }
                }
                else if (SR.IdentityCheckFailedForOutgoingMessage.Equals(errorString))
                {
                    if (actualDnsName == null)
                    {
                        result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForOutgoingMessageLackOfDnsClaim, expectedDnsName));
                    }
                    else
                    {
                        result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForOutgoingMessage, expectedDnsName, actualDnsName));
                    }
                }
                else
                {
                    result = new MessageSecurityException(SR.Format(errorString, identity, serviceReference));
                }
            }
            else
            {
                result = new MessageSecurityException(SR.Format(errorString, identity, serviceReference));
            }

            return(result);
        }
Beispiel #29
0
        CreateWSFederationHttpBinding(bool isClient)
        {
            // Create an instance of the WSFederationHttpBinding.
            WSFederationHttpBinding b = new WSFederationHttpBinding();

            // Set the security mode to Message.
            b.Security.Mode = WSFederationHttpSecurityMode.Message;

            // Set the Algorithm Suite to Basic256Rsa15.
            b.Security.Message.AlgorithmSuite = SecurityAlgorithmSuite.Basic256Rsa15;

            // Set NegotiateServiceCredential to true.
            b.Security.Message.NegotiateServiceCredential = true;

            // Set IssuedKeyType to Symmetric.
            b.Security.Message.IssuedKeyType = SecurityKeyType.SymmetricKey;

            // Set IssuedTokenType to SAML 1.1
            b.Security.Message.IssuedTokenType =
                "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#samlv1.1";

            // Extract the STS certificate from the certificate store.
            X509Store store = new X509Store(StoreName.TrustedPeople, StoreLocation.CurrentUser);

            store.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certs = store.Certificates.Find(
                X509FindType.FindByThumbprint, "0000000000000000000000000000000000000000", false);

            store.Close();

            // Create an EndpointIdentity from the STS certificate.
            EndpointIdentity identity = EndpointIdentity.CreateX509CertificateIdentity(certs[0]);

            // Set the IssuerAddress using the address of the STS and the previously created
            // EndpointIdentity.
            b.Security.Message.IssuerAddress =
                new EndpointAddress(new Uri("http://localhost:8000/sts/x509"), identity);

            // Set the IssuerBinding to a WSHttpBinding loaded from configuration.
            // The IssuerBinding is only used on federated clients.
            if (isClient)
            {
                b.Security.Message.IssuerBinding = new WSHttpBinding("Issuer");
            }

            // Set the IssuerMetadataAddress using the metadata address of the STS and the
            // previously created EndpointIdentity. The IssuerMetadataAddress is only used
            // on federated services.
            else
            {
                b.Security.Message.IssuerMetadataAddress =
                    new EndpointAddress(new Uri("http://localhost:8001/sts/mex"), identity);
            }
            // Create a ClaimTypeRequirement.
            ClaimTypeRequirement ctr = new ClaimTypeRequirement
                                           ("http://example.org/claim/c1", false);

            // Add the ClaimTypeRequirement to ClaimTypeRequirements
            b.Security.Message.ClaimTypeRequirements.Add(ctr);

            // Return the created binding
            return(b);
        }
 internal static void TraceIdentityVerificationSuccess(EventTraceActivity eventTraceActivity, EndpointIdentity identity, Claim claim, Type identityVerifier)
 {
 }
        public static IQueryable <EmailEndpointEntity> GetEmailEndpoint(this IEmailEndpointDbContext emailEndpointDbContext, EndpointIdentity endpointIdentity)
        {
            var queryable = emailEndpointDbContext.EmailEndpoints.Where(x => x.EndpointGUID == endpointIdentity.Value);

            return(queryable);
        }
 internal static void TraceIdentityDeterminationSuccess(EndpointAddress epr, EndpointIdentity identity, Type identityVerifier)
 {
 }
 internal bool TryGetIdentity(EndpointAddress reference, Uri via, out EndpointIdentity identity)
 {
     AdjustAddress(ref reference, via);
     return(TryGetIdentity(reference, out identity));
 }
Beispiel #34
0
            public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext)
            {
                EventTraceActivity eventTraceActivity = null;
 
                if (identity == null)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identity");
 
                if (authContext == null)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authContext");
 
 
                if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled)
                {
                    eventTraceActivity = EventTraceActivityHelper.TryExtractActivity((OperationContext.Current != null) ? OperationContext.Current.IncomingMessage : null);
                }
 
                for (int i = 0; i < authContext.ClaimSets.Count; ++i)
                {
                    ClaimSet claimSet = authContext.ClaimSets[i];
                    if (claimSet.ContainsClaim(identity.IdentityClaim))
                    {
                        SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, identity.IdentityClaim, this.GetType());
                        return true;
                    }
 
                    // try Claim equivalence
                    string expectedSpn = null;
                    if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
                    {
                        expectedSpn = string.Format(CultureInfo.InvariantCulture, "host/{0}", (string)identity.IdentityClaim.Resource);
                        Claim claim = CheckDnsEquivalence(claimSet, expectedSpn);
                        if (claim != null)
                        {
                            SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, this.GetType());
                            return true;
                        }
                    }

                    // Allow a Sid claim to support UPN, and SPN identities
                    
                    // SID claims not available yet 
                    //SecurityIdentifier identitySid = null;
                    //if (ClaimTypes.Sid.Equals(identity.IdentityClaim.ClaimType))
                    //{
                    //    throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Sid");
                    //}
                    //else if (ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType))
                    //{
                    //    throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Upn");
                    //}
                    //else if (ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType))
                    //{
                    //    throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Spn");
                    //}
                    //else if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
                    //{
                    //    throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Dns");
                    //}
                    //if (identitySid != null)
                    //{
                    //    Claim claim = CheckSidEquivalence(identitySid, claimSet);
                    //    if (claim != null)
                    //    {
                    //        SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, this.GetType());
                    //        return true;
                    //    }
                    //}
                }
                SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authContext, this.GetType());
                if (WcfEventSource.Instance.SecurityIdentityVerificationFailureIsEnabled())
                {
                    WcfEventSource.Instance.SecurityIdentityVerificationFailure(eventTraceActivity);
                }

                return false; 
            }
Beispiel #35
0
 private static EndpointAddress CreateEndpointAddress(Uri serviceUrl, string dnsName)
 {
     return(new EndpointAddress(serviceUrl, EndpointIdentity.CreateDnsIdentity(dnsName)));
 }
Beispiel #36
0
 public abstract bool TryGetIdentity(EndpointAddress reference, out EndpointIdentity identity);
 public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext)
 {
     return(true);
 }
Beispiel #38
0
        private Exception CreateIdentityCheckException(EndpointIdentity identity, AuthorizationContext authorizationContext, string errorString, EndpointAddress serviceReference)
        {
            Exception result;
 
            if (identity.IdentityClaim != null
                && identity.IdentityClaim.ClaimType == ClaimTypes.Dns
                && identity.IdentityClaim.Right == Rights.PossessProperty
                && identity.IdentityClaim.Resource is string)
            {
                string expectedDnsName = (string)identity.IdentityClaim.Resource;
                string actualDnsName = null;
                for (int i = 0; i < authorizationContext.ClaimSets.Count; ++i)
                {
                    ClaimSet claimSet = authorizationContext.ClaimSets[i];
                    foreach (Claim claim in claimSet.FindClaims(ClaimTypes.Dns, Rights.PossessProperty))
                    {
                        if (claim.Resource is string)
                        {
                            actualDnsName = (string)claim.Resource;
                            break;
                        }
                    }
                    if (actualDnsName != null)
                    {
                        break;
                    }
                }
                if (SR.IdentityCheckFailedForIncomingMessage.Equals(errorString))
                {
                    if (actualDnsName == null)
                    {
                        result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForIncomingMessageLackOfDnsClaim, expectedDnsName));
                    }
                    else
                    {
                        result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForIncomingMessage, expectedDnsName, actualDnsName));
                    }
                }
                else if (SR.IdentityCheckFailedForOutgoingMessage.Equals(errorString))
                {
                    if (actualDnsName == null)
                    {
                        result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForOutgoingMessageLackOfDnsClaim, expectedDnsName));
                    }
                    else
                    {
                        result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForOutgoingMessage, expectedDnsName, actualDnsName));
                    }
                }
                else
                {
                    result = new MessageSecurityException(SR.Format(errorString, identity, serviceReference));
                }
            }
            else
            {
                result = new MessageSecurityException(SR.Format(errorString, identity, serviceReference));
            }
 
            return result;
        }
Beispiel #39
0
        // Host the service within this EXE console application.
        public static void Main()
        {
            // Create a ServiceHost for the CalculatorService type. Base Address is supplied in app.config
            using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService)))
            {
                // The base address is read from the app.config
                Uri dnsrelativeAddress         = new Uri(serviceHost.BaseAddresses[0], "dnsidentity");
                Uri certificaterelativeAddress = new Uri(serviceHost.BaseAddresses[0], "certificateidentity");
                Uri rsarelativeAddress         = new Uri(serviceHost.BaseAddresses[0], "rsaidentity");

                // Set the service's X509Certificate to protect the messages
                serviceHost.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine,
                                                                          StoreName.My,
                                                                          X509FindType.FindBySubjectDistinguishedName,
                                                                          "CN=identity.com, O=Contoso");
                //cache a reference to the server's certificate.
                X509Certificate2 servercert = serviceHost.Credentials.ServiceCertificate.Certificate;

                //Create endpoints for the service using a WSHttpBinding set for anonymous clients
                WSHttpBinding wsAnonbinding = new WSHttpBinding(SecurityMode.Message);
                //Clients are anonymous to the service
                wsAnonbinding.Security.Message.ClientCredentialType = MessageCredentialType.None;
                //Secure conversation (session) is turned off
                wsAnonbinding.Security.Message.EstablishSecurityContext = false;

                //Create a service endpoint and change its identity to the DNS for an X509 Certificate
                ServiceEndpoint ep = serviceHost.AddServiceEndpoint(typeof(ICalculator),
                                                                    wsAnonbinding,
                                                                    String.Empty);
                EndpointAddress epa = new EndpointAddress(dnsrelativeAddress, EndpointIdentity.CreateDnsIdentity("identity.com"));
                ep.Address = epa;

                //Create a service endpoint and change its identity to the X509 certificate returned as base64 encoded value
                ServiceEndpoint ep2 = serviceHost.AddServiceEndpoint(typeof(ICalculator),
                                                                     wsAnonbinding,
                                                                     String.Empty);
                EndpointAddress epa2 = new EndpointAddress(certificaterelativeAddress, EndpointIdentity.CreateX509CertificateIdentity(servercert));
                ep2.Address = epa2;

                //Create a service endpoint and change its identity to the X509 certificate's RSA key value
                ServiceEndpoint ep3  = serviceHost.AddServiceEndpoint(typeof(ICalculator), wsAnonbinding, String.Empty);
                EndpointAddress epa3 = new EndpointAddress(rsarelativeAddress, EndpointIdentity.CreateRsaIdentity(servercert));
                ep3.Address = epa3;

                // Open the ServiceHostBase to create listeners and start listening for messages.
                serviceHost.Open();

                // List the address and the identity for each ServiceEndpoint
                foreach (ChannelDispatcher channelDispatcher in serviceHost.ChannelDispatchers)
                {
                    foreach (EndpointDispatcher endpointDispatcher in channelDispatcher.Endpoints)
                    {
                        Console.WriteLine("Endpoint Address: {0}", endpointDispatcher.EndpointAddress);
                        Console.WriteLine("Endpoint Identity: {0}", endpointDispatcher.EndpointAddress.Identity);
                        Console.WriteLine();
                    }
                }

                //foreach (ServiceEndpoint endpoint in serviceHost.Description.Endpoints)
                //{
                //    object resource = endpoint.Address.Identity.IdentityClaim.Resource;
                //    string identityValue;
                //    if (resource.GetType() == typeof(System.Byte[]))
                //    {
                //        identityValue = System.Convert.ToBase64String((System.Byte[])(resource));
                //    }
                //    else
                //        identityValue = resource.ToString();

                //    Console.WriteLine("Service listening Address: {0}", endpoint.Address);
                //    Console.WriteLine("Service listening Identity: {0}", identityValue);
                //    Console.WriteLine();
                //}

                // The service can now be accessed.
                Console.WriteLine();
                Console.WriteLine("The service is ready.");
                Console.WriteLine("Press <ENTER> to terminate service.");
                Console.WriteLine();
                Console.ReadLine();
            }
        }