Example #1
0
        public static List <List <string> > GetEndpoints(Uri uri)
        {
            using (DiscoveryClient client = DiscoveryClient.Create(uri))
            {
                var lst = new List <List <string> >();

                EndpointDescriptionCollection endpoints = client.GetEndpoints(null);

                if (endpoints.Count > 0)
                {
                    StringBuilder[] arrStrBuilder = new StringBuilder[endpoints.Count];
                    List <string>[] arrList       = new List <string> [endpoints.Count];

                    for (int ii = 0; ii < endpoints.Count; ii++)
                    {
                        arrList[ii] = new List <string>();
                        arrList[ii].Add(endpoints[ii].EndpointUrl);
                        arrList[ii].Add(endpoints[ii].SecurityPolicyUri.Substring(
                                            endpoints[ii].SecurityPolicyUri.LastIndexOf('#') + 1));
                        arrList[ii].Add(endpoints[ii].SecurityMode.ToString()); // [None, Sign, SignAndEncrypt]
                        lst.Add(arrList[ii]);
                    }
                }

                return(lst);
            }
        }
Example #2
0
        /// <summary>
        /// Creates the endpoints and creates the hosts.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="bindingFactory">The binding factory.</param>
        /// <param name="serverDescription">The server description.</param>
        /// <param name="endpoints">The endpoints.</param>
        /// <returns>
        /// Returns IList of a host for a UA service which type is <seealso cref="ServiceHost"/>.
        /// </returns>
        protected override IList <Task> InitializeServiceHosts(
            ApplicationConfiguration configuration,
            out ApplicationDescription serverDescription,
            out EndpointDescriptionCollection endpoints)
        {
            serverDescription = null;
            endpoints         = null;

            Dictionary <string, Task> hosts = new Dictionary <string, Task>();

            // ensure at least one security policy exists.
            if (configuration.ServerConfiguration.SecurityPolicies.Count == 0)
            {
                configuration.ServerConfiguration.SecurityPolicies.Add(new ServerSecurityPolicy());
            }

            // ensure at least one user token policy exists.
            if (configuration.ServerConfiguration.UserTokenPolicies.Count == 0)
            {
                UserTokenPolicy userTokenPolicy = new UserTokenPolicy();

                userTokenPolicy.TokenType = UserTokenType.Anonymous;
                userTokenPolicy.PolicyId  = userTokenPolicy.TokenType.ToString();

                configuration.ServerConfiguration.UserTokenPolicies.Add(userTokenPolicy);
            }

            // set server description.
            serverDescription = new ApplicationDescription();

            serverDescription.ApplicationUri  = configuration.ApplicationUri;
            serverDescription.ApplicationName = new LocalizedText("en-US", configuration.ApplicationName);
            serverDescription.ApplicationType = configuration.ApplicationType;
            serverDescription.ProductUri      = configuration.ProductUri;
            serverDescription.DiscoveryUrls   = GetDiscoveryUrls();

            endpoints = new EndpointDescriptionCollection();
            IList <EndpointDescription> endpointsForHost = null;

            // create UA TCP host.
            endpointsForHost = CreateUaTcpServiceHost(
                hosts,
                configuration,
                configuration.ServerConfiguration.BaseAddresses,
                serverDescription,
                configuration.ServerConfiguration.SecurityPolicies);

            endpoints.InsertRange(0, endpointsForHost);

            // create HTTPS host.
            endpointsForHost = CreateHttpsServiceHost(
                hosts,
                configuration,
                configuration.ServerConfiguration.BaseAddresses,
                serverDescription,
                configuration.ServerConfiguration.SecurityPolicies);

            endpoints.AddRange(endpointsForHost);
            return(new List <Task>(hosts.Values));
        }
Example #3
0
        public List <EndpointDes> FindServer(string serverUrl)
        {
            List <EndpointDes> endpointListView = new List <EndpointDes>();

            _EndpointDescriptions.Clear();
            ApplicationDescriptionCollection servers = uAClient.FindServers(serverUrl);

            foreach (ApplicationDescription ad in servers)
            {
                foreach (string url in ad.DiscoveryUrls)
                {
                    EndpointDescriptionCollection endpoints = uAClient.GetEndpoints(url);
                    foreach (EndpointDescription ep in endpoints)
                    {
                        string      securityPolicy = ep.SecurityPolicyUri.Remove(0, 42);
                        EndpointDes endpointDes    = new EndpointDes()
                        {
                            ID                     = Guid.NewGuid().ToString(),
                            Description            = "[" + ad.ApplicationName + "] " + " [" + ep.SecurityMode + "] " + " [" + securityPolicy + "] " + " [" + ep.EndpointUrl + "]",
                            OpcEndpointDescription = ep
                        };
                        endpointListView.Add(endpointDes);
                        _EndpointDescriptions.Add(endpointDes.ID, endpointDes);
                    }
                }
            }
            return(endpointListView);
        }
