Esempio n. 1
0
        private EndpointDescriptionCollection Discover(string discoveryURL, int operationTimeout)
        {
            Uri uri = new Uri(discoveryURL);

            EndpointConfiguration configuration = EndpointConfiguration.Create();

            if (operationTimeout > 0)
            {
                configuration.OperationTimeout = operationTimeout;
            }

            var endpoints = new EndpointDescriptionCollection();

            using (DiscoveryClient client = DiscoveryClient.Create(uri, configuration))
            {
                foreach (var got in client.GetEndpoints(null))
                {
                    if (got.EndpointUrl.StartsWith(uri.Scheme))
                    {
                        endpoints.Add(got);
                    }
                }
            }

            return(endpoints);
        }
Esempio n. 2
0
        public void RetrieveEndpointsAndPopulateLV()
        {
            EndpointDescriptionCollection endpointDescCol = new EndpointDescriptionCollection();

            XmlNodeList endpointNodes = myDoc.SelectSingleNode("//Endpoints").SelectNodes("//Endpoint");
            XmlNodeList ipConfig      = myDoc.SelectSingleNode("//Endpoints").SelectNodes("//IpConfig");

            foreach (XmlNode node in endpointNodes)
            {
                EndpointDescription epDesc = new EndpointDescription();
                epDesc.EndpointUrl            = node.SelectSingleNode("url").InnerText;
                epDesc.Server.ApplicationName = node.SelectSingleNode("serverName").InnerText;
                string[] secMode = node.SelectSingleNode("securityMode").InnerText.Split('-');
                epDesc.SecurityPolicyUri = "http://opcfoundation.org/UA/SecurityPolicy#" + secMode[0];
                if (secMode[1].Equals("SignAndEncrypt"))
                {
                    epDesc.SecurityMode = MessageSecurityMode.SignAndEncrypt;
                }
                else if (secMode[1].Equals("Sign"))
                {
                    epDesc.SecurityMode = MessageSecurityMode.Sign;
                }
                else if (secMode[1].Equals("None"))
                {
                    epDesc.SecurityMode = MessageSecurityMode.None;
                }
                else
                {
                    epDesc.SecurityMode = MessageSecurityMode.Invalid;
                }

                endpointDescCol.Add(epDesc);
            }

            RecentEndpointsLV.Items.Clear();
            foreach (EndpointDescription ep in endpointDescCol)
            {
                string       securityPolicy = ep.SecurityPolicyUri.Remove(0, 43);
                string[]     row            = { ep.Server.ApplicationName.Text, ep.EndpointUrl, ep.SecurityMode + "-" + securityPolicy };
                ListViewItem listViewItem   = new ListViewItem(row);
                RecentEndpointsLV.Items.Add(listViewItem).Tag = ep;
                RecentEndpointsLV.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            }

            if (ipConfig[0].ChildNodes.Count > 0)
            {
                DiscoveryUrlTB.Text  = ipConfig[0].SelectSingleNode("IP").InnerText;
                DiscoveryPortTB.Text = ipConfig[0].SelectSingleNode("Port").InnerText;
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Updates an endpoint with information from the server's discovery endpoint.
        /// </summary>
        public void UpdateFromServer(
            Uri endpointUrl,
            MessageSecurityMode securityMode,
            string securityPolicyUri)
        {
            // get the a discovery url.
            Uri discoveryUrl = GetDiscoveryUrl(endpointUrl);

            // create the discovery client.
            DiscoveryClient client = DiscoveryClient.Create(discoveryUrl, m_configuration);

            try
            {
                // get the endpoints.
                EndpointDescriptionCollection collection = client.GetEndpoints(null);

                if (collection == null || collection.Count == 0)
                {
                    throw ServiceResultException.Create(
                              StatusCodes.BadUnknownResponse,
                              "Server does not have any endpoints defined.");
                }

                // find list of matching endpoints.
                EndpointDescriptionCollection matches = new EndpointDescriptionCollection();

                // first pass - match on the requested security parameters.
                foreach (EndpointDescription description in collection)
                {
                    // check for match on security policy.
                    if (!String.IsNullOrEmpty(securityPolicyUri))
                    {
                        if (securityPolicyUri != description.SecurityPolicyUri)
                        {
                            continue;
                        }
                    }

                    // check for match on security mode.
                    if (securityMode != MessageSecurityMode.Invalid)
                    {
                        if (securityMode != description.SecurityMode)
                        {
                            continue;
                        }
                    }

                    // add to list of matches.
                    matches.Add(description);
                }

                // no matches (security parameters may have changed).
                if (matches.Count == 0)
                {
                    matches = collection;
                }

                // check if list has to be narrowed down further.
                if (matches.Count > 1)
                {
                    collection = matches;
                    matches    = new EndpointDescriptionCollection();

                    // second pass - match on the url scheme.
                    foreach (EndpointDescription description in collection)
                    {
                        // parse the endpoint url.
                        Uri sessionUrl = Utils.ParseUri(description.EndpointUrl);

                        if (sessionUrl == null)
                        {
                            continue;
                        }

                        // check for matching protocol.
                        if (sessionUrl.Scheme != endpointUrl.Scheme)
                        {
                            continue;
                        }

                        matches.Add(description);
                    }
                }

                // no matches (protocol may not be supported).
                if (matches.Count == 0)
                {
                    matches = collection;
                }

                // choose first in list by default.
                EndpointDescription match = matches[0];

                // check if list has to be narrowed down further.
                if (matches.Count > 1)
                {
                    // third pass - match based on security level.
                    foreach (EndpointDescription description in matches)
                    {
                        if (description.SecurityMode > match.SecurityMode)
                        {
                            match = description;
                        }
                    }
                }

                // check if the endpoint url matches the endpoint used in the request.
                Uri matchUrl = Utils.ParseUri(match.EndpointUrl);

                if (matchUrl == null || String.Compare(discoveryUrl.DnsSafeHost, matchUrl.DnsSafeHost, StringComparison.OrdinalIgnoreCase) != 0)
                {
                    UriBuilder uri = new UriBuilder(matchUrl);
                    uri.Host          = discoveryUrl.DnsSafeHost;
                    uri.Port          = discoveryUrl.Port;
                    match.EndpointUrl = uri.ToString();

                    // need to update the discovery urls.
                    match.Server.DiscoveryUrls.Clear();
                    match.Server.DiscoveryUrls.Add(discoveryUrl.ToString());
                }

                // update the endpoint.
                Update(match);
            }
            finally
            {
                client.Close();
            }
        }
Esempio n. 4
0
        /// <inheritdoc/>
        /// <summary>
        /// Create a new service host for UA HTTPS.
        /// </summary>
        public List <EndpointDescription> CreateServiceHost(
            ServerBase serverBase,
            IDictionary <string, Task> hosts,
            ApplicationConfiguration configuration,
            IList <string> baseAddresses,
            ApplicationDescription serverDescription,
            List <ServerSecurityPolicy> securityPolicies,
            X509Certificate2 instanceCertificate,
            X509Certificate2Collection instanceCertificateChain
            )
        {
            // generate a unique host name.
            string hostName = String.Empty;

            if (hosts.ContainsKey(hostName))
            {
                hostName = "/Https";
            }

            if (hosts.ContainsKey(hostName))
            {
                hostName += Utils.Format("/{0}", hosts.Count);
            }

            // build list of uris.
            List <Uri> uris = new List <Uri>();
            EndpointDescriptionCollection endpoints = new EndpointDescriptionCollection();

            // create the endpoint configuration to use.
            EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(configuration);
            string computerName = Utils.GetHostName();

            for (int ii = 0; ii < baseAddresses.Count; ii++)
            {
                if (!baseAddresses[ii].StartsWith(Utils.UriSchemeHttps, StringComparison.Ordinal))
                {
                    continue;
                }

                UriBuilder uri = new UriBuilder(baseAddresses[ii]);

                if (uri.Path[uri.Path.Length - 1] != '/')
                {
                    uri.Path += "/";
                }

                if (String.Compare(uri.Host, "localhost", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    uri.Host = computerName;
                }

                uris.Add(uri.Uri);

                if (uri.Scheme == Utils.UriSchemeHttps)
                {
                    // Can only support one policy with HTTPS
                    // So pick the first policy with security mode sign and encrypt
                    ServerSecurityPolicy bestPolicy = null;
                    foreach (ServerSecurityPolicy policy in securityPolicies)
                    {
                        if (policy.SecurityMode != MessageSecurityMode.SignAndEncrypt)
                        {
                            continue;
                        }

                        bestPolicy = policy;
                        break;
                    }

                    // Pick the first policy from the list if no policies with sign and encrypt defined
                    if (bestPolicy == null)
                    {
                        bestPolicy = securityPolicies[0];
                    }

                    EndpointDescription description = new EndpointDescription();

                    description.EndpointUrl = uri.ToString();
                    description.Server      = serverDescription;

                    if (instanceCertificate != null)
                    {
                        description.ServerCertificate = instanceCertificate.RawData;
                        // check if complete chain should be sent.
                        if (configuration.SecurityConfiguration.SendCertificateChain &&
                            instanceCertificateChain != null &&
                            instanceCertificateChain.Count > 0)
                        {
                            List <byte> serverCertificateChain = new List <byte>();

                            for (int i = 0; i < instanceCertificateChain.Count; i++)
                            {
                                serverCertificateChain.AddRange(instanceCertificateChain[i].RawData);
                            }

                            description.ServerCertificate = serverCertificateChain.ToArray();
                        }
                    }

                    description.SecurityMode        = bestPolicy.SecurityMode;
                    description.SecurityPolicyUri   = bestPolicy.SecurityPolicyUri;
                    description.SecurityLevel       = ServerSecurityPolicy.CalculateSecurityLevel(bestPolicy.SecurityMode, bestPolicy.SecurityPolicyUri);
                    description.UserIdentityTokens  = serverBase.GetUserTokenPolicies(configuration, description);
                    description.TransportProfileUri = Profiles.HttpsBinaryTransport;

                    ITransportListener listener = Create();
                    if (listener != null)
                    {
                        endpoints.Add(description);
                        serverBase.CreateServiceHostEndpoint(uri.Uri, endpoints, endpointConfiguration, listener,
                                                             configuration.CertificateValidator.GetChannelValidator());
                    }
                    else
                    {
                        Utils.Trace(Utils.TraceMasks.Error, "Failed to create endpoint {0} because the transport profile is unsupported.", uri);
                    }
                }
            }

            return(endpoints);
        }
Esempio n. 5
0
        /// <inheritdoc/>
        /// <summary>
        /// Create a new service host for UA TCP.
        /// </summary>
        public List <EndpointDescription> CreateServiceHost(
            ServerBase serverBase,
            IDictionary <string, ServiceHost> hosts,
            ApplicationConfiguration configuration,
            IList <string> baseAddresses,
            ApplicationDescription serverDescription,
            List <ServerSecurityPolicy> securityPolicies,
            X509Certificate2 instanceCertificate,
            X509Certificate2Collection instanceCertificateChain)
        {
            // generate a unique host name.
            string hostName = "/Tcp";

            if (hosts.ContainsKey(hostName))
            {
                hostName += Utils.Format("/{0}", hosts.Count);
            }

            // build list of uris.
            List <Uri> uris = new List <Uri>();
            EndpointDescriptionCollection endpoints = new EndpointDescriptionCollection();

            // create the endpoint configuration to use.
            EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(configuration);
            string computerName = Utils.GetHostName();

            for (int ii = 0; ii < baseAddresses.Count; ii++)
            {
                // UA TCP and HTTPS endpoints support multiple policies.
                if (!baseAddresses[ii].StartsWith(Utils.UriSchemeOpcTcp, StringComparison.Ordinal))
                {
                    continue;
                }

                UriBuilder uri = new UriBuilder(baseAddresses[ii]);

                if (String.Equals(uri.Host, "localhost", StringComparison.OrdinalIgnoreCase))
                {
                    uri.Host = computerName;
                }

                ITransportListener listener = this.Create();
                if (listener != null)
                {
                    EndpointDescriptionCollection listenerEndpoints = new EndpointDescriptionCollection();
                    uris.Add(uri.Uri);

                    foreach (ServerSecurityPolicy policy in securityPolicies)
                    {
                        // create the endpoint description.
                        EndpointDescription description = new EndpointDescription();

                        description.EndpointUrl = uri.ToString();
                        description.Server      = serverDescription;

                        description.SecurityMode        = policy.SecurityMode;
                        description.SecurityPolicyUri   = policy.SecurityPolicyUri;
                        description.SecurityLevel       = ServerSecurityPolicy.CalculateSecurityLevel(policy.SecurityMode, policy.SecurityPolicyUri);
                        description.UserIdentityTokens  = serverBase.GetUserTokenPolicies(configuration, description);
                        description.TransportProfileUri = Profiles.UaTcpTransport;

                        bool requireEncryption = ServerBase.RequireEncryption(description);

                        if (requireEncryption)
                        {
                            description.ServerCertificate = instanceCertificate.RawData;

                            // check if complete chain should be sent.
                            if (configuration.SecurityConfiguration.SendCertificateChain &&
                                instanceCertificateChain != null &&
                                instanceCertificateChain.Count > 0)
                            {
                                List <byte> serverCertificateChain = new List <byte>();

                                for (int i = 0; i < instanceCertificateChain.Count; i++)
                                {
                                    serverCertificateChain.AddRange(instanceCertificateChain[i].RawData);
                                }

                                description.ServerCertificate = serverCertificateChain.ToArray();
                            }
                        }

                        listenerEndpoints.Add(description);
                    }

                    serverBase.CreateServiceHostEndpoint(uri.Uri, listenerEndpoints, endpointConfiguration, listener,
                                                         configuration.CertificateValidator.GetChannelValidator()
                                                         );

                    endpoints.AddRange(listenerEndpoints);
                }
                else
                {
                    Utils.Trace(Utils.TraceMasks.Error, "Failed to create endpoint {0} because the transport profile is unsupported.", uri);
                }
            }

            hosts[hostName] = serverBase.CreateServiceHost(serverBase, uris.ToArray());

            return(endpoints);
        }
Esempio n. 6
0
        /// <summary>
        /// Translates the endpoint descriptions based on the client url and profiles provided.
        /// </summary>
        /// <param name="clientUrl">The client URL.</param>
        /// <param name="baseAddresses">The base addresses.</param>
        /// <param name="endpoints">The endpoints.</param>
        /// <param name="application">The application to use with the endpoints.</param>
        /// <returns>The translated list of endpoints.</returns>
        protected EndpointDescriptionCollection TranslateEndpointDescriptions(
            Uri clientUrl,
            IList <BaseAddress> baseAddresses,
            IList <EndpointDescription> endpoints,
            ApplicationDescription application)
        {
            EndpointDescriptionCollection translations = new EndpointDescriptionCollection();

            // process endpoints
            foreach (EndpointDescription endpoint in endpoints)
            {
                UriBuilder endpointUrl = new UriBuilder(endpoint.EndpointUrl);

                // find matching base address.
                foreach (BaseAddress baseAddress in baseAddresses)
                {
                    bool translateHttpsEndpoint = false;
                    if (endpoint.TransportProfileUri == Profiles.HttpsBinaryTransport && baseAddress.ProfileUri == Profiles.HttpsBinaryTransport)
                    {
                        translateHttpsEndpoint = true;
                    }

                    if (endpoint.TransportProfileUri != baseAddress.ProfileUri && !translateHttpsEndpoint)
                    {
                        continue;
                    }

                    if (endpointUrl.Scheme != baseAddress.Url.Scheme)
                    {
                        continue;
                    }

                    EndpointDescription translation = new EndpointDescription();

                    translation.EndpointUrl = baseAddress.Url.ToString();

                    if (endpointUrl.Path.StartsWith(baseAddress.Url.PathAndQuery) && endpointUrl.Path.Length > baseAddress.Url.PathAndQuery.Length)
                    {
                        string suffix = endpointUrl.Path.Substring(baseAddress.Url.PathAndQuery.Length);
                        translation.EndpointUrl += suffix;
                    }

                    translation.ProxyUrl            = endpoint.ProxyUrl;
                    translation.SecurityLevel       = endpoint.SecurityLevel;
                    translation.SecurityMode        = endpoint.SecurityMode;
                    translation.SecurityPolicyUri   = endpoint.SecurityPolicyUri;
                    translation.ServerCertificate   = endpoint.ServerCertificate;
                    translation.TransportProfileUri = endpoint.TransportProfileUri;
                    translation.UserIdentityTokens  = endpoint.UserIdentityTokens;
                    translation.Server = application;

                    // skip duplicates.
                    bool duplicateFound = false;

                    foreach (EndpointDescription existingTranslation in translations)
                    {
                        if (existingTranslation.IsEqual(translation))
                        {
                            duplicateFound = true;
                            break;
                        }
                    }

                    if (!duplicateFound)
                    {
                        translations.Add(translation);
                    }
                }
            }

            return(translations);
        }
Esempio n. 7
0
        /// <summary>
        /// Create a new service host for UA TCP.
        /// </summary>
        protected List<EndpointDescription> CreateUaTcpServiceHost(
            IDictionary<string, ServiceHost> hosts,
            ApplicationConfiguration configuration,
            BindingFactory bindingFactory,
            IList<string> baseAddresses,
            ApplicationDescription serverDescription,
            List<ServerSecurityPolicy> securityPolicies)
        {
            // generate a unique host name.
            string hostName = String.Empty;

            if (hosts.ContainsKey(hostName))
            {
                hostName = "/Tcp";
            }

            if (hosts.ContainsKey(hostName))
            {
                hostName += Utils.Format("/{0}", hosts.Count);
            }

            // check if the server if configured to use the ANSI C stack.
            bool useAnsiCStack = configuration.UseNativeStack;

            // build list of uris.
            List<Uri> uris = new List<Uri>();
            EndpointDescriptionCollection endpoints = new EndpointDescriptionCollection();

            // create the endpoint configuration to use.
            EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(configuration);
            string computerName = System.Net.Dns.GetHostName();

            for (int ii = 0; ii < baseAddresses.Count; ii++)
            {
                // UA TCP and HTTPS endpoints support multiple policies.
                if (!baseAddresses[ii].StartsWith(Utils.UriSchemeOpcTcp, StringComparison.Ordinal))
                {
                    continue;
                }

                UriBuilder uri = new UriBuilder(baseAddresses[ii]);

                if (String.Compare(uri.Host, "localhost", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    uri.Host = computerName;
                }

                uris.Add(uri.Uri);

                foreach (ServerSecurityPolicy policy in securityPolicies)
                {
                    // create the endpoint description.
                    EndpointDescription description = new EndpointDescription();

                    description.EndpointUrl = uri.ToString();
                    description.Server = serverDescription;

                    description.SecurityMode = policy.SecurityMode;
                    description.SecurityPolicyUri = policy.SecurityPolicyUri;
                    description.SecurityLevel = policy.SecurityLevel;
                    description.UserIdentityTokens = GetUserTokenPolicies( configuration, description );
                    description.TransportProfileUri = Profiles.UaTcpTransport;

                    bool requireEncryption = RequireEncryption(description);

                    if (!requireEncryption)
                    {
                        foreach (UserTokenPolicy userTokenPolicy in description.UserIdentityTokens)
                        {
                            if (userTokenPolicy.SecurityPolicyUri != SecurityPolicies.None)
                            {
                                requireEncryption = true;
                                break;
                            }
                        }
                    }

                    if (requireEncryption)
                    {
                        description.ServerCertificate = InstanceCertificate.RawData;

                        //if (InstanceCertificateChain != null)
                        //{
                        //    List<byte> certificateChainList = new List<byte>();
                        //    for (int i = 0; i < InstanceCertificateChain.Count; i++)
                        //    {
                        //        certificateChainList.AddRange(InstanceCertificateChain[i].RawData);
                        //    }
                        //    description.ServerCertificate = certificateChainList.ToArray();
                        //}
                    }

                    endpoints.Add( description );
                }

                // create the UA-TCP stack listener.
                try
                {
                    TransportListenerSettings settings = new TransportListenerSettings();

                    settings.Descriptions = endpoints;
                    settings.Configuration = endpointConfiguration;
                    settings.ServerCertificate = this.InstanceCertificate;
                    //settings.ServerCertificateChain = this.InstanceCertificateChain;
                    settings.CertificateValidator = configuration.CertificateValidator.GetChannelValidator();
                    settings.NamespaceUris = this.MessageContext.NamespaceUris;
                    settings.Factory = this.MessageContext.Factory;

                    ITransportListener listener = null;

                    Type type = null;

                    if (useAnsiCStack)
                    {
                        type = Type.GetType("Opc.Ua.NativeStack.NativeStackListener,Opc.Ua.NativeStackWrapper");
                    }

                    if (useAnsiCStack && type != null)
                    {
                        listener = (ITransportListener)Activator.CreateInstance(type);
                    }
                    else
                    {
                        listener = new Opc.Ua.Bindings.UaTcpChannelListener();
                    }

                    listener.Open(
                       uri.Uri,
                       settings,
                       GetEndpointInstance(this));

                    TransportListeners.Add(listener);
                }
                catch (Exception e)
                {
                    Utils.Trace(e, "Could not load UA-TCP Stack Listener.");
					throw;
                }
            }

            return endpoints;
        }
Esempio n. 8
0
        /// <summary>
        /// Translates the endpoint descriptions based on the client url and profiles provided.
        /// </summary>
        /// <param name="clientUrl">The client URL.</param>
        /// <param name="baseAddresses">The base addresses.</param>
        /// <param name="endpoints">The endpoints.</param>
        /// <param name="application">The application to use with the endpoints.</param>
        /// <returns>The translated list of endpoints.</returns>
        protected EndpointDescriptionCollection TranslateEndpointDescriptions(
            Uri clientUrl,
            IList<BaseAddress> baseAddresses,
            IList<EndpointDescription> endpoints,
            ApplicationDescription application)
        {
            EndpointDescriptionCollection translations = new EndpointDescriptionCollection();

            // process endpoints
            foreach (EndpointDescription endpoint in endpoints)
            {
                UriBuilder endpointUrl = new UriBuilder(endpoint.EndpointUrl);

                // find matching base address.
                foreach (BaseAddress baseAddress in baseAddresses)
                {
					bool translateHttpsEndpoint = false;
					if ((endpoint.TransportProfileUri == Profiles.HttpsBinaryTransport && baseAddress.ProfileUri == Profiles.HttpsXmlOrBinaryTransport)
						|| endpoint.TransportProfileUri == Profiles.HttpsBinaryTransport && baseAddress.ProfileUri == Profiles.HttpsBinaryTransport)
					{
						translateHttpsEndpoint = true;
					}
					if ((endpoint.TransportProfileUri == Profiles.HttpsXmlTransport && baseAddress.ProfileUri == Profiles.HttpsXmlOrBinaryTransport)
						|| endpoint.TransportProfileUri == Profiles.HttpsXmlTransport && baseAddress.ProfileUri == Profiles.HttpsXmlTransport)
					{
						translateHttpsEndpoint = true;
					}

                    if (endpoint.TransportProfileUri != baseAddress.ProfileUri && !translateHttpsEndpoint)
                    {
                        continue;
                    }

                    if (endpointUrl.Scheme != baseAddress.Url.Scheme)
                    {
                        continue;
                    }
                            
                    EndpointDescription translation = new EndpointDescription();

                    translation.EndpointUrl = baseAddress.Url.ToString();

                    if (endpointUrl.Path.StartsWith(baseAddress.Url.PathAndQuery) && endpointUrl.Path.Length > baseAddress.Url.PathAndQuery.Length)
                    {
                        string suffix = endpointUrl.Path.Substring(baseAddress.Url.PathAndQuery.Length);
                        translation.EndpointUrl += suffix;
                    }

                    translation.ProxyUrl = endpoint.ProxyUrl;
                    translation.SecurityLevel = endpoint.SecurityLevel;
                    translation.SecurityMode = endpoint.SecurityMode;
                    translation.SecurityPolicyUri = endpoint.SecurityPolicyUri;
                    translation.ServerCertificate = endpoint.ServerCertificate;
                    translation.TransportProfileUri = endpoint.TransportProfileUri;
                    translation.UserIdentityTokens = endpoint.UserIdentityTokens;
                    translation.Server = application;

                    translations.Add(translation);
                }
            }

            return translations;
        }
Esempio n. 9
0
        /// <summary>
        /// Create a new service host for UA HTTPS.
        /// </summary>
        protected List<EndpointDescription> CreateHttpsServiceHost(
            IDictionary<string, ServiceHost> hosts,
            ApplicationConfiguration configuration,
            BindingFactory bindingFactory,
            IList<string> baseAddresses,
            ApplicationDescription serverDescription,
            List<ServerSecurityPolicy> securityPolicies)
        {
            // generate a unique host name.
            string hostName = String.Empty;

            if (hosts.ContainsKey(hostName))
            {
                hostName = "/Https";
            }

            if (hosts.ContainsKey(hostName))
            {
                hostName += Utils.Format("/{0}", hosts.Count);
            }

            // build list of uris.
            List<Uri> uris = new List<Uri>();
            EndpointDescriptionCollection endpoints = new EndpointDescriptionCollection();

            // create the endpoint configuration to use.
            EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(configuration);
            string computerName = System.Net.Dns.GetHostName();

            for (int ii = 0; ii < baseAddresses.Count; ii++)
            {
                if (!baseAddresses[ii].StartsWith(Utils.UriSchemeHttps, StringComparison.Ordinal) &&
                    !baseAddresses[ii].StartsWith(Utils.UriSchemeNoSecurityHttp, StringComparison.Ordinal))
                {
                    continue;
                }

                UriBuilder uri = new UriBuilder(baseAddresses[ii]);

                if (uri.Scheme == Utils.UriSchemeNoSecurityHttp)
                {
                    uri.Scheme = Utils.UriSchemeHttp;
                }

                if (uri.Path[uri.Path.Length-1] != '/')
                {
                    uri.Path += "/";
                }

                if (String.Compare(uri.Host, "localhost", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    uri.Host = computerName;
                }

                uris.Add(uri.Uri);

                if (uri.Scheme == Utils.UriSchemeHttps)
                {
                    // can only support one policy with HTTPS so pick the best one.
                    ServerSecurityPolicy bestPolicy = null;

                    foreach (ServerSecurityPolicy policy in securityPolicies)
                    {
                        if (bestPolicy == null)
                        {
                            bestPolicy = policy;
                            continue;
                        }

                        if (bestPolicy.SecurityLevel > policy.SecurityLevel)
                        {
                            bestPolicy = policy;
                            continue;
                        }
                    }
                
                    EndpointDescription description = new EndpointDescription();

                    description.EndpointUrl = uri.ToString();
                    description.Server = serverDescription;
                    description.ServerCertificate = InstanceCertificate.RawData;

                    //if (InstanceCertificateChain != null)
                    //{
                    //    List<byte> certificateChainList = new List<byte>();
                    //    for (int i = 0; i < InstanceCertificateChain.Count; i++)
                    //    {
                    //        certificateChainList.AddRange(InstanceCertificateChain[i].RawData);
                    //    }
                    //    description.ServerCertificate = certificateChainList.ToArray();
                    //}
                    
                    description.SecurityMode = bestPolicy.SecurityMode;
                    description.SecurityPolicyUri = bestPolicy.SecurityPolicyUri;
                    description.SecurityLevel = bestPolicy.SecurityLevel;
                    description.UserIdentityTokens = GetUserTokenPolicies(configuration, description);
                    description.TransportProfileUri = Profiles.HttpsBinaryTransport;

                    endpoints.Add(description);

                    // create the endpoint description.
                    description = new EndpointDescription();

                    description.EndpointUrl = uri.ToString();
                    description.Server = serverDescription;
                    description.ServerCertificate = InstanceCertificate.RawData;
                    //if (InstanceCertificateChain != null)
                    //{
                    //    List<byte> certificateChainList = new List<byte>();
                    //    for (int i = 0; i < InstanceCertificateChain.Count; i++)
                    //    {
                    //        certificateChainList.AddRange(InstanceCertificateChain[i].RawData);
                    //    }
                    //    description.ServerCertificate = certificateChainList.ToArray();
                    //}

                    description.SecurityMode = MessageSecurityMode.None;
                    description.SecurityPolicyUri = SecurityPolicies.None;
                    description.SecurityLevel = 0;
                    description.UserIdentityTokens = GetUserTokenPolicies(configuration, description);
                    description.TransportProfileUri = Profiles.HttpsXmlTransport;

                    endpoints.Add(description);
                }

                // create the stack listener.
                try
                {
                    TransportListenerSettings settings = new TransportListenerSettings();

                    settings.Descriptions = endpoints;
                    settings.Configuration = endpointConfiguration;
                    settings.ServerCertificate = this.InstanceCertificate;
                    //settings.ServerCertificateChain = this.InstanceCertificateChain;
                    settings.CertificateValidator = configuration.CertificateValidator.GetChannelValidator();
                    settings.NamespaceUris = this.MessageContext.NamespaceUris;
                    settings.Factory = this.MessageContext.Factory;

                    ITransportListener listener = new Opc.Ua.Bindings.UaHttpsChannelListener();

                    listener.Open(
                       uri.Uri,
                       settings,
                       GetEndpointInstance(this));

                    TransportListeners.Add(listener);
                }
                catch (Exception e)
                {
                    Utils.Trace(e, "Could not load HTTPS Stack Listener.");
					throw;
                }
            }

            return endpoints;
        }
Esempio n. 10
0
        /// <summary>
        /// Finds the best match for the current protocol and security selections.
        /// </summary>
        private EndpointDescription FindBestEndpointDescription(EndpointDescriptionCollection endpoints)
        {
            // filter by the current protocol.
            Protocol currentProtocol = (Protocol)ProtocolCB.SelectedItem;

            // filter by the current security mode.
            MessageSecurityMode currentMode = MessageSecurityMode.None;

            if (SecurityModeCB.SelectedIndex != -1)
            {
                currentMode = (MessageSecurityMode)SecurityModeCB.SelectedItem;
            }

            // filter by the current security policy.
            string currentPolicy = (string)SecurityPolicyCB.SelectedItem;

            // find all matching descriptions.      
            EndpointDescriptionCollection matches = new EndpointDescriptionCollection();

            if (endpoints != null)
            {
                foreach (EndpointDescription endpoint in endpoints)
                {
                    Uri url = Utils.ParseUri(endpoint.EndpointUrl);

                    if (url == null)
                    {
                        continue;
                    }

                    if ((currentProtocol != null) && (!currentProtocol.Matches(url)))
                    {
                        continue;
                    }

                    if (currentMode != endpoint.SecurityMode)
                    {
                        continue;
                    }

                    if (currentPolicy != SecurityPolicies.GetDisplayName(endpoint.SecurityPolicyUri))
                    {
                        continue;
                    }

                    matches.Add(endpoint);
                }
            }

            // check for no matches.
            if (matches.Count == 0)
            {
                return null;
            }

            // check for single match.
            if (matches.Count == 1)
            {
                return matches[0];
            }

            // choose highest priority.
            EndpointDescription bestMatch = matches[0];

            for (int ii = 1; ii < matches.Count; ii++)
            {
                if (bestMatch.SecurityLevel < matches[ii].SecurityLevel)
                {
                    bestMatch = matches[ii];
                }
            }

            return bestMatch;
        }
Esempio n. 11
0
        /// <summary>
        /// Displays the dialog.
        /// </summary>
        public ConfiguredEndpoint ShowDialog(ConfiguredEndpoint endpoint, ApplicationConfiguration configuration)
        {
            if (endpoint == null) throw new ArgumentNullException("endpoint");

            m_endpoint = endpoint;
            m_configuration = configuration;

            // construct a list of available endpoint descriptions for the application.
            m_availableEndpoints = new EndpointDescriptionCollection();
            m_availableEndpointsDescriptions = new List<EndpointDescriptionString>();

            m_availableEndpoints.Add(endpoint.Description);
            m_currentDescription = endpoint.Description;
            m_endpointConfiguration = endpoint.Configuration;

            if (m_endpointConfiguration == null)
            {
                m_endpointConfiguration = EndpointConfiguration.Create(configuration);
            }

            if (endpoint.Collection != null)
            {
                foreach (ConfiguredEndpoint existingEndpoint in endpoint.Collection.Endpoints)
                {
                    if (existingEndpoint.Description.Server.ApplicationUri == endpoint.Description.Server.ApplicationUri)
                    {
                        m_availableEndpoints.Add(existingEndpoint.Description);
                    }
                }
            }

            BuildEndpointDescriptionStrings(m_availableEndpoints);

            UserTokenPolicy policy = m_endpoint.SelectedUserTokenPolicy;

            if (policy == null)
            {
                if (m_endpoint.Description.UserIdentityTokens.Count > 0)
                {
                    policy = m_endpoint.Description.UserIdentityTokens[0];
                }
            }

            if (policy != null)
            {
                UserTokenItem userTokenItem = new UserTokenItem(policy);

                if (policy.TokenType == UserTokenType.UserName && m_endpoint.UserIdentity is UserNameIdentityToken)
                {
                    m_userIdentities[userTokenItem.ToString()] = m_endpoint.UserIdentity;
                }

                if (policy.TokenType == UserTokenType.Certificate && m_endpoint.UserIdentity is X509IdentityToken)
                {
                    m_userIdentities[userTokenItem.ToString()] = m_endpoint.UserIdentity;
                }

                if (policy.TokenType == UserTokenType.IssuedToken && m_endpoint.UserIdentity is IssuedIdentityToken)
                {
                    m_userIdentities[userTokenItem.ToString()] = m_endpoint.UserIdentity;
                }
            }

            // copy com identity.
            m_comIdentity = endpoint.ComIdentity;

            // initializing the protocol will trigger an update to all other controls.
            InitializeProtocols(m_availableEndpoints);

            // check if the current settings match the defaults.
            EndpointConfiguration defaultConfiguration = EndpointConfiguration.Create(configuration);

            // discover endpoints in the background.
            Interlocked.Increment(ref m_discoverCount);
            ThreadPool.QueueUserWorkItem(new WaitCallback(OnDiscoverEndpoints), m_endpoint.Description.Server);

            if (ShowDialog() != DialogResult.OK)
            {
                return null;
            }

            return m_endpoint;
        }
        /// <summary>
        /// Finds the best match for the current protocol and security selections.
        /// </summary>
        private EndpointDescription FindBestEndpointDescription(EndpointDescriptionCollection endpoints)
        {
            // filter by the current protocol.
            string currentProtocol = (string)ProtocolCB.SelectedItem;

            // filter by the current security mode.
            MessageSecurityMode currentMode = MessageSecurityMode.None;

            if (SecurityModeCB.SelectedIndex != -1)
            {
                currentMode = (MessageSecurityMode)SecurityModeCB.SelectedItem;
            }

            // filter by the current security policy.
            string currentPolicy = (string)SecurityPolicyCB.SelectedItem;

            // find all matching descriptions.
            EndpointDescriptionCollection matches = new EndpointDescriptionCollection();

            if (endpoints != null)
            {
                foreach (EndpointDescription endpoint in endpoints)
                {
                    Uri url = Utils.ParseUri(endpoint.EndpointUrl);

                    if (url == null)
                    {
                        continue;
                    }

                    if (currentProtocol != url.Scheme)
                    {
                        continue;
                    }

                    if (currentMode != endpoint.SecurityMode)
                    {
                        continue;
                    }

                    if (currentPolicy != SecurityPolicies.GetDisplayName(endpoint.SecurityPolicyUri))
                    {
                        continue;
                    }

                    matches.Add(endpoint);
                }
            }

            // check for no matches.
            if (matches.Count == 0)
            {
                return(null);
            }

            // check for single match.
            if (matches.Count == 1)
            {
                return(matches[0]);
            }

            // choose highest priority.
            EndpointDescription bestMatch = matches[0];

            for (int ii = 1; ii < matches.Count; ii++)
            {
                if (bestMatch.SecurityLevel < matches[ii].SecurityLevel)
                {
                    bestMatch = matches[ii];
                }
            }

            return(bestMatch);
        }
        /// <summary>
        /// Displays the dialog.
        /// </summary>
        public ConfiguredEndpoint ShowDialog(ConfiguredEndpoint endpoint, ApplicationConfiguration configuration)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException("endpoint");
            }

            m_endpoint      = endpoint;
            m_configuration = configuration;

            // construct a list of available endpoint descriptions for the application.
            m_availableEndpoints = new EndpointDescriptionCollection();

            m_availableEndpoints.Add(endpoint.Description);
            m_currentDescription    = endpoint.Description;
            m_endpointConfiguration = endpoint.Configuration;

            if (m_endpointConfiguration == null)
            {
                m_endpointConfiguration = EndpointConfiguration.Create(configuration);
            }

            if (endpoint.Collection != null)
            {
                foreach (ConfiguredEndpoint existingEndpoint in endpoint.Collection.Endpoints)
                {
                    if (existingEndpoint.Description.Server.ApplicationUri == endpoint.Description.Server.ApplicationUri)
                    {
                        m_availableEndpoints.Add(existingEndpoint.Description);
                    }
                }
            }

            // copy user identity.
            if (endpoint.UserIdentity != null)
            {
                UserTokenType tokenType = UserTokenType.Anonymous;

                if (endpoint.UserIdentity is UserNameIdentityToken)
                {
                    tokenType = UserTokenType.UserName;
                }
                else if (endpoint.UserIdentity is X509IdentityToken)
                {
                    tokenType = UserTokenType.Certificate;
                }
                else if (endpoint.UserIdentity is IssuedIdentityToken)
                {
                    tokenType = UserTokenType.IssuedToken;
                }

                m_userIdentities[tokenType] = endpoint.UserIdentity;
            }

            // copy com identity.
            m_comIdentity = endpoint.ComIdentity;

            // initializing the protocol will trigger an update to all other controls.
            InitializeProtocols(m_availableEndpoints);

            // check if the current settings match the defaults.
            EndpointConfiguration defaultConfiguration = EndpointConfiguration.Create(configuration);

            if (SameAsDefaults(defaultConfiguration, m_endpoint.Configuration))
            {
                UseDefaultLimitsCB.SelectedItem = UseDefaultLimits.Yes;
            }
            else
            {
                UseDefaultLimitsCB.SelectedItem = UseDefaultLimits.No;
            }

            // discover endpoints in the background.
            Interlocked.Increment(ref m_discoverCount);
            ThreadPool.QueueUserWorkItem(new WaitCallback(OnDiscoverEndpoints), m_endpoint.Description.Server);

            if (ShowDialog() != DialogResult.OK)
            {
                return(null);
            }

            return(m_endpoint);
        }
        /// <summary>
        /// Displays the dialog.
        /// </summary>
        public async Task<ConfiguredEndpoint> ShowDialog(ConfiguredEndpoint endpoint, ApplicationConfiguration configuration)
        {
            if (endpoint == null) throw new ArgumentNullException("endpoint");

            m_endpoint = endpoint;
            m_configuration = configuration;

            // construct a list of available endpoint descriptions for the application.
            m_availableEndpoints = new EndpointDescriptionCollection();

            m_availableEndpoints.Add(endpoint.Description);
            m_currentDescription = endpoint.Description;
            m_endpointConfiguration = endpoint.Configuration;

            if (m_endpointConfiguration == null)
            {
                m_endpointConfiguration = EndpointConfiguration.Create(configuration);
            }

            if (endpoint.Collection != null)
            {
                foreach (ConfiguredEndpoint existingEndpoint in endpoint.Collection.Endpoints)
                {
                    if (existingEndpoint.Description.Server.ApplicationUri == endpoint.Description.Server.ApplicationUri)
                    {
                        m_availableEndpoints.Add(existingEndpoint.Description);
                    }
                }
            }

            UserTokenPolicy policy = m_endpoint.SelectedUserTokenPolicy;

            if (policy == null)
            {
                if (m_endpoint.Description.UserIdentityTokens.Count > 0)
                {
                    policy = m_endpoint.Description.UserIdentityTokens[0];
                }
            }

            if (policy != null)
            {
                UserTokenItem userTokenItem = new UserTokenItem(policy);

                if (policy.TokenType == UserTokenType.UserName && m_endpoint.UserIdentity is UserNameIdentityToken)
                {
                    m_userIdentities[userTokenItem.ToString()] = m_endpoint.UserIdentity;
                }

                if (policy.TokenType == UserTokenType.Certificate && m_endpoint.UserIdentity is X509IdentityToken)
                {
                    m_userIdentities[userTokenItem.ToString()] = m_endpoint.UserIdentity;
                }

                if (policy.TokenType == UserTokenType.IssuedToken && m_endpoint.UserIdentity is IssuedIdentityToken)
                {
                    m_userIdentities[userTokenItem.ToString()] = m_endpoint.UserIdentity;
                }

                UserTokenTypeCB.Items.Add(userTokenItem);
                UserTokenTypeCB.SelectedIndex = UserTokenTypeCB.Items.IndexOf(userTokenItem);
            }

            // copy com identity.
            m_comIdentity = endpoint.ComIdentity;

            // initializing the protocol will trigger an update to all other controls.
            InitializeProtocols(m_availableEndpoints);

            // check if the current settings match the defaults.
            EndpointConfiguration defaultConfiguration = EndpointConfiguration.Create(configuration);

            if (SameAsDefaults(defaultConfiguration, m_endpoint.Configuration))
            {
                UseDefaultLimitsCB.SelectedIndex = (int)UseDefaultLimits.Yes;
            }
            else
            {
                UseDefaultLimitsCB.SelectedIndex = (int)UseDefaultLimits.No;
            }

            // discover endpoints in the background.
            Interlocked.Increment(ref m_discoverCount);
            OnDiscoverEndpoints(m_endpoint.Description.Server);

            TaskCompletionSource<ConfiguredEndpoint> tcs = new TaskCompletionSource<ConfiguredEndpoint>();
            // display dialog
            dialogPopup.Child = this;
            dialogPopup.IsOpen = true;
            dialogPopup.Closed += (o, e) =>
            {
                tcs.SetResult(m_endpoint);
            };
            return await tcs.Task;
        }