Example #4
0
        private List <EndpointDescription> ListEndpoints(string serverUrl)
        {
            List <EndpointDescription> endPointsList = new List <EndpointDescription>();

            try
            {
                ApplicationDescriptionCollection servers = FindServers(serverUrl);

                foreach (ApplicationDescription ad in servers)
                {
                    foreach (string url in ad.DiscoveryUrls)
                    {
                        EndpointDescriptionCollection endpoints = GetEndpoints(url);
                        foreach (EndpointDescription ep in endpoints)
                        {
                            endPointsList.Add(ep);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                endPointsList?.Clear();
                endPointsList = null;
                System.Diagnostics.Debug.WriteLine("OpcUaClient::ListEndpoints" + ex.Message);
            }

            return(endPointsList);
        }
        /// <summary>
        /// Fetches the servers from the discovery server.
        /// </summary>
        private bool DiscoverEndpoints(Uri discoveryUrl)
        {
            // use a short timeout.
            EndpointConfiguration configuration = EndpointConfiguration.Create(m_configuration);

            configuration.OperationTimeout = m_discoveryTimeout;

            DiscoveryClient client = DiscoveryClient.Create(
                discoveryUrl,
                BindingFactory.Create(m_configuration, m_configuration.CreateMessageContext()),
                EndpointConfiguration.Create(m_configuration));

            try
            {
                EndpointDescriptionCollection endpoints = client.GetEndpoints(null);
                OnUpdateEndpoints(endpoints);
                return(true);
            }
            catch (Exception e)
            {
                Utils.Trace("Could not fetch endpoints from url: {0}. Reason={1}", discoveryUrl, e.Message);
                return(false);
            }
            finally
            {
                client.Close();
            }
        }
Example #6
0
        /// <summary>
        /// Starts OPC UA server.
        /// </summary>
        private async Task StartOpcServer()
        {
            await opcApp.Start(opcServer);

            StringBuilder sbStartInfo = new StringBuilder("OPC UA server started");
            EndpointDescriptionCollection endpoints = opcServer.GetEndpoints();

            if (endpoints.Count > 0)
            {
                // print endpoint info
                foreach (string endpointUrl in endpoints.Select(e => e.EndpointUrl).Distinct())
                {
                    sbStartInfo.AppendLine().Append("    ").Append(endpointUrl);
                }
            }
            else
            {
                sbStartInfo.AppendLine().Append("    No endpoints");
            }

            dsLog.WriteAction(sbStartInfo.ToString());

            // add event handlers
            ISessionManager sessionManager = opcServer.CurrentInstance.SessionManager;

            sessionManager.SessionActivated += SessionManager_SessionEvent;
            sessionManager.SessionClosing   += SessionManager_SessionEvent;
            sessionManager.SessionCreated   += SessionManager_SessionEvent;

            ISubscriptionManager subscriptionManager = opcServer.CurrentInstance.SubscriptionManager;

            subscriptionManager.SubscriptionCreated += SubscriptionManager_SubscriptionEvent;
            subscriptionManager.SubscriptionDeleted += SubscriptionManager_SubscriptionEvent;
        }
Example #7
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);
        }
Example #8
0
        private void EndpointButton_Click(object sender, EventArgs e)
        {
            endpointListView.Items.Clear();
            //The local discovery URL for the discovery server
            string discoveryUrl = discoveryTextBox.Text;

            try
            {
                ApplicationDescriptionCollection servers = myClientHelperAPI.FindServers(discoveryUrl);
                foreach (ApplicationDescription ad in servers)
                {
                    foreach (string url in ad.DiscoveryUrls)
                    {
                        EndpointDescriptionCollection endpoints = myClientHelperAPI.GetEndpoints(url);
                        foreach (EndpointDescription ep in endpoints)
                        {
                            string securityPolicy = ep.SecurityPolicyUri.Remove(0, 42);
                            endpointListView.Items.Add("[" + ad.ApplicationName + "] " + " [" + ep.SecurityMode + "] " + " [" + securityPolicy + "] " + " [" + ep.EndpointUrl + "]").Tag = ep;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (BGW_OPCUA.IsBusy)
                {
                    BGW_OPCUA.CancelAsync();
                }
                MessageBox.Show(ex.Message, "Error");
            }
        }
        /// <summary>
        /// Patch returned endpoints urls with url used to reached the endpoint.
        /// </summary>
        private EndpointDescriptionCollection PatchEndpointUrls(EndpointDescriptionCollection endpoints)
        {
            // if a server is behind a firewall, can only be accessed with a FQDN or IP address
            // it may return URLs that are not accessible to the client. This problem can be avoided
            // by assuming that the domain in the URL used to call GetEndpoints can be used to
            // access any of the endpoints. This code patches the returned endpoints accordingly.
            Uri endpointUrl = Utils.ParseUri(this.Endpoint.EndpointUrl);

            if (endpointUrl != null)
            {
                // patch discovery Url to endpoint Url used for service call
                foreach (EndpointDescription discoveryEndPoint in endpoints)
                {
                    Uri discoveryEndPointUri = Utils.ParseUri(discoveryEndPoint.EndpointUrl);
                    if (endpointUrl.Scheme == discoveryEndPointUri.Scheme)
                    {
                        UriBuilder builder = new UriBuilder(discoveryEndPointUri);
                        builder.Host = endpointUrl.DnsSafeHost;
                        builder.Port = endpointUrl.Port;
                        discoveryEndPoint.EndpointUrl = builder.ToString();
                    }

                    if (discoveryEndPoint.Server != null &&
                        discoveryEndPoint.Server.DiscoveryUrls != null)
                    {
                        discoveryEndPoint.Server.DiscoveryUrls.Clear();
                        discoveryEndPoint.Server.DiscoveryUrls.Add(this.Endpoint.EndpointUrl.ToString());
                    }
                }
            }
            return(endpoints);
        }
Example #10
0
        private EndpointDescriptionCollection DiscoverEndpoints(ApplicationConfiguration config, Uri discoveryUrl, int timeout)
        {
            // use a short timeout.
            EndpointConfiguration configuration = EndpointConfiguration.Create(config);

            configuration.OperationTimeout = timeout;

            using (DiscoveryClient client = DiscoveryClient.Create(
                       discoveryUrl,
                       EndpointConfiguration.Create(config)))
            {
                try
                {
                    EndpointDescriptionCollection endpoints = client.GetEndpoints(null);
                    ReplaceLocalHostWithRemoteHost(endpoints, discoveryUrl);
                    return(endpoints);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Не удалось найти OPC-сервер по адресу: {discoveryUrl}");
                    Console.WriteLine($"Ошибка = {e.Message}");
                    throw e;
                }
            }
        }
        /// <summary>
        /// Displays the dialog.
        /// </summary>
        public ConfiguredEndpoint ShowDialog(ApplicationDescription server, ApplicationConfiguration configuration)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }

            m_configuration = configuration;

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

            // create a default endpoint description.
            m_endpoint           = null;
            m_currentDescription = null;

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

            UseDefaultLimitsCB.SelectedItem = UseDefaultLimits.Yes;

            // discover endpoints in the background.
            m_discoverySucceeded = false;
            Interlocked.Increment(ref m_discoverCount);
            ThreadPool.QueueUserWorkItem(new WaitCallback(OnDiscoverEndpoints), server);

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

            return(m_endpoint);
        }
Example #12
0
        private static EndpointDescriptionCollection DiscoverEndpoints(ApplicationConfiguration config, Uri discoveryUrl, int timeout)
        {
            // use a short timeout.
            EndpointConfiguration configuration = EndpointConfiguration.Create(config);

            configuration.OperationTimeout = timeout;

            using (DiscoveryClient client = DiscoveryClient.Create(
                       discoveryUrl,
                       EndpointConfiguration.Create(config)))
            {
                try
                {
                    EndpointDescriptionCollection endpoints = client.GetEndpoints(null);
                    ReplaceLocalHostWithRemoteHost(endpoints, discoveryUrl);
                    return(endpoints);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Could not fetch endpoints from url: {0}", discoveryUrl);
                    Console.WriteLine("Reason = {0}", e.Message);
                    throw e;
                }
            }
        }
Example #13
0
        private void DiscoveryB_Click(object sender, EventArgs e)
        {
            bool foundEndpoints = false;

            DiscoveredServersLV.Items.Clear();

            //Create discovery URL for the discovery client
            string serverUrl = null;

            if (!String.IsNullOrEmpty(DiscoveryUrlTB.Text) & !String.IsNullOrEmpty(DiscoveryPortTB.Text))
            {
                serverUrl = "opc.tcp://" + DiscoveryUrlTB.Text + ":" + DiscoveryPortTB.Text;
            }
            else if (String.IsNullOrEmpty(DiscoveryUrlTB.Text) & !String.IsNullOrEmpty(DiscoveryPortTB.Text))
            {
                serverUrl = "opc.tcp://localhost:" + DiscoveryPortTB.Text;
            }
            else if (!String.IsNullOrEmpty(DiscoveryUrlTB.Text) & String.IsNullOrEmpty(DiscoveryPortTB.Text))
            {
                serverUrl = "opc.tcp://" + DiscoveryUrlTB.Text + ":" + "4840";
            }
            else
            {
                serverUrl = "opc.tcp://localhost:4840";
            }

            //Get the endpoints
            try
            {
                ApplicationDescriptionCollection servers = myHelperApi.FindServers(serverUrl);
                foreach (ApplicationDescription ad in servers)
                {
                    foreach (string url in ad.DiscoveryUrls)
                    {
                        EndpointDescriptionCollection endpoints = myHelperApi.GetEndpoints(url);
                        foundEndpoints = foundEndpoints || endpoints.Count > 0;
                        foreach (EndpointDescription ep in endpoints)
                        {
                            string securityPolicy = ep.SecurityPolicyUri.Remove(0, 43);
                            if (!DiscoveredServersLV.Items.ContainsKey(ep.Server.ApplicationName.Text))
                            {
                                string[]     row          = { ep.Server.ApplicationName.Text, ep.EndpointUrl, ep.SecurityMode + "-" + securityPolicy };
                                ListViewItem listViewItem = new ListViewItem(row);
                                DiscoveredServersLV.Items.Add(listViewItem).Tag = ep;
                                DiscoveredServersLV.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
                            }
                        }
                    }
                    if (!foundEndpoints)
                    {
                        MessageBox.Show("Could not get any Endpoints", "Error");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }
        /// <summary>
        /// Initializes the protocol dropdown.
        /// </summary>
        private void InitializeProtocols(EndpointDescriptionCollection endpoints)
        {
            // preserve the existing value.
            string currentProtocol = (string)ProtocolCB.SelectedItem;

            ProtocolCB.Items.Clear();

            // set all available protocols.
            if (m_showAllOptions)
            {
                ProtocolCB.Items.Add(Utils.UriSchemeHttp);
                ProtocolCB.Items.Add(Utils.UriSchemeOpcTcp);
            }

            // find all unique protocols.
            else
            {
                if (endpoints != null)
                {
                    foreach (EndpointDescription endpoint in endpoints)
                    {
                        Uri url = Utils.ParseUri(endpoint.EndpointUrl);

                        if (url != null)
                        {
                            int existingIndex = ProtocolCB.FindStringExact(url.Scheme);

                            if (existingIndex == -1)
                            {
                                ProtocolCB.Items.Add(url.Scheme);
                            }
                        }
                    }
                }

                // add at least one protocol.
                if (ProtocolCB.Items.Count == 0)
                {
                    ProtocolCB.Items.Add(Utils.UriSchemeHttp);
                }
            }

            // set the current value.
            int index = 0;

            if (!String.IsNullOrEmpty(currentProtocol))
            {
                index = ProtocolCB.FindStringExact(currentProtocol);

                if (index == -1)
                {
                    index = 0;
                }
            }

            ProtocolCB.SelectedIndex = index;
        }
Example #15
0
 /// <summary>
 /// Creates the endpoints and creates the hosts.
 /// </summary>
 /// <param name="configuration">The object that stores the configurable configuration information for a UA application.</param>
 /// <param name="serverDescription">The object of the class that contains a description for the ApplicationDescription DataType.</param>
 /// <param name="endpoints">The collection of <see cref="EndpointDescription"/> objects.</param>
 /// <returns>Returns list of hosts for a UA service.</returns>
 protected virtual IList <Task> InitializeServiceHosts(
     ApplicationConfiguration configuration,
     out ApplicationDescription serverDescription,
     out EndpointDescriptionCollection endpoints)
 {
     serverDescription = null;
     endpoints         = null;
     return(new List <Task>());
 }
Example #16
0
 /// <summary>
 /// Create channel
 /// </summary>
 /// <param name="contextId"></param>
 /// <param name="listener"></param>
 /// <param name="bufferManager"></param>
 /// <param name="quotas"></param>
 /// <param name="serverCertificate"></param>
 /// <param name="serverCertificateChain"></param>
 /// <param name="endpoints"></param>
 public SecureChannel(string contextId, ITcpChannelListener listener,
                      BufferManager bufferManager, ChannelQuotas quotas,
                      X509Certificate2 serverCertificate,
                      X509Certificate2Collection serverCertificateChain,
                      EndpointDescriptionCollection endpoints) :
     base(contextId, listener, bufferManager, quotas, serverCertificate,
          serverCertificateChain, endpoints)
 {
     _endpoints = endpoints;
 }
Example #17
0
 /// <summary>
 /// Attaches the object to an existing socket.
 /// </summary>
 public TcpReverseConnectChannel(
     string contextId,
     ITcpChannelListener listener,
     BufferManager bufferManager,
     ChannelQuotas quotas,
     EndpointDescriptionCollection endpoints)
     :
     base(contextId, listener, bufferManager, quotas, null, null, endpoints)
 {
 }
Example #18
0
 /// <summary>
 /// Attaches the object to an existing socket.
 /// </summary>
 public TcpListenerChannel(
     string contextId,
     ITcpChannelListener listener,
     BufferManager bufferManager,
     ChannelQuotas quotas,
     X509Certificate2 serverCertificate,
     EndpointDescriptionCollection endpoints)
     :
     this(contextId, listener, bufferManager, quotas, serverCertificate, null, endpoints)
 {
 }
Example #19
0
        /// <summary>
        /// Starts the server (called from a IIS host process).
        /// </summary>
        /// <param name="configuration">The object that stores the configurable configuration information
        /// for a UA application</param>
        /// <param name="baseAddresses">The array of Uri elements which contains base addresses.</param>
        /// <returns>Returns a host for a UA service.</returns>
        public Task Start(ApplicationConfiguration configuration, params Uri[] baseAddresses)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            // do any pre-startup processing
            OnServerStarting(configuration);

            // intialize the request queue from the configuration.
            InitializeRequestQueue(configuration);

            // initialize the server capabilities
            ServerCapabilities = configuration.ServerConfiguration.ServerCapabilities;

            // initialize the base addresses.
            InitializeBaseAddresses(configuration);

            // initialize the hosts.
            ApplicationDescription        serverDescription = null;
            EndpointDescriptionCollection endpoints         = null;

            IList <Task> hosts = InitializeServiceHosts(
                configuration,
                out serverDescription,
                out endpoints);

            // save discovery information.
            ServerDescription = serverDescription;
            m_endpoints       = new ReadOnlyList <EndpointDescription>(endpoints);

            // start the application.
            StartApplication(configuration);

            // the configuration file may specify multiple security policies or non-HTTP protocols
            // which will require multiple service hosts. the default host will be opened by WCF when
            // it is returned from this function. The others must be opened here.

            if (hosts == null || hosts.Count == 0)
            {
                throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "The UA server does not have a default host.");
            }

            lock (m_hosts)
            {
                for (int ii = 1; ii < hosts.Count; ii++)
                {
                    m_hosts.Add(hosts[ii]);
                }
            }

            return(hosts[0]);
        }
Example #20
0
        public int Connect()
        {
            try
            {
                List <object> Listtmp = new List <object>();
                ApplicationDescriptionCollection servers = null;
                servers = m_Server.FindServers(discoveryUrl.ToString());
                //for (int i = 0; i < servers.Count; i++)
                //{

                //    // Create discovery client and get the available endpoints.
                EndpointDescriptionCollection endpoints = null;
                //    string sUrl;
                //    sUrl = servers[i].DiscoveryUrls[0];
                //    discoveryUrl = new Uri(sUrl);
                endpoints = m_Server.GetEndpoints(discoveryUrl.ToString());
                // Create wrapper and fill the combobox.

                for (int j = 0; j < endpoints.Count; j++)
                {
                    // Create endpoint wrapper.
                    EndpointWrapper wrapper = new EndpointWrapper(endpoints[j]);
                    Listtmp.Add(wrapper);
                    // Add it to the combobox.
                    // UrlCB.Items.Add(wrapper);
                }
                if (Listtmp != null)
                {
                    // Call connect with URL
                    //m_Server.Connect(Listtmp[0].ToString(), "none", MessageSecurityMode.None, false, "", "");
                    m_Server.Connect(((EndpointWrapper)Listtmp[0]).Endpoint, false, "", "");
                }
                else
                {
                    m_Connected = false;
                    return(-1);
                }
                //}
                //servers[i].ApplicationName;
                m_Connected = true;
                return(0);
            }
            catch
            {
                //MessageBox.Show(ex.Message);
                if (m_Connected)
                {
                    // Disconnect from server.
                    Disconnect();
                }
                m_Connected = false;
                return(-1);
            }
        }
        //private EndpointDescription CreateEndpointDescription(string url, string secPolicy, MessageSecurityMode msgSecMode)
        //{
        //    // create the endpoint description.
        //    EndpointDescription endpointDescription = new EndpointDescription();

        //    // submit the url of the endopoint
        //    endpointDescription.EndpointUrl = url;

        //    // specify the security policy to use.
        //    endpointDescription.SecurityPolicyUri = secPolicy;
        //    endpointDescription.SecurityMode = msgSecMode;
        //    // specify the transport profile.
        //    endpointDescription.TransportProfileUri = Profiles.UaTcpTransport;
        //    return endpointDescription;
        //}

        //url="opc.tcp://192.168.0.15:4840"
        private EndpointDescription getEndpointDescription(string url)
        {
            EndpointDescription           ret       = null;
            EndpointDescriptionCollection endpoints = myClientHelperAPI.GetEndpoints(url);

            if (endpoints != null && endpoints.Count > 0)
            {
                ret = endpoints[0];
            }
            return(ret);
        }
Example #22
0
        public async Task GetEndpoints()
        {
            var endpointConfiguration = EndpointConfiguration.Create();

            endpointConfiguration.OperationTimeout = 10000;

            using (var client = DiscoveryClient.Create(m_url, endpointConfiguration))
            {
                m_endpoints = await client.GetEndpointsAsync(null).ConfigureAwait(false);
            }
        }
 /// <summary>
 /// Attaches the object to an existing socket.
 /// </summary>
 public UaSCUaBinaryChannel(
     string contextId,
     BufferManager bufferManager,
     ChannelQuotas quotas,
     X509Certificate2 serverCertificate,
     EndpointDescriptionCollection endpoints,
     MessageSecurityMode securityMode,
     string securityPolicyUri)
     :
     this(contextId, bufferManager, quotas, serverCertificate, null, endpoints, securityMode, securityPolicyUri)
 {
 }
Example #24
0
 protected void GetEnpoints_Click(object sender, EventArgs e)
 {
     if (discoveryTextBox.Text != "")
     {
         bool foundEndpoints = false;
         endpointListView.Items.Clear();
         Session["Urltext"] = discoveryTextBox.Text;
         //The local discovery URL for the discovery server
         string discoveryUrl = discoveryTextBox.Text;
         try
         {
             ApplicationDescriptionCollection servers = myClientHelperAPI.FindServers(discoveryUrl);
             foreach (ApplicationDescription ad in servers)
             {
                 foreach (string url in ad.DiscoveryUrls)
                 {
                     try
                     {
                         EndpointDescriptionCollection endpoints = myClientHelperAPI.GetEndpoints(url);
                         foundEndpoints = foundEndpoints || endpoints.Count > 0;
                         List <string> enps = new List <string>();
                         foreach (EndpointDescription ep in endpoints)
                         {
                             string securityPolicy = ep.SecurityPolicyUri.Remove(0, 42);
                             string key            = "[" + ad.ApplicationName + "] " + " [" + ep.SecurityMode + "] " + " [" + securityPolicy + "] " + " [" + ep.EndpointUrl + "]";
                             enps.Add(key);
                             endpointListView.Items.Add(key);
                         }
                         Session["endpointlist"] = enps;
                     }
                     catch (ServiceResultException sre)
                     {
                         //If an url in ad.DiscoveryUrls can not be reached, myClientHelperAPI will throw an Exception
                         ClientScript.RegisterStartupScript(this.GetType(), "Alert", "mess('error','Oops...'," + sre.ToString() + ")", true);
                     }
                 }
                 if (!foundEndpoints)
                 {
                     ClientScript.RegisterStartupScript(this.GetType(), "Alert", "mess('warning','Oops...','Could not get any Endpoints!')", true);
                 }
             }
         }
         catch (Exception ex)
         {
             ClientScript.RegisterStartupScript(this.GetType(), "Alert", "mess('error','Oops...'," + ex.ToString() + ")", true);
         }
     }
     else
     {
         ClientScript.RegisterStartupScript(this.GetType(), "Alert", "mess('warning','Warning...','You forget write endpoint Url!')", true);
     }
 }
 /// <summary>
 /// Attaches the object to an existing socket.
 /// </summary>
 public TcpServerChannel(
     string                        contextId,
     UaTcpChannelListener          listener,
     BufferManager                 bufferManager, 
     TcpChannelQuotas              quotas,
     X509Certificate2              serverCertificate, 
     EndpointDescriptionCollection endpoints)
 :
     base(contextId, bufferManager, quotas, serverCertificate, endpoints, MessageSecurityMode.None, SecurityPolicies.None)
 {
     m_listener = listener;
     m_queuedResponses = new SortedDictionary<uint,IServiceResponse>();
 }
Example #26
0
 private static void ReplaceLocalHostWithRemoteHost(EndpointDescriptionCollection endpoints, Uri discoveryUrl)
 {
     foreach (EndpointDescription endpoint in endpoints)
     {
         endpoint.EndpointUrl = Utils.ReplaceLocalhost(endpoint.EndpointUrl, discoveryUrl.DnsSafeHost);
         StringCollection updatedDiscoveryUrls = new StringCollection();
         foreach (string url in endpoint.Server.DiscoveryUrls)
         {
             updatedDiscoveryUrls.Add(Utils.ReplaceLocalhost(url, discoveryUrl.DnsSafeHost));
         }
         endpoint.Server.DiscoveryUrls = updatedDiscoveryUrls;
     }
 }
Example #27
0
 /// <summary>
 /// Attaches the object to an existing socket.
 /// </summary>
 public TcpServerChannel(
     string contextId,
     UaTcpChannelListener listener,
     BufferManager bufferManager,
     TcpChannelQuotas quotas,
     X509Certificate2 serverCertificate,
     EndpointDescriptionCollection endpoints)
     :
     base(contextId, bufferManager, quotas, serverCertificate, endpoints, MessageSecurityMode.None, SecurityPolicies.None)
 {
     m_listener        = listener;
     m_queuedResponses = new SortedDictionary <uint, IServiceResponse>();
 }
        /// <summary>
        /// Invokes the GetEndpoints service.
        /// </summary>
        /// <param name="profileUris">The collection of profile URIs.</param>
        /// <returns></returns>
        public virtual EndpointDescriptionCollection GetEndpoints(StringCollection profileUris)
        {
            EndpointDescriptionCollection endpoints = null;

            GetEndpoints(
                null,
                this.Endpoint.EndpointUrl,
                null,
                profileUris,
                out endpoints);

            return(PatchEndpointUrls(endpoints));
        }
Example #29
0
        private async Task MainTask()
        {
            ApplicationInstance application = new ApplicationInstance
            {
                ApplicationName   = "UA Console Client",
                ApplicationType   = ApplicationType.Client,
                ConfigSectionName = "UaConsoleClient"
            };

            // load the application configuration.
            ApplicationConfiguration config = await application.LoadApplicationConfiguration(false);

            // check the application certificate.
            bool haveAppCertificate = await application.CheckApplicationInstanceCertificate(false, 0);

            if (!haveAppCertificate)
            {
                throw new Exception("Application instance certificate invalid!");
            }

            if (haveAppCertificate)
            {
                config.ApplicationUri = Utils.GetApplicationUriFromCertificate(config.SecurityConfiguration.ApplicationCertificate.Certificate);
                if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates)
                {
                    autoAccept = true;
                }
                config.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation);
            }
            else
            {
                Console.WriteLine("    WARN: missing application certificate, using unsecure connection.");
            }

            using (DiscoveryClient client = DiscoveryClient.Create(new Uri("opc.tcp://localhost:4840")))
            {
                EndpointDescriptionCollection endpoints = client.GetEndpoints(null);

                for (int ii = 0; ii < endpoints.Count; ii++)
                {
                    Console.WriteLine("Endpoint #{0}:", ii);
                    Console.WriteLine(endpoints[ii].EndpointUrl);
                    Console.WriteLine(endpoints[ii].SecurityPolicyUri.Substring(
                                          endpoints[ii].SecurityPolicyUri.LastIndexOf('#') + 1));
                    Console.WriteLine(endpoints[ii].SecurityMode.ToString()); // [None, Sign, SignAndEncrypt]
                }
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Example #30
0
        /// <summary>
        /// Reads the endpoints for a server.
        /// </summary>
        private ConfiguredEndpointCollection GetEndpoints(ConfiguredEndpoint endpoint)
        {
            // some protocols will require a seperate endpoint for the discovery endpoints.
            List <Uri> urlsToTry = new List <Uri>();

            foreach (string discoveryUrl in endpoint.Description.Server.DiscoveryUrls)
            {
                urlsToTry.Add(new Uri(discoveryUrl));
            }

            urlsToTry.Add(endpoint.EndpointUrl);

            // servers that do not support using the same endpoint for discovery and sessions should
            // use the convention where the discovery endpoint is constructed by appending "/discovery";
            if (endpoint.EndpointUrl.Scheme != Utils.UriSchemeOpcTcp)
            {
                urlsToTry.Add(new Uri(endpoint.EndpointUrl.ToString() + "/discovery"));
            }

            for (int ii = 0; ii < urlsToTry.Count; ii++)
            {
                // the discovery client provides a programmer's interace to a discovery server.
                DiscoveryClient client = DiscoveryClient.Create(urlsToTry[ii], m_bindingFactory, null);

                try {
                    // fetch the endpoints from the server.
                    EndpointDescriptionCollection endpoints = client.GetEndpoints(null);

                    // add endpoints to cache.
                    ConfiguredEndpointCollection endpointCache = new ConfiguredEndpointCollection();

                    foreach (EndpointDescription description in endpoints)
                    {
                        endpointCache.Add(description, endpoint.Configuration);
                    }

                    return(endpointCache);
                } catch (Exception) {
                    Report("No discovery endpoint found at: {0}", urlsToTry[ii]);
                } finally {
                    // must always close the channel to free resources.
                    client.Close();
                }
            }

            // nothing found.
            throw ServiceResultException.Create(
                      StatusCodes.BadUnexpectedError,
                      "Could not find discovery endpoint for server at: {0}",
                      endpoint);
        }
Example #31
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;
            }
        }
        /// <summary>
        /// Displays the dialog.
        /// </summary>
        public ITransportChannel ShowDialog(
            ApplicationConfiguration      configuration,
            EndpointDescriptionCollection endpoints)
        {
            if (endpoints == null)      throw new ArgumentNullException("endpoints");
            if (configuration == null)  throw new ArgumentNullException("configuration");

            m_endpoints      = endpoints;
            m_configuration  = configuration;
            m_messageContext = configuration.CreateMessageContext();

            EndpointCB.Items.Clear();

            foreach (EndpointDescription endpoint in endpoints)
            {
                EndpointCB.Items.Add(endpoint.EndpointUrl);
            }

            if (EndpointCB.Items.Count > 0)
            {
                EndpointCB.SelectedIndex = 0;
            }
            
            OperationTimeoutNC.Value    = configuration.TransportQuotas.OperationTimeout;
            MaxMessageSizeNC.Value      = configuration.TransportQuotas.MaxMessageSize;
            MaxArrayLengthNC.Value      = configuration.TransportQuotas.MaxArrayLength;
            MaxStringLengthNC.Value     = configuration.TransportQuotas.MaxStringLength;
            MaxByteStringLengthNC.Value = configuration.TransportQuotas.MaxByteStringLength;

            if (ShowDialog() != DialogResult.OK)
            {
                return null;
            }
                       
            // return the channel.
            return m_channel;
        }
        /// <summary>
        /// Creates the endpoints and creates the hosts.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="bindingFactory">The binding factory.</param>
        /// <param name="serverDescription">The server description.</param>
        /// <param name="endpoints">The endpoints.</param>
        /// <returns>
        /// Returns IList of a host for a UA service which type is <seealso cref="ServiceHost"/>.
        /// </returns>
        protected override IList<Task> InitializeServiceHosts(
            ApplicationConfiguration          configuration, 
            out ApplicationDescription        serverDescription,
            out EndpointDescriptionCollection endpoints)
        {
            serverDescription = null;
            endpoints = null;

            Dictionary<string, Task> hosts = new Dictionary<string, Task>();

            // ensure at least one security policy exists.
            if (configuration.ServerConfiguration.SecurityPolicies.Count == 0)
            {                   
                configuration.ServerConfiguration.SecurityPolicies.Add(new ServerSecurityPolicy());
            }
            
            // ensure at least one user token policy exists.
            if (configuration.ServerConfiguration.UserTokenPolicies.Count == 0)
            {                   
                UserTokenPolicy userTokenPolicy = new UserTokenPolicy();
                
                userTokenPolicy.TokenType = UserTokenType.Anonymous;
                userTokenPolicy.PolicyId  = userTokenPolicy.TokenType.ToString();

                configuration.ServerConfiguration.UserTokenPolicies.Add(userTokenPolicy);
            }

            // set server description.
            serverDescription = new ApplicationDescription();

            serverDescription.ApplicationUri = configuration.ApplicationUri;
            serverDescription.ApplicationName = configuration.ApplicationName;
            serverDescription.ApplicationType = configuration.ApplicationType;
            serverDescription.ProductUri = configuration.ProductUri;
            serverDescription.DiscoveryUrls = GetDiscoveryUrls();
                          
            endpoints = new EndpointDescriptionCollection();
            IList<EndpointDescription> endpointsForHost = null;

            // create UA TCP host.
            endpointsForHost = CreateUaTcpServiceHost(
                hosts,
                configuration,
                configuration.ServerConfiguration.BaseAddresses,
                serverDescription,
                configuration.ServerConfiguration.SecurityPolicies);

            endpoints.InsertRange(0, endpointsForHost);

            // create HTTPS host.
#if !NO_HTTPS
            endpointsForHost = CreateHttpsServiceHost(
            hosts,
            configuration,
            configuration.ServerConfiguration.BaseAddresses,
            serverDescription,
            configuration.ServerConfiguration.SecurityPolicies);

            endpoints.AddRange(endpointsForHost);
#endif
            return new List<Task>(hosts.Values);
        }
Example #34
0
        /// <summary>
        /// Initializes the protocol dropdown.
        /// </summary>
        private void InitializeProtocols(EndpointDescriptionCollection endpoints)
        {
            // preserve the existing value.
            Protocol currentProtocol = (Protocol)ProtocolCB.SelectedItem;

            ProtocolCB.Items.Clear();

            // set all available protocols.
            if (m_showAllOptions)
            {
                ProtocolCB.Items.Add(new Protocol("http://localhost"));
                ProtocolCB.Items.Add(new Protocol("https://localhost"));
                ProtocolCB.Items.Add(new Protocol("opc.tcp://localhost"));
            }

            // find all unique protocols.
            else
            {
                if (endpoints != null)
                {
                    foreach (EndpointDescription endpoint in endpoints)
                    {
                        Uri url = Utils.ParseUri(endpoint.EndpointUrl);

                        if (url != null)
                        {
                            bool found = false;

                            for (int ii = 0; ii < ProtocolCB.Items.Count; ii++)
                            {
                                if (((Protocol)ProtocolCB.Items[ii]).Matches(url))
                                {
                                    found = true;
                                    break;
                                }
                            }

                            if (!found)
                            {
                                ProtocolCB.Items.Add(new Protocol(endpoint));
                            }
                        }
                    }
                }

                // add at least one protocol.
                if (ProtocolCB.Items.Count == 0)
                {
                    ProtocolCB.Items.Add(new Protocol("opc.tcp://localhost"));
                }
            }

            // set the current value.
            int index = 0;

            if (currentProtocol != null)
            {
                index = 0;
                
                for (int ii = 0; ii < ProtocolCB.Items.Count; ii++)
                {
                    if (((Protocol)ProtocolCB.Items[ii]).Matches(currentProtocol.Url))
                    {
                        index = ii;
                        break;
                    }
                }
            }

            ProtocolCB.SelectedIndex = index;
        }
 /// <summary>
 /// Replace localhost in returned discovery url with remote host name.
 /// </summary>
 private void ReplaceLocalHostWithRemoteHost(EndpointDescriptionCollection endpoints, Uri discoveryUrl)
 {
     foreach (EndpointDescription endpoint in endpoints)
     {
         endpoint.EndpointUrl = Utils.ReplaceLocalhost(endpoint.EndpointUrl, discoveryUrl.DnsSafeHost);
         StringCollection updatedDiscoveryUrls = new StringCollection();
         foreach (string url in endpoint.Server.DiscoveryUrls)
         {
             updatedDiscoveryUrls.Add(Utils.ReplaceLocalhost(url, discoveryUrl.DnsSafeHost));
         }
         endpoint.Server.DiscoveryUrls = updatedDiscoveryUrls;
     }
 }
Example #36
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;
        }
        /// <summary>
        /// Displays the dialog.
        /// </summary>
        public async Task<ConfiguredEndpoint> ShowDialog(ApplicationDescription server, ApplicationConfiguration configuration)
        {
            if (server == null) throw new ArgumentNullException("server");

            m_configuration = configuration;

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

            // create a default endpoint description.
            m_endpoint = null;
            m_currentDescription = null;

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

            UseDefaultLimitsCB.SelectedIndex = (int)UseDefaultLimits.Yes;

            // discover endpoints in the background.
            m_discoverySucceeded = false;
            Interlocked.Increment(ref m_discoverCount);
            OnDiscoverEndpoints(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;

        }
Example #38
0
        /// <summary>
        /// Invokes the CreateSession service.
        /// </summary>
        public virtual ResponseHeader CreateSession(
            RequestHeader                           requestHeader,
            ApplicationDescription                  clientDescription,
            string                                  serverUri,
            string                                  endpointUrl,
            string                                  sessionName,
            byte[]                                  clientNonce,
            byte[]                                  clientCertificate,
            double                                  requestedSessionTimeout,
            uint                                    maxResponseMessageSize,
            out NodeId                              sessionId,
            out NodeId                              authenticationToken,
            out double                              revisedSessionTimeout,
            out byte[]                              serverNonce,
            out byte[]                              serverCertificate,
            out EndpointDescriptionCollection       serverEndpoints,
            out SignedSoftwareCertificateCollection serverSoftwareCertificates,
            out SignatureData                       serverSignature,
            out uint                                maxRequestMessageSize)
        {
            CreateSessionRequest request = new CreateSessionRequest();
            CreateSessionResponse response = null;

            request.RequestHeader           = requestHeader;
            request.ClientDescription       = clientDescription;
            request.ServerUri               = serverUri;
            request.EndpointUrl             = endpointUrl;
            request.SessionName             = sessionName;
            request.ClientNonce             = clientNonce;
            request.ClientCertificate       = clientCertificate;
            request.RequestedSessionTimeout = requestedSessionTimeout;
            request.MaxResponseMessageSize  = maxResponseMessageSize;

            UpdateRequestHeader(request, requestHeader == null, "CreateSession");

            try
            {
                if (UseTransportChannel)
                {
                    IServiceResponse genericResponse = TransportChannel.SendRequest(request);

                    if (genericResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    ValidateResponse(genericResponse.ResponseHeader);
                    response = (CreateSessionResponse)genericResponse;
                }
                else
                {
                    CreateSessionResponseMessage responseMessage = InnerChannel.CreateSession(new CreateSessionMessage(request));

                    if (responseMessage == null || responseMessage.CreateSessionResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    response = responseMessage.CreateSessionResponse;
                    ValidateResponse(response.ResponseHeader);
                }

                sessionId                  = response.SessionId;
                authenticationToken        = response.AuthenticationToken;
                revisedSessionTimeout      = response.RevisedSessionTimeout;
                serverNonce                = response.ServerNonce;
                serverCertificate          = response.ServerCertificate;
                serverEndpoints            = response.ServerEndpoints;
                serverSoftwareCertificates = response.ServerSoftwareCertificates;
                serverSignature            = response.ServerSignature;
                maxRequestMessageSize      = response.MaxRequestMessageSize;
            }
            finally
            {
                RequestCompleted(request, response, "CreateSession");
            }

            return response.ResponseHeader;
        }
Example #39
0
        /// <summary>
        /// Invokes the GetEndpoints service.
        /// </summary>
        public virtual ResponseHeader GetEndpoints(
            RequestHeader                     requestHeader,
            string                            endpointUrl,
            StringCollection                  localeIds,
            StringCollection                  profileUris,
            out EndpointDescriptionCollection endpoints)
        {
            GetEndpointsRequest request = new GetEndpointsRequest();
            GetEndpointsResponse response = null;

            request.RequestHeader = requestHeader;
            request.EndpointUrl   = endpointUrl;
            request.LocaleIds     = localeIds;
            request.ProfileUris   = profileUris;

            UpdateRequestHeader(request, requestHeader == null, "GetEndpoints");

            try
            {
                if (UseTransportChannel)
                {
                    IServiceResponse genericResponse = TransportChannel.SendRequest(request);

                    if (genericResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    ValidateResponse(genericResponse.ResponseHeader);
                    response = (GetEndpointsResponse)genericResponse;
                }
                else
                {
                    GetEndpointsResponseMessage responseMessage = InnerChannel.GetEndpoints(new GetEndpointsMessage(request));

                    if (responseMessage == null || responseMessage.GetEndpointsResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    response = responseMessage.GetEndpointsResponse;
                    ValidateResponse(response.ResponseHeader);
                }

                endpoints = response.Endpoints;
            }
            finally
            {
                RequestCompleted(request, response, "GetEndpoints");
            }

            return response.ResponseHeader;
        }
        /// <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;
        }
        /// <summary>
        /// Invokes the GetEndpoints service.
        /// </summary>
        /// <param name="requestHeader">The request header.</param>
        /// <param name="endpointUrl">The endpoint URL.</param>
        /// <param name="localeIds">The locale ids.</param>
        /// <param name="profileUris">The profile uris.</param>
        /// <param name="endpoints">The endpoints supported by the server.</param>
        /// <returns>
        /// Returns a <see cref="ResponseHeader"/> object
        /// </returns>
        public override ResponseHeader GetEndpoints(
            RequestHeader                     requestHeader,
            string                            endpointUrl,
            StringCollection                  localeIds,
            StringCollection                  profileUris,
            out EndpointDescriptionCollection endpoints)
        {   
            endpoints = null;
            
            ValidateRequest(requestHeader);

            lock (m_lock)
            {
                // filter by profile.
                IList<BaseAddress> baseAddresses = FilterByProfile(profileUris, BaseAddresses);

                // get the descriptions.
                endpoints = GetEndpointDescriptions(
                    endpointUrl,
                    baseAddresses,
                    localeIds);
            }

            return CreateResponse(requestHeader, StatusCodes.Good);
        }
Example #42
0
        /// <summary>
        /// Updates the list of servers displayed in the control.
        /// </summary>
        private void OnUpdateEndpoints(object state)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new WaitCallback(OnUpdateEndpoints), state);
                return;
            }

            try
            {
                // get the updated descriptions.
                EndpointDescriptionCollection endpoints = state as EndpointDescriptionCollection;

                if (endpoints == null)
                {
                    m_showAllOptions = true;
                    InitializeProtocols(m_availableEndpoints);
                }

                else
                {
                    m_showAllOptions = false;

                    m_availableEndpoints = endpoints;
                    BuildEndpointDescriptionStrings(m_availableEndpoints);

                    if (endpoints.Count > 0)
                    {
                        m_currentDescription = endpoints[0];
                    }

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

                    // select the best security mode.
                    MessageSecurityMode bestMode = MessageSecurityMode.Invalid;

                    foreach (MessageSecurityMode securityMode in SecurityModeCB.Items)
                    {
                        if (securityMode > bestMode)
                        {
                            bestMode = securityMode;
                        }
                    }

                    SecurityModeCB.SelectedItem = bestMode;

                    // select the best encoding.
                    Encoding bestEncoding = Encoding.Default;

                    foreach (Encoding encoding in EncodingCB.Items)
                    {
                        if (encoding > bestEncoding)
                        {
                            bestEncoding = encoding;
                        }
                    }

                    EncodingCB.SelectedItem = bestEncoding;
                }

                if (m_endpoint != null)
                {
                    Uri url = m_endpoint.EndpointUrl;

                    foreach (Protocol protocol in ProtocolCB.Items)
                    {
                        if (protocol.Matches(url))
                        {
                            ProtocolCB.SelectedItem = protocol;
                            break;
                        }
                    }

                    foreach (MessageSecurityMode securityMode in SecurityModeCB.Items)
                    {
                        if (securityMode == m_endpoint.Description.SecurityMode)
                        {
                            SecurityModeCB.SelectedItem = securityMode;
                            break;
                        }
                    }

                    foreach (string securityPolicy in SecurityPolicyCB.Items)
                    {
                        if (securityPolicy == m_endpoint.Description.SecurityPolicyUri)
                        {
                            SecurityPolicyCB.SelectedItem = securityPolicy;
                            break;
                        }
                    }

                    foreach (Encoding encoding in EncodingCB.Items)
                    {
                        if (encoding == Encoding.Binary && m_endpoint.Configuration.UseBinaryEncoding)
                        {
                            EncodingCB.SelectedItem = encoding;
                            break;
                        }

                        if (encoding == Encoding.Xml && !m_endpoint.Configuration.UseBinaryEncoding)
                        {
                            EncodingCB.SelectedItem = encoding;
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Utils.Trace(e, "Unexpected error updating endpoints.");
            }
        }
Example #43
0
        public Session(
            ITransportChannel channel,
            ApplicationConfiguration configuration,
            ConfiguredEndpoint endpoint,
            X509Certificate2 clientCertificate,
            EndpointDescriptionCollection availableEndpoints)
            :
                base(channel)
        {
            Initialize(channel, configuration, endpoint, clientCertificate);

            m_expectedServerEndpoints = availableEndpoints;
        }
Example #44
0
        /// <summary>
        /// Displays the dialog.
        /// </summary>
        public ConfiguredEndpoint ShowDialog(ApplicationDescription server, ApplicationConfiguration configuration)
        {
            if (server == null) throw new ArgumentNullException("server");

            m_configuration = configuration;

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

            // create a default endpoint description.
            m_endpoint = null;
            m_currentDescription = null;

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

            // discover endpoints in the background.
            m_discoverySucceeded = false;
            Interlocked.Increment(ref m_discoverCount);
            ThreadPool.QueueUserWorkItem(new WaitCallback(OnDiscoverEndpoints), server);

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

            return m_endpoint;
        }
Example #45
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;
        }
Example #46
0
        /// <summary>
        /// Creates the string representation of each EndpointDescription - to be used in the Endpoint Description List
        /// </summary>
        private void BuildEndpointDescriptionStrings(EndpointDescriptionCollection endpoints)
        {
            lock (m_availableEndpointsDescriptions)
            {
                m_availableEndpointsDescriptions.Clear();

                foreach (EndpointDescription endpoint in endpoints)
                {
                    m_availableEndpointsDescriptions.Add(new EndpointDescriptionString(endpoint));
                }

                InitializeEndpointList(m_availableEndpointsDescriptions);
            }
        }
Example #47
0
        /// <summary>
        /// Initializes the security modes dropdown.
        /// </summary>
        private void InitializeSecurityModes(EndpointDescriptionCollection endpoints)
        {
            // filter by the current protocol.
            Protocol currentProtocol = (Protocol)ProtocolCB.SelectedItem;

            // preserve the existing value.
            MessageSecurityMode currentMode = MessageSecurityMode.None;

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

            SecurityModeCB.Items.Clear();

            // set all available security modes.
            if (m_showAllOptions)
            {
                SecurityModeCB.Items.Add(MessageSecurityMode.None);
                SecurityModeCB.Items.Add(MessageSecurityMode.Sign);
                SecurityModeCB.Items.Add(MessageSecurityMode.SignAndEncrypt);
            }

            // find all unique security modes.
            else
            {
                if (endpoints != null)
                {
                    foreach (EndpointDescription endpoint in endpoints)
                    {
                        Uri url = Utils.ParseUri(endpoint.EndpointUrl);

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

                            if (!SecurityModeCB.Items.Contains(endpoint.SecurityMode))
                            {
                                SecurityModeCB.Items.Add(endpoint.SecurityMode);
                            }
                        }
                    }
                }

                // add at least one policy.
                if (SecurityModeCB.Items.Count == 0)
                {
                    SecurityModeCB.Items.Add(MessageSecurityMode.None);
                }
            }

            // set the current value.
            int index = SecurityModeCB.Items.IndexOf(currentMode);

            if (index == -1)
            {
                index = 0;
            }

            SecurityModeCB.SelectedIndex = index;
        }
        /// <summary>
        /// Invokes the CreateSession service.
        /// </summary>
        /// <param name="requestHeader">The request header.</param>
        /// <param name="clientDescription">Application description for the client application.</param>
        /// <param name="serverUri">The server URI.</param>
        /// <param name="endpointUrl">The endpoint URL.</param>
        /// <param name="sessionName">Name for the Session assigned by the client.</param>
        /// <param name="clientNonce">The client nonce.</param>
        /// <param name="clientCertificate">The client certificate.</param>
        /// <param name="requestedSessionTimeout">The requested session timeout.</param>
        /// <param name="maxResponseMessageSize">Size of the max response message.</param>
        /// <param name="sessionId">The unique public identifier assigned by the Server to the Session.</param>
        /// <param name="authenticationToken">The unique private identifier assigned by the Server to the Session.</param>
        /// <param name="revisedSessionTimeout">The revised session timeout.</param>
        /// <param name="serverNonce">The server nonce.</param>
        /// <param name="serverCertificate">The server certificate.</param>
        /// <param name="serverEndpoints">The server endpoints.</param>
        /// <param name="serverSoftwareCertificates">The server software certificates.</param>
        /// <param name="serverSignature">The server signature.</param>
        /// <param name="maxRequestMessageSize">Size of the max request message.</param>
        /// <returns>
        /// Returns a <see cref="ResponseHeader"/> object
        /// </returns>
        public override ResponseHeader CreateSession(
            RequestHeader                           requestHeader,
            ApplicationDescription                  clientDescription,
            string                                  serverUri,
            string                                  endpointUrl,
            string                                  sessionName,
            byte[]                                  clientNonce,
            byte[]                                  clientCertificate,
            double                                  requestedSessionTimeout,
            uint                                    maxResponseMessageSize,
            out NodeId                              sessionId,
            out NodeId                              authenticationToken,
            out double                              revisedSessionTimeout,
            out byte[]                              serverNonce,
            out byte[]                              serverCertificate,
            out EndpointDescriptionCollection       serverEndpoints,
            out SignedSoftwareCertificateCollection serverSoftwareCertificates,
            out SignatureData                       serverSignature,
            out uint                                maxRequestMessageSize)
        {       
            sessionId = 0;
            revisedSessionTimeout = 0;
            serverNonce = null;
            serverCertificate = null;
            serverSoftwareCertificates = null;
            serverSignature = null;
            maxRequestMessageSize = (uint)MessageContext.MaxMessageSize;

            OperationContext context = ValidateRequest(requestHeader, RequestType.CreateSession);
        
            try
            {
                // check the server uri.
                if (!String.IsNullOrEmpty(serverUri))
                {
                    if (serverUri != this.Configuration.ApplicationUri)
                    {
                        throw new ServiceResultException(StatusCodes.BadServerUriInvalid);
                    }
                }

                bool requireEncryption = ServerBase.RequireEncryption(context.ChannelContext.EndpointDescription);

                if (!requireEncryption && clientCertificate != null)
                {
                    requireEncryption = true;
                }

                // validate client application instance certificate.
                X509Certificate2 parsedClientCertificate = null;

                if (requireEncryption && clientCertificate != null && clientCertificate.Length > 0)
                {
                    try
                    {
                        parsedClientCertificate = CertificateFactory.Create(clientCertificate, true);

                        if (context.SecurityPolicyUri != SecurityPolicies.None)
                        {
                            string certificateApplicationUri = Utils.GetApplicationUriFromCertficate(parsedClientCertificate);

                            // verify if applicationUri from ApplicationDescription matches the applicationUri in the client certificate.
                            if (!String.IsNullOrEmpty(certificateApplicationUri) &&
                                !String.IsNullOrEmpty(clientDescription.ApplicationUri) &&
                                certificateApplicationUri != clientDescription.ApplicationUri)
                            {
                                throw ServiceResultException.Create(
                                    StatusCodes.BadCertificateUriInvalid,
                                    "The URI specified in the ApplicationDescription does not match the URI in the Certificate.");
                            }

                            CertificateValidator.Validate(parsedClientCertificate);
                        }
                    }
                    catch (Exception e)
                    {
                        OnApplicationCertificateError(clientCertificate, new ServiceResult(e));
                    }
                }

                // verify the nonce provided by the client.
                if (clientNonce != null)
                {
                    if (clientNonce.Length < m_minNonceLength)
                    {
                        throw new ServiceResultException(StatusCodes.BadNonceInvalid);
                    }
                }

                // create the session.
                Session session = ServerInternal.SessionManager.CreateSession(
                    context,
                    requireEncryption ? InstanceCertificate : null,
                    sessionName,
                    clientNonce,
                    clientDescription,
                    endpointUrl,
                    parsedClientCertificate,
                    requestedSessionTimeout,
                    maxResponseMessageSize,
                    out sessionId,
                    out authenticationToken,
                    out serverNonce,
                    out revisedSessionTimeout);           
                                
                lock (m_lock)
                {                
                    // return the application instance certificate for the server.
                    if (requireEncryption)
                    {
                        serverCertificate = InstanceCertificate.RawData;
                    }
                                 
                    // return the endpoints supported by the server.
                    serverEndpoints = GetEndpointDescriptions(endpointUrl, BaseAddresses, null);

                    // return the software certificates assigned to the server.
                    serverSoftwareCertificates = new SignedSoftwareCertificateCollection(ServerProperties.SoftwareCertificates);
                    
                    // sign the nonce provided by the client.
                    serverSignature = null;
                    
                    //  sign the client nonce (if provided).
                    if (parsedClientCertificate != null && clientNonce != null)
                    {
                        byte[] dataToSign = Utils.Append(clientCertificate, clientNonce);
                        serverSignature = SecurityPolicies.Sign(InstanceCertificate, context.SecurityPolicyUri, dataToSign);
                    }
                }

                lock (ServerInternal.DiagnosticsLock)
                {
                    ServerInternal.ServerDiagnostics.CurrentSessionCount++;
                    ServerInternal.ServerDiagnostics.CumulatedSessionCount++;
                }

                Utils.Trace("Server - SESSION CREATED. SessionId={0}", sessionId);

                return CreateResponse(requestHeader, StatusCodes.Good);
            }
            catch (ServiceResultException e)
            {
                Utils.Trace("Server - SESSION CREATE failed. {0}", e.Message);

                lock (ServerInternal.DiagnosticsLock)
                {
                    ServerInternal.ServerDiagnostics.RejectedSessionCount++;
                    ServerInternal.ServerDiagnostics.RejectedRequestsCount++;

                    if (IsSecurityError(e.StatusCode))
                    {
                        ServerInternal.ServerDiagnostics.SecurityRejectedSessionCount++;
                        ServerInternal.ServerDiagnostics.SecurityRejectedRequestsCount++;
                    }
                }

                throw TranslateException((DiagnosticsMasks)requestHeader.ReturnDiagnostics, new StringCollection(), e);
            }  
            finally
            {
                OnRequestComplete(context);
            }
        }
        /// <summary>
        /// Invokes the CreateSession service.
        /// </summary>
        public virtual ResponseHeader CreateSession(
            RequestHeader                           requestHeader,
            ApplicationDescription                  clientDescription,
            string                                  serverUri,
            string                                  endpointUrl,
            string                                  sessionName,
            byte[]                                  clientNonce,
            byte[]                                  clientCertificate,
            double                                  requestedSessionTimeout,
            uint                                    maxResponseMessageSize,
            out NodeId                              sessionId,
            out NodeId                              authenticationToken,
            out double                              revisedSessionTimeout,
            out byte[]                              serverNonce,
            out byte[]                              serverCertificate,
            out EndpointDescriptionCollection       serverEndpoints,
            out SignedSoftwareCertificateCollection serverSoftwareCertificates,
            out SignatureData                       serverSignature,
            out uint                                maxRequestMessageSize)
        {
            sessionId = null;
            authenticationToken = null;
            revisedSessionTimeout = 0;
            serverNonce = null;
            serverCertificate = null;
            serverEndpoints = null;
            serverSoftwareCertificates = null;
            serverSignature = null;
            maxRequestMessageSize = 0;

            ValidateRequest(requestHeader);

            // Insert implementation.

            return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported);
        }
Example #50
0
        /// <summary>
        /// Finishes an asynchronous invocation of the GetEndpoints service.
        /// </summary>
        public ResponseHeader EndGetEndpoints(
            IAsyncResult                      result,
            out EndpointDescriptionCollection endpoints)
        {
            GetEndpointsResponse response = null;

            try
            {
                if (UseTransportChannel)
                {
                    IServiceResponse genericResponse = TransportChannel.EndSendRequest(result);

                    if (genericResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    ValidateResponse(genericResponse.ResponseHeader);
                    response = (GetEndpointsResponse)genericResponse;
                }
                else
                {
                    GetEndpointsResponseMessage responseMessage = InnerChannel.EndGetEndpoints(result);

                    if (responseMessage == null || responseMessage.GetEndpointsResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    response = responseMessage.GetEndpointsResponse;
                    ValidateResponse(response.ResponseHeader);
                }

                endpoints = response.Endpoints;
            }
            finally
            {
                RequestCompleted(null, response, "GetEndpoints");
            }

            return response.ResponseHeader;
        }
        /// <summary>
        /// Creates the endpoints and creates the hosts.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="bindingFactory">The binding factory.</param>
        /// <param name="serverDescription">The server description.</param>
        /// <param name="endpoints">The endpoints.</param>
        /// <returns>
        /// Returns IList of a host for a UA service which type is <seealso cref="ServiceHost"/>.
        /// </returns>
        protected override IList<IBackgroundTask> InitializeServiceHosts(
            ApplicationConfiguration          configuration, 
            BindingFactory                    bindingFactory,
            out ApplicationDescription        serverDescription,
            out EndpointDescriptionCollection endpoints)
        {
            serverDescription = null;
            endpoints = null;

            Dictionary<string, IBackgroundTask> hosts = new Dictionary<string, IBackgroundTask>();

            // ensure at least one security policy exists.
            if (configuration.ServerConfiguration.SecurityPolicies.Count == 0)
            {                   
                configuration.ServerConfiguration.SecurityPolicies.Add(new ServerSecurityPolicy());
            }
            
            // ensure at least one user token policy exists.
            if (configuration.ServerConfiguration.UserTokenPolicies.Count == 0)
            {                   
                UserTokenPolicy userTokenPolicy = new UserTokenPolicy();
                
                userTokenPolicy.TokenType = UserTokenType.Anonymous;
                userTokenPolicy.PolicyId  = userTokenPolicy.TokenType.ToString();

                configuration.ServerConfiguration.UserTokenPolicies.Add(userTokenPolicy);
            }

            // set server description.
            serverDescription = new ApplicationDescription();

            serverDescription.ApplicationUri = configuration.ApplicationUri;
            serverDescription.ApplicationName = configuration.ApplicationName;
            serverDescription.ApplicationType = configuration.ApplicationType;
            serverDescription.ProductUri = configuration.ProductUri;
            serverDescription.DiscoveryUrls = GetDiscoveryUrls();
                          
            endpoints = new EndpointDescriptionCollection();
            IList<EndpointDescription> endpointsForHost = null;

            // create hosts for protocols that require one endpoints per security policy
            foreach (ServerSecurityPolicy securityPolicy in configuration.ServerConfiguration.SecurityPolicies)
            {
                endpointsForHost = CreateSinglePolicyServiceHost(
                    hosts,
                    configuration,
                    bindingFactory, 
                    configuration.ServerConfiguration.BaseAddresses, 
                    serverDescription,
                    securityPolicy.SecurityMode, 
                    securityPolicy.SecurityPolicyUri,
                    String.Empty);

                for (int ii = 0; ii < endpointsForHost.Count; ii++)
                {
                    endpointsForHost[ii].SecurityLevel = securityPolicy.SecurityLevel;
                }

                endpoints.AddRange(endpointsForHost);
            }

            // create UA TCP host.
            endpointsForHost = CreateUaTcpServiceHost(
                hosts,
                configuration,
                bindingFactory,
                configuration.ServerConfiguration.BaseAddresses,
                serverDescription,
                configuration.ServerConfiguration.SecurityPolicies);

            endpoints.InsertRange(0, endpointsForHost);

            // create HTTPS host.
            endpointsForHost = CreateHttpsServiceHost(
                hosts,
                configuration,
                bindingFactory, 
                configuration.ServerConfiguration.BaseAddresses, 
                serverDescription,
                configuration.ServerConfiguration.SecurityPolicies);

            endpoints.AddRange(endpointsForHost);

            return new List<IBackgroundTask>(hosts.Values);
        }
Example #52
0
        /// <summary>
        /// Initializes the message encodings dropdown.
        /// </summary>
        private void InitializeEncodings(EndpointDescriptionCollection endpoints, EndpointDescription endpoint)
        {
            // preserve the existing value.
            Encoding currentEncoding = Encoding.Default;

            if (EncodingCB.SelectedIndex != -1)
            {
                currentEncoding = (Encoding)EncodingCB.SelectedItem;
            }

            EncodingCB.Items.Clear();

            if (endpoint != null)
            {
                Protocol protocol = new Protocol(endpoint);
                String securityPolicy = SecurityPolicies.GetDisplayName(endpoint.SecurityPolicyUri);

                foreach (EndpointDescription endpointDescription in endpoints)
                {
                    if ((protocol.Matches(Utils.ParseUri(endpointDescription.EndpointUrl))) &&
                        (endpoint.SecurityMode == endpointDescription.SecurityMode) &&
                        (securityPolicy == SecurityPolicies.GetDisplayName(endpointDescription.SecurityPolicyUri)))
                    {
                        switch (endpointDescription.EncodingSupport)
                        {
                            case BinaryEncodingSupport.None:
                                {
                                    if (!EncodingCB.Items.Contains(Encoding.Xml))
                                    {
                                        EncodingCB.Items.Add(Encoding.Xml);
                                    }
                                    break;
                                }

                            case BinaryEncodingSupport.Required:
                                {
                                    if (!EncodingCB.Items.Contains(Encoding.Binary))
                                    {
                                        EncodingCB.Items.Add(Encoding.Binary);
                                    }
                                    break;
                                }

                            case BinaryEncodingSupport.Optional:
                                {
                                    if (!EncodingCB.Items.Contains(Encoding.Binary))
                                    {
                                        EncodingCB.Items.Add(Encoding.Binary);
                                    }
                                    if (!EncodingCB.Items.Contains(Encoding.Xml))
                                    {
                                        EncodingCB.Items.Add(Encoding.Xml);
                                    }
                                    break;
                                }
                        }
                    }
                }
            }

            // add at least one encoding.
            if (EncodingCB.Items.Count == 0)
            {
                EncodingCB.Items.Add(Encoding.Default);
            }

            // set the current value.
            int index = EncodingCB.Items.IndexOf(currentEncoding);

            if (index == -1)
            {
                index = 0;
            }

            EncodingCB.SelectedIndex = index;
        }
Example #53
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;
        }
Example #54
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;
        }
        /// <summary>
        /// Invokes the GetEndpoints service.
        /// </summary>
        public virtual ResponseHeader GetEndpoints(
            RequestHeader                     requestHeader,
            string                            endpointUrl,
            StringCollection                  localeIds,
            StringCollection                  profileUris,
            out EndpointDescriptionCollection endpoints)
        {
            endpoints = null;

            ValidateRequest(requestHeader);

            // Insert implementation.

            return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported);
        }
Example #56
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;
        }
Example #57
0
 /// <summary>
 /// Creates the endpoints and creates the hosts.
 /// </summary>
 /// <param name="configuration">The object that stores the configurable configuration information for a UA application.</param>
 /// <param name="bindingFactory">The object of a class that manages a mapping between a URL scheme and a binding.</param>
 /// <param name="serverDescription">The object of the class that contains a description for the ApplicationDescription DataType.</param>
 /// <param name="endpoints">The collection of <see cref="EndpointDescription"/> objects.</param>
 /// <returns>Returns list of hosts for a UA service.</returns>
 protected virtual IList<ServiceHost> InitializeServiceHosts(
     ApplicationConfiguration          configuration, 
     BindingFactory                    bindingFactory,
     out ApplicationDescription        serverDescription,
     out EndpointDescriptionCollection endpoints)            
 {
     serverDescription = null;
     endpoints = null;
     return new List<ServiceHost>();
 }
Example #58
0
        /// <summary>
        /// Initializes the security policies dropdown.
        /// </summary>
        private void InitializeSecurityPolicies(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;
            }

            // preserve the existing value.
            string currentPolicy = (string)SecurityPolicyCB.SelectedItem;

            SecurityPolicyCB.Items.Clear();

            // set all available security policies.
            if (m_showAllOptions)
            {
                SecurityPolicyCB.Items.Add(SecurityPolicies.GetDisplayName(SecurityPolicies.None));
                SecurityPolicyCB.Items.Add(SecurityPolicies.GetDisplayName(SecurityPolicies.Basic128Rsa15));
                SecurityPolicyCB.Items.Add(SecurityPolicies.GetDisplayName(SecurityPolicies.Basic256));
            }

            // find all unique security policies.    
            else
            {
                if (endpoints != null)
                {
                    foreach (EndpointDescription endpoint in endpoints)
                    {
                        Uri url = Utils.ParseUri(endpoint.EndpointUrl);

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

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

                            string policyName = SecurityPolicies.GetDisplayName(endpoint.SecurityPolicyUri);

                            if (policyName != null)
                            {
                                int existingIndex = SecurityPolicyCB.FindStringExact(policyName);

                                if (existingIndex == -1)
                                {
                                    SecurityPolicyCB.Items.Add(policyName);
                                }
                            }
                        }
                    }
                }
            }

            // add at least one policy.
            if (SecurityPolicyCB.Items.Count == 0)
            {
                SecurityPolicyCB.Items.Add(SecurityPolicies.GetDisplayName(SecurityPolicies.None));
            }

            // set the current value.
            int index = 0;

            if (!String.IsNullOrEmpty(currentPolicy))
            {
                index = SecurityPolicyCB.FindStringExact(currentPolicy);

                if (index == -1)
                {
                    index = 0;
                }
            }

            SecurityPolicyCB.SelectedIndex = index;
        }
Example #59
0
        /// <summary>
        /// Finishes an asynchronous invocation of the CreateSession service.
        /// </summary>
        public ResponseHeader EndCreateSession(
            IAsyncResult                            result,
            out NodeId                              sessionId,
            out NodeId                              authenticationToken,
            out double                              revisedSessionTimeout,
            out byte[]                              serverNonce,
            out byte[]                              serverCertificate,
            out EndpointDescriptionCollection       serverEndpoints,
            out SignedSoftwareCertificateCollection serverSoftwareCertificates,
            out SignatureData                       serverSignature,
            out uint                                maxRequestMessageSize)
        {
            CreateSessionResponse response = null;

            try
            {
                if (UseTransportChannel)
                {
                    IServiceResponse genericResponse = TransportChannel.EndSendRequest(result);

                    if (genericResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    ValidateResponse(genericResponse.ResponseHeader);
                    response = (CreateSessionResponse)genericResponse;
                }
                else
                {
                    CreateSessionResponseMessage responseMessage = InnerChannel.EndCreateSession(result);

                    if (responseMessage == null || responseMessage.CreateSessionResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    response = responseMessage.CreateSessionResponse;
                    ValidateResponse(response.ResponseHeader);
                }

                sessionId                  = response.SessionId;
                authenticationToken        = response.AuthenticationToken;
                revisedSessionTimeout      = response.RevisedSessionTimeout;
                serverNonce                = response.ServerNonce;
                serverCertificate          = response.ServerCertificate;
                serverEndpoints            = response.ServerEndpoints;
                serverSoftwareCertificates = response.ServerSoftwareCertificates;
                serverSignature            = response.ServerSignature;
                maxRequestMessageSize      = response.MaxRequestMessageSize;
            }
            finally
            {
                RequestCompleted(null, response, "CreateSession");
            }

            return response.ResponseHeader;
        }
 private static EndpointDescription SelectUaTcpEndpoint(EndpointDescriptionCollection endpointCollection, bool haveCert)
 {
     EndpointDescription bestEndpoint = null;
     foreach (EndpointDescription endpoint in endpointCollection)
     {
         if (endpoint.TransportProfileUri == Profiles.UaTcpTransport)
         {
             if (bestEndpoint == null || 
                 haveCert && (endpoint.SecurityLevel > bestEndpoint.SecurityLevel) ||
                 !haveCert && (endpoint.SecurityLevel < bestEndpoint.SecurityLevel))
             {
                 bestEndpoint = endpoint;
             }
         }
     }
     return bestEndpoint;
 }