Exemple #1
0
        /// <summary>
        /// Creates the session.
        /// </summary>
        public void Create(
            EndpointDescription endpoint,
            ApplicationDescription client,
            byte[] clientCertificate,
            string sessionName,
            double sessionTimeout,
            out NodeId sessionId,
            out NodeId authenticationToken,
            out byte[] serverNonce,
            out double revisedSessionTimeout)
        {
            lock (m_lock)
            {
                // save the secure channel id.
                m_secureChannelId = null;

                if (OperationContext.Current != null)
                {
                    m_secureChannelId = OperationContext.Current.Channel.SessionId;
                }

                m_endpoint = endpoint;
                m_client = client;
                m_sessionName = sessionName;

                if (clientCertificate != null)
                {
                    m_clientCertificate = new X509Certificate2(clientCertificate);
                }

                // Create a public and a private identifier for the session. The public identifier is visible in the
                // address space and audit logs. The private identifier is only used by the client to identify itself 
                // when it sends a request. Clients and servers that do not keep the authentication token will be vulnerable
                // to session hijacking when using transports such as SSL to implement the secure channel. It is not an
                // issue for applications that use WS-Secure Conversation.

                // create a guid for a session id. use it for an authentication token as well.
                m_sessionId = new NodeId(System.Guid.NewGuid(), 1);
                m_authenticationToken = authenticationToken = sessionId = m_sessionId;

                // set a reasonable session timeout.
                m_sessionTimeout = sessionTimeout;

                if (m_sessionTimeout < 30000)
                {
                    m_sessionTimeout = 30000;
                }

                revisedSessionTimeout = m_sessionTimeout;

                // create a server nonce.
                m_serverNonce = serverNonce = new byte[32];
                RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();
                random.GetBytes(m_serverNonce);
            }
        }
Exemple #2
0
        /// <summary>
        /// Loads the endpoint information from the registry.
        /// </summary>
        public static ConfiguredEndpoint Load(Guid clsid)
        {
            // load the configuration.
            ConfiguredEndpoint endpoint = LoadConfiguredEndpoint(clsid);

            // create a dummy configuration.
            if (endpoint == null)
            {
                ApplicationDescription server = new ApplicationDescription();

                server.ApplicationName = "(Missing Configuration File)";
                server.ApplicationType = ApplicationType.Server;
                server.ApplicationUri  = clsid.ToString();

                endpoint = new ConfiguredEndpoint(server, null);
            }

            // update the COM identity based on what is actually in the registry.
            endpoint.ComIdentity = new EndpointComIdentity();
            endpoint.ComIdentity.Clsid  = clsid;
            endpoint.ComIdentity.ProgId = ConfigUtils.ProgIDFromCLSID(clsid);
            
            List<Guid> categories = ConfigUtils.GetImplementedCategories(clsid);

            for (int ii = 0; ii < categories.Count; ii++)
            {
                if (categories[ii] == ConfigUtils.CATID_OPCDAServer20)
                {
                    endpoint.ComIdentity.Specification = ComSpecification.DA;
                    break;
                }

                if (categories[ii] == ConfigUtils.CATID_OPCDAServer30)
                {
                    endpoint.ComIdentity.Specification = ComSpecification.DA;
                    break;
                }

                if (categories[ii] == ConfigUtils.CATID_OPCAEServer10)
                {
                    endpoint.ComIdentity.Specification = ComSpecification.AE;
                    break;
                }

                if (categories[ii] == ConfigUtils.CATID_OPCHDAServer10)
                {
                    endpoint.ComIdentity.Specification = ComSpecification.HDA;
                    break;
                }
            }

            return endpoint;
        }
        public async Task<IActionResult> Post([FromRoute] string tenantName, [FromBody] TenantApplicationParams parameters)
        {
            // First create the application instance.
            // This won't actually create the services yet.
            ApplicationDescription application = new ApplicationDescription(
                new Uri($"{Names.TenantApplicationNamePrefix}/{tenantName}"),
                Names.TenantApplicationTypeName,
                parameters.Version);

            await this.fabricClient.ApplicationManager.CreateApplicationAsync(application, this.operationTimeout, this.serviceCancellationToken);

            // Now create the data service in the new application instance.
            ServiceUriBuilder dataServiceNameUriBuilder = new ServiceUriBuilder(application.ApplicationName.ToString(), Names.TenantDataServiceName);
            StatefulServiceDescription dataServiceDescription = new StatefulServiceDescription()
            {
                ApplicationName = application.ApplicationName,
                HasPersistedState = true,
                MinReplicaSetSize = 3,
                TargetReplicaSetSize = 3,
                PartitionSchemeDescription = new UniformInt64RangePartitionSchemeDescription(parameters.DataPartitionCount, Int64.MinValue, Int64.MaxValue),
                ServiceName = dataServiceNameUriBuilder.Build(),
                ServiceTypeName = Names.TenantDataServiceTypeName
            };

            await this.fabricClient.ServiceManager.CreateServiceAsync(dataServiceDescription, this.operationTimeout, this.serviceCancellationToken);

            // And finally, create the web service in the new application instance.
            ServiceUriBuilder webServiceNameUriBuilder = new ServiceUriBuilder(application.ApplicationName.ToString(), Names.TenantWebServiceName);
            StatelessServiceDescription webServiceDescription = new StatelessServiceDescription()
            {
                ApplicationName = application.ApplicationName,
                InstanceCount = parameters.WebInstanceCount,
                PartitionSchemeDescription = new SingletonPartitionSchemeDescription(),
                ServiceName = webServiceNameUriBuilder.Build(),
                ServiceTypeName = Names.TenantWebServiceTypeName
            };

            await this.fabricClient.ServiceManager.CreateServiceAsync(webServiceDescription, this.operationTimeout, this.serviceCancellationToken);


            return this.Ok();
        }
Exemple #4
0
        /// <summary>
        /// Displays the dialog.
        /// </summary>
        public ApplicationDescription ShowDialog(string hostname, ApplicationConfiguration configuration)
        {
            m_configuration = configuration;

            if (String.IsNullOrEmpty(hostname))
            {
                hostname = Utils.GetHostName();
            }

            m_hostname = hostname;
            m_server   = null;

            List <string> hostnames = new List <string>();

            HostNameCTRL.Initialize(hostname, hostnames);
            ServersCTRL.Initialize(hostname, configuration);

            OkBTN.IsEnabled = false;

            return(m_server);
        }
        /// <summary>
        /// Displays the dialog.
        /// </summary>
        public ApplicationDescription ShowDialog(string hostname, ApplicationConfiguration configuration)
        {
            m_configuration = configuration;

            if (String.IsNullOrEmpty(hostname))
            {
                hostname = Utils.GetHostName();
            }

            m_hostname = hostname;
            m_server = null;

            List<string> hostnames = new List<string>();

            HostNameCTRL.Initialize(hostname, hostnames);
            ServersCTRL.Initialize(hostname, configuration);

            OkBTN.IsEnabled = false;

            return m_server;
        }
        private string SelectDiscoveryUrl(ApplicationDescription server)
        {
            if (server == null || server.DiscoveryUrls == null)
            {
                return(null);
            }

            string url = null;

            // always use opc.tcp by default.
            foreach (string discoveryUrl in server.DiscoveryUrls)
            {
                if (discoveryUrl.StartsWith("opc.tcp://"))
                {
                    url = discoveryUrl;
                    break;
                }
            }

            // try HTTPS if no opc.tcp.
            if (url == null)
            {
                foreach (string discoveryUrl in server.DiscoveryUrls)
                {
                    if (discoveryUrl.StartsWith("https://"))
                    {
                        url = discoveryUrl;
                        break;
                    }
                }
            }

            // use the first URL if nothing else.
            if (url == null)
            {
                url = server.DiscoveryUrls[0];
            }

            return(url);
        }
        /// <summary>
        /// Attempts fetch the list of servers from the discovery server.
        /// </summary>
        private void OnDiscoverEndpoints(object state)
        {
            int discoverCount = m_discoverCount;

            // do nothing if a valid list is not provided.
            ApplicationDescription server = state as ApplicationDescription;

            if (server == null)
            {
                return;
            }

            OnUpdateStatus("Attempting to read latest configuration options from server.");

            // process each url.
            foreach (string discoveryUrl in server.DiscoveryUrls)
            {
                Uri url = Utils.ParseUri(discoveryUrl);

                if (url != null)
                {
                    if (DiscoverEndpoints(url))
                    {
                        m_discoverySucceeded = true;
                        m_discoveryUrl       = url;
                        OnUpdateStatus("Configuration options are up to date.");
                        return;
                    }

                    // check if another discover operation has started.
                    if (discoverCount != m_discoverCount)
                    {
                        return;
                    }
                }
            }

            OnUpdateEndpoints(null);
            OnUpdateStatus("Configuration options may not be correct because the server is not available.");
        }
Exemple #8
0
        private void ServersLV_SelectedIndexChanged(object sender, EventArgs e)
        {
            try {
                if (ServerCTRL.Session == null)
                {
                    return;
                }

                foreach (ListViewItem item in ServersLV.SelectedItems)
                {
                    m_application = item.Tag as ApplicationDescription;
                    OkBTN.Enabled = m_application.ApplicationType == ApplicationType.Server ||
                                    m_application.ApplicationType == ApplicationType.ClientAndServer;
                    return;
                }

                m_application = null;
                OkBTN.Enabled = false;
            } catch (Exception exception) {
                ClientUtils.HandleException(this.Text, exception);
            }
        }
Exemple #9
0
        public async Task LoadCertificate()
        {
            using (var dir = TempDirectory.Create())
            {
                var store = new DirectoryStore(dir.Name, createLocalCertificateIfNotExist: true);

                var app = new ApplicationDescription
                {
                    ApplicationUri = "urn:hostname:appname",
                };

                var(cert1, key1) = await store.GetLocalCertificateAsync(app);

                var(cert2, key2) = await store.GetLocalCertificateAsync(app);

                cert1
                .Should().Be(cert2);

                key1
                .Should().Be(key2);
            }
        }
Exemple #10
0
        public async Task Connect()
        {
            // describe this client application.
            var clientDescription = new ApplicationDescription
            {
                ApplicationName = "Workstation.UaClient.FeatureTests",
                ApplicationUri  = $"urn:{System.Net.Dns.GetHostName()}:Workstation.UaClient.FeatureTests",
                ApplicationType = ApplicationType.Client
            };

            // create a 'UaTcpSessionChannel', a client-side channel that opens a 'session' with the server.
            var channel = new UaTcpSessionChannel(
                clientDescription,
                null,                        // no x509 client certificate
                new AnonymousIdentity(),     // the anonymous identity
                "opc.tcp://localhost:48010", // the endpoint of Unified Automation's UaCPPServer.
                SecurityPolicyUris.None);

            try
            {
                // try opening a session and reading a few nodes.
                await channel.OpenAsync();

                // success! client session opened with these settings.
                Console.WriteLine($"Opened session with endpoint '{channel.RemoteEndpoint.EndpointUrl}'.");
                Console.WriteLine($"SecurityPolicy: '{channel.RemoteEndpoint.SecurityPolicyUri}'.");
                Console.WriteLine($"SecurityMode: '{channel.RemoteEndpoint.SecurityMode}'.");
                Console.WriteLine($"UserIdentityToken: '{channel.UserIdentity}'.");

                Console.WriteLine($"Closing session '{channel.SessionId}'.");
                await channel.CloseAsync();
            }
            catch (Exception ex)
            {
                await channel.AbortAsync();

                Console.WriteLine(ex.Message);
            }
        }
Exemple #11
0
        public async Task CreateCertificate()
        {
            using (var dir = TempDirectory.Create())
            {
                var store = new DirectoryStore(dir.Name, createLocalCertificateIfNotExist: true);

                var app = new ApplicationDescription
                {
                    ApplicationUri = "http://hostname/appname",
                };

                var(cert, key) = await store.GetLocalCertificateAsync(app);

                cert
                .Should().NotBeNull();
                key
                .Should().NotBeNull();

                cert.SubjectDN.ToString()
                .Should().Be("CN=appname,DC=hostname");
            }
        }
        public async Task ExecuteAsync(RestartApplication command, CancellationToken cancellationToken)
        {
            var types = await _fabricClient.QueryManager.GetApplicationTypeListAsync(command.ApplicationType);

            if (types?.Any() ?? false)
            {
                var applications = await _fabricClient.QueryManager.GetApplicationListAsync(command.ApplicationUri);

                if (applications?.Any() ?? false)
                {
                    DeleteApplicationDescription delete = new DeleteApplicationDescription(command.ApplicationUri);
                    await _fabricClient.ApplicationManager.DeleteApplicationAsync(delete);
                }

                ApplicationDescription applicationDescription = new ApplicationDescription(command.ApplicationUri, command.ApplicationType, command.ApplicationVersion);
                await _fabricClient.ApplicationManager.CreateApplicationAsync(applicationDescription);
            }
            else
            {
                throw new ArgumentException($"Application type '{command.ApplicationType}' not deployed to the cluster.");
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="UaTcpSessionChannel"/> class.
 /// </summary>
 /// <param name="localDescription">The <see cref="ApplicationDescription"/> of the local application.</param>
 /// <param name="certificateStore">The local certificate store.</param>
 /// <param name="userIdentityProvider">An asynchronous function that provides the user identity. Provide an <see cref="AnonymousIdentity"/>, <see cref="UserNameIdentity"/>, <see cref="IssuedIdentity"/> or <see cref="X509Identity"/>.</param>
 /// <param name="endpointUrl">The url of the endpoint of the remote application</param>
 /// <param name="securityPolicyUri">Optionally, filter by SecurityPolicyUri.</param>
 /// <param name="loggerFactory">The logger factory.</param>
 /// <param name="options">The session channel options.</param>
 public UaTcpSessionChannel(
     ApplicationDescription localDescription,
     ICertificateStore certificateStore,
     Func <EndpointDescription, Task <IUserIdentity> > userIdentityProvider,
     string endpointUrl,
     string securityPolicyUri           = null,
     ILoggerFactory loggerFactory       = null,
     UaTcpSessionChannelOptions options = null)
     : base(localDescription, certificateStore, new EndpointDescription {
     EndpointUrl = endpointUrl, SecurityPolicyUri = securityPolicyUri
 }, loggerFactory, options)
 {
     this.UserIdentityProvider = userIdentityProvider;
     this.options          = options ?? new UaTcpSessionChannelOptions();
     this.loggerFactory    = loggerFactory;
     this.logger           = loggerFactory?.CreateLogger <UaTcpSessionChannel>();
     this.actionBlock      = new ActionBlock <PublishResponse>(pr => this.OnPublishResponse(pr));
     this.stateMachineCts  = new CancellationTokenSource();
     this.publishResponses = new BroadcastBlock <PublishResponse>(null, new DataflowBlockOptions {
         CancellationToken = this.stateMachineCts.Token
     });
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="UaTcpSessionChannel"/> class.
 /// </summary>
 /// <param name="localDescription">The <see cref="ApplicationDescription"/> of the local application.</param>
 /// <param name="certificateStore">The local certificate store.</param>
 /// <param name="userIdentity">The user identity. Provide an <see cref="AnonymousIdentity"/>, <see cref="UserNameIdentity"/>, <see cref="IssuedIdentity"/> or <see cref="X509Identity"/>.</param>
 /// <param name="endpointUrl">The url of the endpoint of the remote application</param>
 /// <param name="securityPolicyUri">Optionally, filter by SecurityPolicyUri.</param>
 /// <param name="loggerFactory">The logger factory.</param>
 /// <param name="options">The session channel options.</param>
 public UaTcpSessionChannel(
     ApplicationDescription localDescription,
     ICertificateStore?certificateStore,
     IUserIdentity?userIdentity,
     string endpointUrl,
     string?securityPolicyUri           = null,
     ILoggerFactory?loggerFactory       = null,
     UaTcpSessionChannelOptions?options = null)
     : base(localDescription, certificateStore, new EndpointDescription {
     EndpointUrl = endpointUrl, SecurityPolicyUri = securityPolicyUri
 }, loggerFactory, options)
 {
     UserIdentity      = userIdentity;
     _options          = options ?? new UaTcpSessionChannelOptions();
     _loggerFactory    = loggerFactory;
     _logger           = loggerFactory?.CreateLogger <UaTcpSessionChannel>();
     _actionBlock      = new ActionBlock <PublishResponse>(pr => OnPublishResponse(pr));
     _stateMachineCts  = new CancellationTokenSource();
     _publishResponses = new BroadcastBlock <PublishResponse>(null, new DataflowBlockOptions {
         CancellationToken = _stateMachineCts.Token
     });
 }
Exemple #15
0
        /// <inheritdoc />
        public Task CreateApplicationAsync(
            ApplicationDescription applicationDescription,
            long?serverTimeout = 60,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            applicationDescription.ThrowIfNull(nameof(applicationDescription));
            serverTimeout?.ThrowIfOutOfInclusiveRange("serverTimeout", 1, 4294967295);
            var requestId   = Guid.NewGuid().ToString();
            var url         = "Applications/$/Create";
            var queryParams = new List <string>();

            // Append to queryParams if not null.
            serverTimeout?.AddToQueryParameters(queryParams, $"timeout={serverTimeout}");
            queryParams.Add("api-version=6.0");
            url += "?" + string.Join("&", queryParams);

            string content;

            using (var sw = new StringWriter())
            {
                ApplicationDescriptionConverter.Serialize(new JsonTextWriter(sw), applicationDescription);
                content = sw.ToString();
            }

            HttpRequestMessage RequestFunc()
            {
                var request = new HttpRequestMessage()
                {
                    Method  = HttpMethod.Post,
                    Content = new StringContent(content, Encoding.UTF8)
                };

                request.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
                return(request);
            }

            return(this.httpClient.SendAsync(RequestFunc, url, requestId, cancellationToken));
        }
Exemple #16
0
        /// <summary>
        /// Returns the endpoints that match the base addresss and endpoint url.
        /// </summary>
        protected EndpointDescriptionCollection GetEndpointDescriptions(
            string endpointUrl,
            IList <BaseAddress> baseAddresses,
            StringCollection localeIds)
        {
            EndpointDescriptionCollection endpoints = null;

            // parse the url provided by the client.
            Uri parsedEndpointUrl = Utils.ParseUri(endpointUrl);

            if (parsedEndpointUrl != null)
            {
                baseAddresses = FilterByEndpointUrl(parsedEndpointUrl, baseAddresses);
            }

            // check if nothing to do.
            if (baseAddresses.Count != 0)
            {
                // localize the application name if requested.
                LocalizedText applicationName = this.ServerDescription.ApplicationName;

                // translate the application description.
                ApplicationDescription application = TranslateApplicationDescription(
                    parsedEndpointUrl,
                    ServerDescription,
                    baseAddresses,
                    applicationName);

                // translate the endpoint descriptions.
                endpoints = TranslateEndpointDescriptions(
                    parsedEndpointUrl,
                    baseAddresses,
                    Endpoints,
                    application);
            }

            return(endpoints);
        }
Exemple #17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ClientSessionChannel"/> class.
 /// </summary>
 /// <param name="localDescription">The <see cref="ApplicationDescription"/> of the local application.</param>
 /// <param name="certificateStore">The local certificate store.</param>
 /// <param name="userIdentityProvider">An asynchronous function that provides the user identity. Provide an <see cref="AnonymousIdentity"/>, <see cref="UserNameIdentity"/>, <see cref="IssuedIdentity"/> or <see cref="X509Identity"/>.</param>
 /// <param name="endpointUrl">The url of the endpoint of the remote application</param>
 /// <param name="securityPolicyUri">Optionally, filter by SecurityPolicyUri.</param>
 /// <param name="loggerFactory">The logger factory.</param>
 /// <param name="options">The session channel options.</param>
 public ClientSessionChannel(
     ApplicationDescription localDescription,
     ICertificateStore certificateStore,
     Func <EndpointDescription, Task <IUserIdentity> > userIdentityProvider,
     string endpointUrl,
     string?securityPolicyUri            = null,
     ILoggerFactory?loggerFactory        = null,
     ClientSessionChannelOptions?options = null,
     StackProfile?stackProfile           = null)
     : base(localDescription, certificateStore, new EndpointDescription {
     EndpointUrl = endpointUrl, SecurityPolicyUri = securityPolicyUri
 }, loggerFactory, options, stackProfile)
 {
     UserIdentityProvider = userIdentityProvider;
     _options             = options ?? new ClientSessionChannelOptions();
     _loggerFactory       = loggerFactory;
     _logger           = loggerFactory?.CreateLogger <ClientSessionChannel>();
     _actionBlock      = new ActionBlock <PublishResponse>(pr => OnPublishResponse(pr));
     _stateMachineCts  = new CancellationTokenSource();
     _publishResponses = new BroadcastBlock <PublishResponse>(null, new DataflowBlockOptions {
         CancellationToken = _stateMachineCts.Token
     });
 }
        static async Task DeployAsync(string applicationPackagePath, ApplicationDescription applicationDescription)
        {
            var clusterManifest    = new XmlDocument();
            var clusterManifestXml = await client.ClusterManager.GetClusterManifestAsync();

            clusterManifest.LoadXml(clusterManifestXml);
            var namespaceManager = new XmlNamespaceManager(clusterManifest.NameTable);

            namespaceManager.AddNamespace("sf", "http://schemas.microsoft.com/2011/01/fabric");
            var imageStoreConnectionStringPath = "/sf:ClusterManifest/sf:FabricSettings/sf:Section[@Name='Management']/sf:Parameter[@Name='ImageStoreConnectionString']";
            var imageStoreConnectionStringNode = clusterManifest.DocumentElement.SelectSingleNode(imageStoreConnectionStringPath, namespaceManager);
            var imageStoreConnectionString     = imageStoreConnectionStringNode.Attributes["Value"].Value;

            var path = Guid.NewGuid().ToString();

            client.ApplicationManager.CopyApplicationPackage(imageStoreConnectionString, applicationPackagePath, path);

            await client.ApplicationManager.ProvisionApplicationAsync(path);

            client.ApplicationManager.RemoveApplicationPackage(imageStoreConnectionString, path);

            await client.ApplicationManager.CreateApplicationAsync(applicationDescription);
        }
Exemple #19
0
        public override async Task <Group[]> Initialize(Adapter config, AdapterCallback callback, DataItemInfo[] itemInfos)
        {
            this.config   = config;
            this.callback = callback;

            string appName = "Mediator.IO.OPC_UA";

            appDescription = new ApplicationDescription {
                ApplicationName = appName,
                ApplicationUri  = $"urn:{Dns.GetHostName()}:{appName}",
                ApplicationType = ApplicationType.Client
            };

            this.mapId2Info = config.GetAllDataItems().Where(di => !string.IsNullOrEmpty(di.Address)).ToDictionary(
                item => /* key */ item.ID,
                item => /* val */ new ItemInfo(item.ID, item.Name, item.Type, item.Dimension, item.Address));

            PrintLine(config.Address);

            await TryConnect();

            return(new Group[0]);
        }
Exemple #20
0
        private void DiscoverServersOnNetworkMI_Click(object sender, EventArgs e)
        {
            try {
                ServerOnNetwork serverOnNetwork =
                    new DiscoveredServerOnNetworkListDlg().ShowDialog(null, m_configuration);

                if (serverOnNetwork != null)
                {
                    ApplicationDescription server = new ApplicationDescription();
                    server.ApplicationName = serverOnNetwork.ServerName;
                    server.DiscoveryUrls.Add(serverOnNetwork.DiscoveryUrl);

                    ConfiguredEndpoint endpoint =
                        new ConfiguredEndpoint(server, EndpointConfiguration.Create(m_configuration));

                    this.EndpointSelectorCTRL.SelectedEndpoint = endpoint;

                    return;
                }
            } catch (Exception exception) {
                GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
            }
        }
        public async Task GivenTheServiceFabricApplicationInstanceExists(string applicationName, string applicationTypeName)
        {
            var types = await _fabricClient.QueryManager.GetApplicationTypeListAsync(applicationTypeName);

            if (types?.Any() ?? false)
            {
                var applicationUri = new Uri(applicationName);
                var applications   = await _fabricClient.QueryManager.GetApplicationListAsync(applicationUri);

                if (applications?.Any() ?? false)
                {
                    DeleteApplicationDescription delete = new DeleteApplicationDescription(applicationUri);
                    await _fabricClient.ApplicationManager.DeleteApplicationAsync(delete);
                }

                ApplicationDescription applicationDescription = new ApplicationDescription(applicationUri, applicationTypeName, _applicationTypeVersion);
                await _fabricClient.ApplicationManager.CreateApplicationAsync(applicationDescription);
            }
            else
            {
                throw new ArgumentException($"Application type '{applicationTypeName}' not deployed to the cluster.");
            }
        }
        /// <summary>
        /// Updates an item in the control.
        /// </summary>
        public void UpdateItem(ListViewItem listItem, object item)
        {
            ApplicationDescription server = listItem.Tag as ApplicationDescription;

            if (server == null)
            {
                listItem.Tag = server;
                return;
            }

            string hostname = "";

            // extract host from application uri.
            Uri uri = Utils.ParseUri(server.ApplicationUri);

            if (uri != null)
            {
                hostname = uri.DnsSafeHost;
            }

            // get the host name from the discovery urls.
            if (String.IsNullOrEmpty(hostname))
            {
                foreach (string discoveryUrl in server.DiscoveryUrls)
                {
                    Uri url = Utils.ParseUri(discoveryUrl);

                    if (url != null)
                    {
                        hostname = url.DnsSafeHost;
                        break;
                    }
                }
            }

            listItem.Content = String.Format("Name: {0}, type: {1}, host: {2}, URI: {3}", server.ApplicationName, server.ApplicationType, hostname, server.ApplicationUri);
        }
        static async Task Reset()
        {
            WriteConsole("Resetting test...");
            FabricClient client = new FabricClient();
            var          types  = await client.QueryManager.GetApplicationTypeListAsync(NoOpApplicationTypeName);

            if (types?.Any() ?? false)
            {
                var applications = await client.QueryManager.GetApplicationListAsync(NoOpApplicationName);

                if (applications?.Any() ?? false)
                {
                    DeleteApplicationDescription delete = new DeleteApplicationDescription(NoOpApplicationName);
                    await client.ApplicationManager.DeleteApplicationAsync(delete);
                }

                ApplicationDescription applicationDescription = new ApplicationDescription(NoOpApplicationName, NoOpApplicationTypeName, NoOpApplicationVersion);
                await client.ApplicationManager.CreateApplicationAsync(applicationDescription);
            }
            else
            {
                throw new ArgumentException($"Application type '{NoOpApplicationTypeName}' not deployed to the cluster.");
            }
        }
        /// <summary>
        /// Serializes the object to JSON.
        /// </summary>
        /// <param name="writer">The <see cref="T: Newtonsoft.Json.JsonWriter" /> to write to.</param>
        /// <param name="obj">The object to serialize to JSON.</param>
        internal static void Serialize(JsonWriter writer, ApplicationDescription obj)
        {
            // Required properties are always serialized, optional properties are serialized when not null.
            writer.WriteStartObject();
            writer.WriteProperty(obj.Name, "Name", ApplicationNameConverter.Serialize);
            writer.WriteProperty(obj.TypeName, "TypeName", JsonWriterExtensions.WriteStringValue);
            writer.WriteProperty(obj.TypeVersion, "TypeVersion", JsonWriterExtensions.WriteStringValue);
            if (obj.Parameters != null)
            {
                writer.WriteProperty(obj.Parameters, "ParameterList", ApplicationParametersConverter.Serialize);
            }

            if (obj.ApplicationCapacity != null)
            {
                writer.WriteProperty(obj.ApplicationCapacity, "ApplicationCapacity", ApplicationCapacityDescriptionConverter.Serialize);
            }

            if (obj.ManagedApplicationIdentity != null)
            {
                writer.WriteProperty(obj.ManagedApplicationIdentity, "ManagedApplicationIdentity", ManagedApplicationIdentityDescriptionConverter.Serialize);
            }

            writer.WriteEndObject();
        }
        private ApplicationDescription GetApplicationDescription(ServerOnNetwork server)
        {
            ApplicationDescription fallback = null;

            try
            {
                foreach (var application in m_lds.FindServers(server.DiscoveryUrl, null))
                {
                    if (fallback == null)
                    {
                        fallback = application;
                    }

                    if (application.DiscoveryUrls != null)
                    {
                        if (application.DiscoveryUrls.Contains(server.DiscoveryUrl))
                        {
                            return(application);
                        }
                    }
                }
            }
            catch (Exception)
            {
                fallback = new ApplicationDescription()
                {
                    ApplicationType = ApplicationType.Server,
                    ApplicationName = server.ServerName,
                    ApplicationUri  = server.DiscoveryUrl
                };

                fallback.DiscoveryUrls.Add(server.DiscoveryUrl);
            }

            return(fallback);
        }
Exemple #26
0
        public void Open(
            string        sessionName,
            uint          sessionTimeout,
            IUserIdentity identity,
            IList<string> preferredLocales,
            bool          checkDomain)
        {
            // check connection state.
            lock (SyncRoot)
            {
                if (Connected)
                {
                    throw new ServiceResultException(StatusCodes.BadInvalidState, "Already connected to server.");
                }
            }

            string securityPolicyUri = m_endpoint.Description.SecurityPolicyUri;

            // get the identity token.            
            if (identity == null)
            {
                identity = new UserIdentity();
            }

            // get identity token.
            UserIdentityToken identityToken = identity.GetIdentityToken();

            // check that the user identity is supported by the endpoint.
            UserTokenPolicy identityPolicy = m_endpoint.Description.FindUserTokenPolicy(identityToken.PolicyId);

            if (identityPolicy == null)
            {
                // try looking up by TokenType if the policy id was not found.
                identityPolicy = m_endpoint.Description.FindUserTokenPolicy(identity.TokenType, identity.IssuedTokenType);

                if (identityPolicy == null)
                {
                    throw ServiceResultException.Create(
                        StatusCodes.BadUserAccessDenied,
                        "Endpoint does not supported the user identity type provided.");
                }

                identityToken.PolicyId = identityPolicy.PolicyId;
            }

            bool requireEncryption = securityPolicyUri != SecurityPolicies.None;

            if (!requireEncryption)
            {
                requireEncryption = identityPolicy.SecurityPolicyUri != SecurityPolicies.None && 
                    !String.IsNullOrEmpty(identityPolicy.SecurityPolicyUri);
            }

            // validate the server certificate.
            X509Certificate2 serverCertificate = null;
            byte[] certificateData = m_endpoint.Description.ServerCertificate;

            if (certificateData != null && certificateData.Length > 0 && requireEncryption)
            {
                serverCertificate = Utils.ParseCertificateBlob(certificateData);
                m_configuration.CertificateValidator.Validate(serverCertificate);

                if(checkDomain)
                {
                    CheckCertificateDomain(m_endpoint);
                }

                //X509Certificate2Collection certificateChain = Utils.ParseCertificateChainBlob(certificateData);                
                //if (certificateChain.Count > 0)
                //    serverCertificate = certificateChain[0];
                //m_configuration.CertificateValidator.Validate(certificateChain);
            }

            // create a nonce.
            byte[] clientNonce = new byte[m_configuration.SecurityConfiguration.NonceLength];
            new RNGCryptoServiceProvider().GetBytes(clientNonce);
            
                        
            NodeId sessionId = null;
            NodeId sessionCookie = null;
            byte[] serverNonce = new byte[0];
            byte[] serverCertificateData = new byte[0];
            SignatureData serverSignature = null;
            EndpointDescriptionCollection serverEndpoints = null;
            SignedSoftwareCertificateCollection serverSoftwareCertificates = null;
                                   
            // send the application instance certificate for the client.
            byte[] clientCertificateData = m_instanceCertificate != null ? m_instanceCertificate.RawData : null;

            //byte[] clientCertificateData = null;
            //if (m_instanceCertificateChain != null)
            //{
            //    List<byte> clientCertificateChainData = new List<byte>();
            //    for (int i = 0; i < m_instanceCertificateChain.Count; i++)
            //    {
            //        clientCertificateChainData.AddRange(m_instanceCertificateChain[i].RawData);
            //    }

            //    clientCertificateData = clientCertificateChainData.ToArray();
            //}
                                
            ApplicationDescription clientDescription = new ApplicationDescription();

            clientDescription.ApplicationUri  = m_configuration.ApplicationUri;
            clientDescription.ApplicationName = m_configuration.ApplicationName;
            clientDescription.ApplicationType = ApplicationType.Client;
            clientDescription.ProductUri      = m_configuration.ProductUri;
            
            if (sessionTimeout == 0)
            {
                sessionTimeout = (uint)m_configuration.ClientConfiguration.DefaultSessionTimeout;
            }

            bool successCreateSession = false;
            //if security none, first try to connect without certificate
            if (m_endpoint.Description.SecurityPolicyUri == SecurityPolicies.None)
            {
                //first try to connect with client certificate NULL
                try
                {
                    CreateSession(
                        null,
                        clientDescription,
                        m_endpoint.Description.Server.ApplicationUri,
                        m_endpoint.EndpointUrl.ToString(),
                        sessionName,
                        clientNonce,
                        null,
                        sessionTimeout,
                        (uint)MessageContext.MaxMessageSize,
                        out sessionId,
                        out sessionCookie,
                        out m_sessionTimeout,
                        out serverNonce,
                        out serverCertificateData,
                        out serverEndpoints,
                        out serverSoftwareCertificates,
                        out serverSignature,
                        out m_maxRequestMessageSize);

                    successCreateSession = true;
                }
                catch(Exception ex)
                {
                    Utils.Trace("Create session failed with client certificate NULL. " + ex.Message);
                    successCreateSession = false;
                }
            }

            if (!successCreateSession)
            {
                CreateSession(
                        null,
                        clientDescription,
                        m_endpoint.Description.Server.ApplicationUri,
                        m_endpoint.EndpointUrl.ToString(),
                        sessionName,
                        clientNonce,
                        clientCertificateData,
                        sessionTimeout,
                        (uint)MessageContext.MaxMessageSize,
                        out sessionId,
                        out sessionCookie,
                        out m_sessionTimeout,
                        out serverNonce,
                        out serverCertificateData,
                        out serverEndpoints,
                        out serverSoftwareCertificates,
                        out serverSignature,
                        out m_maxRequestMessageSize);

            }
            // save session id.
            lock (SyncRoot)
            {
                base.SessionCreated(sessionId, sessionCookie);
            }

            Utils.Trace("Revised session timeout value: {0}. ", m_sessionTimeout);
            Utils.Trace("Max response message size value: {0}. Max request message size: {1} ", MessageContext.MaxMessageSize, m_maxRequestMessageSize);

			//we need to call CloseSession if CreateSession was successful but some other exception is thrown
			try
			{

				// verify that the server returned the same instance certificate.
                if (serverCertificateData != null && !Utils.IsEqual(serverCertificateData, m_endpoint.Description.ServerCertificate))
				{
					throw ServiceResultException.Create(
						StatusCodes.BadCertificateInvalid,
						"Server did not return the certificate used to create the secure channel." );
				}

                if (serverSignature == null || serverSignature.Signature == null)
                {
                    Utils.Trace("Server signature is null or empty.");

                    //throw ServiceResultException.Create(
                    //    StatusCodes.BadSecurityChecksFailed,
                    //    "Server signature is null or empty.");
                }

                if (m_expectedServerEndpoints != null && m_expectedServerEndpoints.Count > 0)
                {
                    // verify that the list of endpoints returned by CreateSession matches the list returned at GetEndpoints.
                    if (m_expectedServerEndpoints.Count != serverEndpoints.Count)
                    {
                        throw ServiceResultException.Create(
                            StatusCodes.BadSecurityChecksFailed,
                            "Server did not return a number of ServerEndpoints that matches the one from GetEndpoints.");
                    }

                    for (int ii = 0; ii < serverEndpoints.Count; ii++)
                    {
                        EndpointDescription serverEndpoint = serverEndpoints[ii];
                        EndpointDescription expectedServerEndpoint = m_expectedServerEndpoints[ii];

                        if (serverEndpoint.SecurityMode != expectedServerEndpoint.SecurityMode ||
                            serverEndpoint.SecurityPolicyUri != expectedServerEndpoint.SecurityPolicyUri ||
                            serverEndpoint.TransportProfileUri != expectedServerEndpoint.TransportProfileUri ||
                            serverEndpoint.SecurityLevel != expectedServerEndpoint.SecurityLevel)
                        {
                            throw ServiceResultException.Create(
                                StatusCodes.BadSecurityChecksFailed,
                                "The list of ServerEndpoints returned at CreateSession does not match the list from GetEndpoints.");
                        }

                        if (serverEndpoint.UserIdentityTokens.Count != expectedServerEndpoint.UserIdentityTokens.Count)
                        {
                            throw ServiceResultException.Create(
                                StatusCodes.BadSecurityChecksFailed,
                                "The list of ServerEndpoints returned at CreateSession does not match the one from GetEndpoints.");
                        }

                        for (int jj = 0; jj < serverEndpoint.UserIdentityTokens.Count; jj++)
                        {
                            if (!serverEndpoint.UserIdentityTokens[jj].IsEqual(expectedServerEndpoint.UserIdentityTokens[jj]))
                            {
                                throw ServiceResultException.Create(
                                StatusCodes.BadSecurityChecksFailed,
                                "The list of ServerEndpoints returned at CreateSession does not match the one from GetEndpoints.");
                            }
                        }
                    }
                }


				// find the matching description (TBD - check domains against certificate).
				bool found = false;
				Uri expectedUrl = Utils.ParseUri( m_endpoint.Description.EndpointUrl );

                if (expectedUrl != null)
                {
                    for (int ii = 0; ii < serverEndpoints.Count; ii++)
                    {
                        EndpointDescription serverEndpoint = serverEndpoints[ii];
                        Uri actualUrl = Utils.ParseUri(serverEndpoint.EndpointUrl);

                        if (actualUrl != null && actualUrl.Scheme == expectedUrl.Scheme)
                        {
                            if (serverEndpoint.SecurityPolicyUri == m_endpoint.Description.SecurityPolicyUri)
                            {
                                if (serverEndpoint.SecurityMode == m_endpoint.Description.SecurityMode)
                                {
                                    // ensure endpoint has up to date information.
                                    m_endpoint.Description.Server.ApplicationName = serverEndpoint.Server.ApplicationName;
                                    m_endpoint.Description.Server.ApplicationUri = serverEndpoint.Server.ApplicationUri;
                                    m_endpoint.Description.Server.ApplicationType = serverEndpoint.Server.ApplicationType;
                                    m_endpoint.Description.Server.ProductUri = serverEndpoint.Server.ProductUri;
                                    m_endpoint.Description.TransportProfileUri = serverEndpoint.TransportProfileUri;
                                    m_endpoint.Description.UserIdentityTokens = serverEndpoint.UserIdentityTokens;

                                    found = true;
                                    break;
                                }
                            }
                        }
                    }
                }

				// could be a security risk.
				if( !found )
				{
					throw ServiceResultException.Create(
						StatusCodes.BadSecurityChecksFailed,
						"Server did not return an EndpointDescription that matched the one used to create the secure channel." );
				}

				// validate the server's signature.
				byte[] dataToSign = Utils.Append( clientCertificateData, clientNonce );

                if (!SecurityPolicies.Verify(serverCertificate, m_endpoint.Description.SecurityPolicyUri, dataToSign, serverSignature))
				{
					throw ServiceResultException.Create(
						StatusCodes.BadApplicationSignatureInvalid,
						"Server did not provide a correct signature for the nonce data provided by the client." );
				}

				// get a validator to check certificates provided by server.
				CertificateValidator validator = m_configuration.CertificateValidator;

				// validate software certificates.
				List<SoftwareCertificate> softwareCertificates = new List<SoftwareCertificate>();

				foreach( SignedSoftwareCertificate signedCertificate in serverSoftwareCertificates )
				{
					SoftwareCertificate softwareCertificate = null;

					ServiceResult result = SoftwareCertificate.Validate(
						validator,
						signedCertificate.CertificateData,
						out softwareCertificate );

					if( ServiceResult.IsBad( result ) )
					{
						OnSoftwareCertificateError( signedCertificate, result );
					}

					softwareCertificates.Add( softwareCertificate );
				}

				// check if software certificates meet application requirements.
				ValidateSoftwareCertificates( softwareCertificates );

				// create the client signature.
				dataToSign = Utils.Append( serverCertificateData, serverNonce );
				SignatureData clientSignature = SecurityPolicies.Sign( m_instanceCertificate, securityPolicyUri, dataToSign );

                // select the security policy for the user token.
                securityPolicyUri = identityPolicy.SecurityPolicyUri;

                if (String.IsNullOrEmpty(securityPolicyUri))
                {
                    securityPolicyUri = m_endpoint.Description.SecurityPolicyUri;
                }

				// sign data with user token.
				SignatureData userTokenSignature = identityToken.Sign( dataToSign, securityPolicyUri );

				// encrypt token.
				identityToken.Encrypt( serverCertificate, serverNonce, securityPolicyUri );

				// send the software certificates assigned to the client.
				SignedSoftwareCertificateCollection clientSoftwareCertificates = GetSoftwareCertificates();

				// copy the preferred locales if provided.
				if( preferredLocales != null && preferredLocales.Count > 0 )
				{
					m_preferredLocales = new StringCollection( preferredLocales );
				}

				StatusCodeCollection certificateResults = null;
				DiagnosticInfoCollection certificateDiagnosticInfos = null;

				// activate session.
				ActivateSession(
					null,
					clientSignature,
					clientSoftwareCertificates,
					m_preferredLocales,
					new ExtensionObject( identityToken ),
					userTokenSignature,
					out serverNonce,
					out certificateResults,
					out certificateDiagnosticInfos );

                if (certificateResults != null)
                {
                    for (int i = 0; i < certificateResults.Count; i++)
                    {
                        Utils.Trace("ActivateSession result[{0}] = {1}", i, certificateResults[i]);    
                    }
                }

                if (certificateResults == null || certificateResults.Count == 0)
                {
                    Utils.Trace("Empty results were received for the ActivateSession call.");
                }

				// fetch namespaces.
				FetchNamespaceTables();

				lock( SyncRoot )
				{
					// save nonces.
					m_sessionName = sessionName;
					m_identity = identity;
					m_serverNonce = serverNonce;
					m_serverCertificate = serverCertificate;

					// update system context.
					m_systemContext.PreferredLocales = m_preferredLocales;
					m_systemContext.SessionId = this.SessionId;
					m_systemContext.UserIdentity = identity;
				}

            // start keep alive thread.
            StartKeepAliveTimer();
			}
			catch
			{
				try
				{
					CloseSession( null, false );
					CloseChannel();
				}
				catch(Exception e)
				{
                    Utils.Trace("Cleanup: CloseSession() or CloseChannel() raised exception. " + e.Message);
				}
				finally
				{
					SessionCreated( null, null );
				}

				throw;
			}
        }
        /// <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);
        }
        /// <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);
        }
Exemple #29
0
        /// <inheritdoc/>
        /// <summary>
        /// Create a new service host for UA HTTPS.
        /// </summary>
        public List <EndpointDescription> CreateServiceHost(
            ServerBase serverBase,
            IDictionary <string, Task> hosts,
            ApplicationConfiguration configuration,
            IList <string> baseAddresses,
            ApplicationDescription serverDescription,
            List <ServerSecurityPolicy> securityPolicies,
            X509Certificate2 instanceCertificate,
            X509Certificate2Collection instanceCertificateChain
            )
        {
            // generate a unique host name.
            string hostName = String.Empty;

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

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

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

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

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

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

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

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

                uris.Add(uri.Uri);

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

                        bestPolicy = policy;
                        break;
                    }

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

                    EndpointDescription description = new EndpointDescription();

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

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

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

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

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

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

            return(endpoints);
        }
        private void ServersLV_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ServerCTRL.Session == null)
                {
                    return;
                }

                foreach (ListViewItem item in ServersLV.SelectedItems)
                {
                    m_application = item.Tag as ApplicationDescription;
                    OkBTN.Enabled = m_application.ApplicationType == ApplicationType.Server || m_application.ApplicationType == ApplicationType.ClientAndServer;
                    return;
                }

                m_application = null;
                OkBTN.Enabled = false;
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(this.Text, exception);
            }
        }
        /// <summary>
        /// Creates a new instance of a session.
        /// </summary>
        protected virtual Session CreateSession(
            OperationContext          context,
            IServerInternal           server,
            X509Certificate2          serverCertificate,
            NodeId                    sessionCookie,
            byte[]                    serverNonce,
            string                    sessionName, 
            ApplicationDescription    clientDescription,
            string                    endpointUrl,
            X509Certificate2          clientCertificate,
            double                    sessionTimeout,
            uint                      maxResponseMessageSize,
            int                       maxRequestAge, // TBD - Remove unused parameter.
            int                       maxContinuationPoints) // TBD - Remove unused parameter.
        {
            Session session = new Session(
                context,
                m_server,
                serverCertificate,
                sessionCookie,
                serverNonce,
                sessionName,
                clientDescription,
                endpointUrl,
                clientCertificate,
                sessionTimeout,
                maxResponseMessageSize,
                m_maxRequestAge,
                m_maxBrowseContinuationPoints,
                m_maxHistoryContinuationPoints);

            return session;
        }
Exemple #32
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>();
 }
        /// <summary>
        /// Adds the results to the control.
        /// </summary>
        private void UpdateResults(ApplicationDescription[] descriptions)
        {
            ServersLV.Items.Clear();

            if (descriptions == null)
            {
                return;
            }

            for (int ii = 0; ii < descriptions.Length; ii++)
            {
                ApplicationDescription description = descriptions[ii];

                if (description == null)
                {
                    continue;
                }

                ListViewItem item = new ListViewItem();
                item.Text = Utils.Format("{0}", description.ApplicationName);
                item.ImageIndex = ClientUtils.GetImageIndex(ServerCTRL.Session, NodeClass.Object, null, false);
                item.SubItems.Add(new ListViewItem.ListViewSubItem());
                item.SubItems.Add(new ListViewItem.ListViewSubItem());
                item.SubItems.Add(new ListViewItem.ListViewSubItem());
                item.Tag = description;
                ServersLV.Items.Add(item);

                item.SubItems[1].Text = description.ApplicationType.ToString();

                if (description.DiscoveryUrls == null)
                {
                    continue;
                }
                
                // collect the domains and protocols.
                List<string> domains = new List<string>();
                List<string> protocols = new List<string>();

                foreach (string discoveryUrl in description.DiscoveryUrls)
                {
                    Uri url = Utils.ParseUri(discoveryUrl);

                    if (url != null)
                    {
                        if (!domains.Contains(url.DnsSafeHost))
                        {
                            domains.Add(url.DnsSafeHost);
                        }

                        if (!protocols.Contains(url.Scheme))
                        {
                            protocols.Add(url.Scheme);
                        }
                    }
                }

                // format the domains.
                StringBuilder buffer = new StringBuilder();

                foreach (string domain in domains)
                {
                    if (buffer.Length > 0)
                    {
                        buffer.Append(", ");
                    }

                    buffer.Append(domain);
                }

                item.SubItems[2].Text = buffer.ToString();

                // format the protocols.
                buffer = new StringBuilder();

                foreach (string protocol in protocols)
                {
                    if (buffer.Length > 0)
                    {
                        buffer.Append(", ");
                    }

                    buffer.Append(protocol);
                }

                item.SubItems[3].Text = buffer.ToString();
            }

            // adjust column widths.
            for (int ii = 0; ii < ServersLV.Columns.Count; ii++)
            {
                ServersLV.Columns[ii].Width = -2;
            }
        }
        private void ServersCTRL_ItemsPicked(object sender, ListItemActionEventArgs e)
        {
            try
            {
                m_server = null;

                foreach (ApplicationDescription server in e.Items)
                {
                    m_server = server;
                    break;
                }

                if (m_server != null)
                {
                    DialogResult = DialogResult.OK;
                }
            }
            catch (Exception exception)
            {
                GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
            }
        }
Exemple #35
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;
        }
Exemple #36
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;
        }
        /// <summary>
        /// Creates an instance of an application.
        /// </summary>
        /// <param name="cluster"></param>
        /// <param name="applicationInstanceName"></param>
        /// <param name="applicationTypeName"></param>
        /// <param name="applicationTypeVersion"></param>
        /// <returns></returns>
        public async Task CreateApplicationAsync(string cluster, string applicationInstanceName, string applicationTypeName, string applicationTypeVersion, CancellationToken token)
        {
            FabricClient fabricClient = this.GetClient(cluster);
            FabricClient.ApplicationManagementClient applicationClient = fabricClient.ApplicationManager;

            Uri appName = new Uri("fabric:/" + applicationInstanceName);

            if ( await ApplicationExistsAsync(cluster, applicationInstanceName, token))
            {
                return;
            }
 
            ApplicationDescription appDescription = new ApplicationDescription(appName, applicationTypeName, applicationTypeVersion);

            await applicationClient.CreateApplicationAsync(appDescription, this.writeOperationTimeout, token);
        }
        public Session(
            OperationContext        context,
            IServerInternal         server,
            X509Certificate2        serverCertificate,
            NodeId                  authenticationToken,
            byte[]                  serverNonce,
            string                  sessionName, 
            ApplicationDescription  clientDescription,    
            string                  endpointUrl,      
            X509Certificate2        clientCertificate,  
            double                  sessionTimeout,
            uint                    maxResponseMessageSize,
            double                  maxRequestAge,
            int                     maxBrowseContinuationPoints,
            int                     maxHistoryContinuationPoints)
        {
            if (context == null) throw new ArgumentNullException("context");
            if (server == null)  throw new ArgumentNullException("server");
            
            // verify that a secure channel was specified.
            if (context.ChannelContext == null)
            {
                throw new ServiceResultException(StatusCodes.BadSecureChannelIdInvalid);
            }

            m_server                       = server;
            m_authenticationToken          = authenticationToken;
            m_serverNonce                  = serverNonce;
            m_sessionName                  = sessionName;
            m_serverCertificate            = serverCertificate;
            m_clientCertificate            = clientCertificate;
            m_secureChannelId              = context.ChannelContext.SecureChannelId;
            m_maxResponseMessageSize       = maxResponseMessageSize;
            m_maxRequestAge                = maxRequestAge;
            m_maxBrowseContinuationPoints  = maxBrowseContinuationPoints;
            m_maxHistoryContinuationPoints = maxHistoryContinuationPoints;
            m_endpoint                     = context.ChannelContext.EndpointDescription;
            
            // use anonymous the default identity.
            m_identity = new UserIdentity();
            
            // initialize diagnostics.
            m_diagnostics = new SessionDiagnosticsDataType();

            m_diagnostics.SessionId = null;
            m_diagnostics.SessionName = sessionName;
            m_diagnostics.ClientDescription = clientDescription;
            m_diagnostics.ServerUri = null;
            m_diagnostics.EndpointUrl = endpointUrl;
            m_diagnostics.LocaleIds = new StringCollection();
            m_diagnostics.ActualSessionTimeout = sessionTimeout;
            m_diagnostics.ClientConnectionTime = DateTime.UtcNow;
            m_diagnostics.ClientLastContactTime = DateTime.UtcNow;
            m_diagnostics.CurrentSubscriptionsCount = 0;
            m_diagnostics.CurrentMonitoredItemsCount = 0;
            m_diagnostics.CurrentPublishRequestsInQueue = 0;
            m_diagnostics.TotalRequestCount = new ServiceCounterDataType();
            m_diagnostics.UnauthorizedRequestCount = 0;
            m_diagnostics.ReadCount = new ServiceCounterDataType();
            m_diagnostics.HistoryReadCount = new ServiceCounterDataType();
            m_diagnostics.WriteCount = new ServiceCounterDataType();
            m_diagnostics.HistoryUpdateCount = new ServiceCounterDataType();
            m_diagnostics.CallCount = new ServiceCounterDataType();
            m_diagnostics.CreateMonitoredItemsCount = new ServiceCounterDataType();
            m_diagnostics.ModifyMonitoredItemsCount = new ServiceCounterDataType();
            m_diagnostics.SetMonitoringModeCount = new ServiceCounterDataType();
            m_diagnostics.SetTriggeringCount = new ServiceCounterDataType();
            m_diagnostics.DeleteMonitoredItemsCount = new ServiceCounterDataType();
            m_diagnostics.CreateSubscriptionCount= new ServiceCounterDataType();
            m_diagnostics.ModifySubscriptionCount = new ServiceCounterDataType();
            m_diagnostics.SetPublishingModeCount = new ServiceCounterDataType();
            m_diagnostics.PublishCount = new ServiceCounterDataType();
            m_diagnostics.RepublishCount = new ServiceCounterDataType();
            m_diagnostics.TransferSubscriptionsCount = new ServiceCounterDataType();
            m_diagnostics.DeleteSubscriptionsCount = new ServiceCounterDataType();
            m_diagnostics.AddNodesCount = new ServiceCounterDataType();
            m_diagnostics.AddReferencesCount = new ServiceCounterDataType();
            m_diagnostics.DeleteNodesCount = new ServiceCounterDataType();
            m_diagnostics.DeleteReferencesCount = new ServiceCounterDataType();
            m_diagnostics.BrowseCount = new ServiceCounterDataType();
            m_diagnostics.BrowseNextCount = new ServiceCounterDataType();
            m_diagnostics.TranslateBrowsePathsToNodeIdsCount = new ServiceCounterDataType();
            m_diagnostics.QueryFirstCount = new ServiceCounterDataType();
            m_diagnostics.QueryNextCount = new ServiceCounterDataType();
            m_diagnostics.RegisterNodesCount = new ServiceCounterDataType();
            m_diagnostics.UnregisterNodesCount = new ServiceCounterDataType();
            
            // initialize security diagnostics.
            m_securityDiagnostics = new SessionSecurityDiagnosticsDataType();
            
            m_securityDiagnostics.SessionId                = m_sessionId;
            m_securityDiagnostics.ClientUserIdOfSession    = m_identity.DisplayName;
            m_securityDiagnostics.AuthenticationMechanism  = m_identity.TokenType.ToString();
            m_securityDiagnostics.Encoding                 = context.ChannelContext.MessageEncoding.ToString();
            
            m_securityDiagnostics.ClientUserIdHistory = new StringCollection();
            m_securityDiagnostics.ClientUserIdHistory.Add(m_identity.DisplayName);

            EndpointDescription description = context.ChannelContext.EndpointDescription;
            
            if (description != null)
            {
                m_securityDiagnostics.TransportProtocol = new Uri(description.EndpointUrl).Scheme;
                m_securityDiagnostics.SecurityMode      = m_endpoint.SecurityMode;
                m_securityDiagnostics.SecurityPolicyUri = m_endpoint.SecurityPolicyUri;
            }

            if (clientCertificate != null)
            {
                m_securityDiagnostics.ClientCertificate = clientCertificate.RawData;
            }

            ServerSystemContext systemContext = m_server.DefaultSystemContext.Copy(context);

            // create diagnostics object.
            m_sessionId = server.DiagnosticsNodeManager.CreateSessionDiagnostics(
                systemContext,
                m_diagnostics,
                OnUpdateDiagnostics,
                m_securityDiagnostics,
                OnUpdateSecurityDiagnostics);

            // report the audit event.
            ReportAuditCreateSessionEvent(systemContext);

            TraceState("CREATED");
        }
        /// <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);
            }
        }
Exemple #40
0
        /// <summary>
        /// Create a new service host for protocols that support only one policy per host.
        /// </summary>
        /// <param name="hosts">The hosts.</param>
        /// <param name="configuration">The configuration.</param>
        /// <param name="bindingFactory">The binding factory.</param>
        /// <param name="baseAddresses">The base addresses.</param>
        /// <param name="serverDescription">The server description.</param>
        /// <param name="securityMode">The security mode.</param>
        /// <param name="securityPolicyUri">The security policy URI.</param>
        /// <param name="basePath">The base path to use when constructing the hosts.</param>
        /// <returns>Returns list of descriptions for the EndpointDescription DataType, return type is list of <seealso cref="EndpointDescription"/>.</returns>
        protected List<EndpointDescription> CreateSinglePolicyServiceHost(
            IDictionary<string, ServiceHost> hosts,
            ApplicationConfiguration configuration,
            BindingFactory bindingFactory,
            IList<string> baseAddresses,
            ApplicationDescription serverDescription,
            MessageSecurityMode securityMode,
            string securityPolicyUri,
            string basePath)
        {
            // generate a unique host name.
            string hostName = basePath;

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

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

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

            // build list of uris.
            List<Uri> uris = new List<Uri>();
            List<EndpointDescription> endpoints = new List<EndpointDescription>();
            string computerName = System.Net.Dns.GetHostName();

            for (int ii = 0; ii < baseAddresses.Count; ii++)
            {
                // UA TCP and HTTPS endpoints have their own host.
                if (baseAddresses[ii].StartsWith(Utils.UriSchemeOpcTcp, StringComparison.Ordinal) ||
                    baseAddresses[ii].StartsWith(Utils.UriSchemeHttps, StringComparison.Ordinal)  ||
                    baseAddresses[ii].StartsWith(Utils.UriSchemeNoSecurityHttp, StringComparison.Ordinal))
                {
                    continue;
                }

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

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

                uri.Path += hostName;
                uris.Add(uri.Uri);

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

                description.EndpointUrl = uri.ToString();
                description.Server = serverDescription;
                
                description.SecurityMode = securityMode;
                description.SecurityPolicyUri = securityPolicyUri;
                description.TransportProfileUri = Profiles.WsHttpXmlTransport; 
                description.UserIdentityTokens = GetUserTokenPolicies(configuration, description);

                bool requireEncryption = RequireEncryption(description);

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

                if (requireEncryption)
                {
                    if (InstanceCertificate == null)
                    {
                        throw new ServiceResultException( StatusCodes.BadConfigurationError,
                            "Server does not have an instance certificate assigned." );
                    }

                    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);
            }

            // check if nothing to do.
            if (uris.Count == 0)
            {
                return endpoints;
            }

            // create the host.
            ServiceHost serviceHost = CreateServiceHost(this, uris.ToArray());

            // create the endpoint configuration to use.
            EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(configuration);

            // initialize the host.
            serviceHost.InitializeSinglePolicy(
                GetServiceContract(),
                configuration,
                bindingFactory,
                endpointConfiguration,
                endpoints,
                securityMode,
                securityPolicyUri);

            if (String.IsNullOrEmpty(hostName))
            {
                serviceHost.InitializeDiscovery(configuration, serverDescription.DiscoveryUrls);
            }

            // save in server list.
            hosts[hostName] = serviceHost;

            return endpoints;
        }
 private void HostNameCTRL_HostConnected(object sender, SelectHostCtrlEventArgs e)
 {
     try
     {
         m_hostname = e.Hostname;
         ServersCTRL.Initialize(m_hostname, m_configuration);
         m_server = null;
         OkBTN.Enabled = false;
     }
     catch (Exception exception)
     {
         GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
     }
 }
Exemple #42
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>
        /// Reads the application description from the GDS.
        /// </summary>
        private ApplicationDescription Read(NodeId nodeId)
        {
            NamespaceTable wellKnownNamespaceUris = new NamespaceTable();
            wellKnownNamespaceUris.Append(Namespaces.OpcUaGds);

            string[] browsePaths = new string[] 
            {
                "1:ApplicationName",
                "1:ApplicationType",
                "1:ApplicationUri",
                "1:ProductUri",
                "1:GatewayServerUri",
                "1:DiscoveryUrls"
            };

            List<NodeId> propertyIds = ClientUtils.TranslateBrowsePaths(
                ServerCTRL.Session,
                nodeId,
                wellKnownNamespaceUris,
                browsePaths);

            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            foreach (NodeId propertyId in propertyIds)
            {
                ReadValueId nodeToRead = new ReadValueId();
                nodeToRead.NodeId = propertyId;
                nodeToRead.AttributeId = Attributes.Value;
                nodesToRead.Add(nodeToRead);
            }

            DataValueCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            ServerCTRL.Session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out results,
                out diagnosticInfos);

            ClientBase.ValidateResponse(results, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            ApplicationDescription application = new ApplicationDescription();

            application.ApplicationName = results[0].GetValue<LocalizedText>(null);
            application.ApplicationType = (ApplicationType)results[1].GetValue<int>((int)ApplicationType.Server);
            application.ApplicationUri = results[2].GetValue<string>(null);
            application.ProductUri = results[3].GetValue<string>(null);
            application.GatewayServerUri = results[4].GetValue<string>(null);

            string[] discoveryUrls = results[5].GetValue<string[]>(null);

            if (discoveryUrls != null)
            {
                application.DiscoveryUrls = new StringCollection(discoveryUrls);
            }

            return application;
        }
    /// <summary>
    /// We are ready to create a session.  Ensure the data is valid
    /// then create the session
    /// </summary>
    private void btnOK_Click(object sender, System.EventArgs e)
    {
        ApplicationDescription dpApp;
        if ((txtSession.Text == null) || (txtSession.Text == "")) {
            MessageBox.Show(this,"Please enter a session name before clicking OK.","No sessionname",MessageBoxButtons.OK,MessageBoxIcon.Information);
            return;
        }

        Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\DirectX\\SDK\\csDPlay");
        if (regKey != null) {
            regKey.SetValue("DirectPlaySessionName", txtSession.Text);
            if (migrateHostCheckBox.Checked)
                regKey.SetValue("DirectPlayMigrateHost",1);
            else
                regKey.SetValue("DirectPlayMigrateHost",0);

            if (fastSignedRadio.Checked)
                regKey.SetValue("DirectPlaySessionSigning","Fast");
            else if (fullSignedRadio.Checked)
                regKey.SetValue("DirectPlaySessionSigning","Full");
            else
                regKey.SetValue("DirectPlaySessionSigning","Disabled");
            regKey.Close();
        }

        dpApp = new ApplicationDescription();
        dpApp.GuidApplication = connectionWizard.ApplicationGuid;
        dpApp.SessionName = txtSession.Text;
        dpApp.Flags = 0;

        if (migrateHostCheckBox.Checked)
            dpApp.Flags |= SessionFlags.MigrateHost;

        if (!useDPNSVRCheckBox.Checked)
            dpApp.Flags |= SessionFlags.NoDpnServer;

        if (fastSignedRadio.Checked)
            dpApp.Flags |= SessionFlags.FastSigned;
        else if (fullSignedRadio.Checked)
            dpApp.Flags |= SessionFlags.FullSigned;

        // Specify the port number if available
        if (ConnectWizard.ProviderRequiresPort(deviceAddress.ServiceProvider)) {
            if (Port > 0)
                deviceAddress.AddComponent(Address.KeyPort, Port);
        }

        connectionWizard.SetUserInfo();
        // Host a game on deviceAddress as described by dpApp
        // HostFlags.OkToQueryForAddressing allows DirectPlay to prompt the user
        // using a dialog box for any device address information that is missing
        peer.Host(dpApp,deviceAddress,HostFlags.OkToQueryForAddressing);
        this.DialogResult = DialogResult.OK;
    }
        private void BrowseCTRL_AfterSelect(object sender, EventArgs e)
        {
            try
            {         
                if (ServerCTRL.Session == null)
                {
                    return;
                }

                ushort namespaceIndex = (ushort)ServerCTRL.Session.NamespaceUris.GetIndex(Opc.Ua.Namespaces.OpcUaGds);
                NodeId typeId = new NodeId(GdsId_ApplicationElementType, namespaceIndex);

                ReferenceDescription reference = BrowseCTRL.SelectedNode;

                if (reference != null)
                {
                    if (reference.TypeDefinition == typeId)
                    {
                        m_application = Read((NodeId)reference.NodeId);
                        OkBTN.Enabled = m_application.ApplicationType == ApplicationType.Server || m_application.ApplicationType == ApplicationType.ClientAndServer;
                        return;
                    }
                }

                m_application = null;
                OkBTN.Enabled = false;
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(this.Text, exception);
            }
        }
        private void ServersCTRL_ItemsPicked(object sender, ListItemActionEventArgs e)
        {
            try
            {
                m_server = null;

                foreach (ApplicationDescription server in e.Items)
                {
                    m_server = server;
                    break;
                }
            }
            catch (Exception exception)
            {
                GuiUtils.HandleException(String.Empty, GuiUtils.CallerName(), exception);
            }
        }
    /// <summary>
    /// We either want to start or stop searching
    /// </summary>
    private void btnSearch_Click(object sender, System.EventArgs e)
    {
        if (!isSearching)
        {
            if( hostAddress != null )
                hostAddress.Dispose();

            hostAddress = new Address();
            hostAddress.ServiceProvider = deviceAddress.ServiceProvider;

            // See if we should prompt the user for the remote address
            if (ConnectWizard.ProviderRequiresPort(hostAddress.ServiceProvider))
            {
                AddressForm addressDialog = new AddressForm(connectionWizard.DefaultPort);
                addressDialog.ShowDialog(this);

                // If the user cancelled the address form, abort the search
                if (addressDialog.DialogResult != DialogResult.OK)
                    return;

                // If a port was specified, add the component
                if (addressDialog.Hostname != "")
                    hostAddress.AddComponent(Address.KeyHostname, addressDialog.Hostname);

                // If a hostname was specified, add the component
                if (addressDialog.Port > 0)
                    hostAddress.AddComponent(Address.KeyPort, addressDialog.Port);
            }

            //Time to enum our hosts
            ApplicationDescription desc = new ApplicationDescription();
            desc.GuidApplication = connectionWizard.ApplicationGuid;

            // If the user was not already asked for address information, DirectPlay
            // should prompt with native UI
            FindHostsFlags flags = 0;
            if (!ConnectWizard.ProviderRequiresPort(deviceAddress.ServiceProvider))
                flags = FindHostsFlags.OkToQueryForAddressing;

            peer.FindHosts(desc,hostAddress,deviceAddress,null,Timeout.Infinite,0,Timeout.Infinite, flags, out findHostHandle);
            isSearching = true;
            btnCreate.Enabled = false;
            btnSearch.Text = "Stop Search";
        }
        else
        {
            btnSearch.Text = "Stopping...";
            btnSearch.Enabled = false;
            if (findHostHandle != 0)
                peer.CancelAsyncOperation(findHostHandle);
        }
    }
        private void ServersCTRL_ItemsSelected(object sender, ListItemActionEventArgs e)
        {
            try
            {
                m_server = null;

                foreach (ApplicationDescription server in e.Items)
                {
                    m_server = server;
                    break;
                }

                OkBTN.Enabled = m_server != null;
            }
            catch (Exception exception)
            {
                GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
            }
        }
        /// <summary>
        /// Creates a new session.
        /// </summary>
        public virtual Session CreateSession(
            OperationContext       context,
            X509Certificate2       serverCertificate,
            string                 sessionName, 
            byte[]                 clientNonce,
            ApplicationDescription clientDescription,
            string                 endpointUrl,
            X509Certificate2       clientCertificate,
            double                 requestedSessionTimeout, 
            uint                   maxResponseMessageSize,
            out NodeId             sessionId, 
            out NodeId             authenticationToken, 
            out byte[]             serverNonce,
            out double             revisedSessionTimeout)
        {
            sessionId = 0;
            revisedSessionTimeout = requestedSessionTimeout;
                 
            Session session = null;
            IBuffer buffer = null;

            lock (m_lock)
            {
                // check session count.
                if (m_maxSessionCount > 0 && m_sessions.Count >= m_maxSessionCount)
                {
                    throw new ServiceResultException(StatusCodes.BadTooManySessions);
                }

                // can assign a simple identifier if secured.
                authenticationToken = null;

                if (!String.IsNullOrEmpty(context.ChannelContext.SecureChannelId))
                {
                    if (context.ChannelContext.EndpointDescription.SecurityMode != MessageSecurityMode.None)
                    {
                        authenticationToken = Utils.IncrementIdentifier(ref m_lastSessionId);
                    }
                }

                // must assign a hard-to-guess id if not secured.
                if (authenticationToken == null)
                {
                    byte[] token = new byte[32];
                    buffer = CryptographicBuffer.GenerateRandom(32);
                    CryptographicBuffer.CopyToByteArray(buffer, out token);
                    authenticationToken = new NodeId(token);
                }
                
                // determine session timeout.
                if (requestedSessionTimeout > m_maxSessionTimeout)
                {
                    revisedSessionTimeout = m_maxSessionTimeout;
                }
                
                if (requestedSessionTimeout < m_minSessionTimeout)
                {
                    revisedSessionTimeout = m_minSessionTimeout;
                }
                
                // create server nonce.
                serverNonce = new byte[m_minNonceLength];
                buffer = CryptographicBuffer.GenerateRandom((uint) m_minNonceLength);
                CryptographicBuffer.CopyToByteArray(buffer, out serverNonce);
                
                // assign client name.
                if (String.IsNullOrEmpty(sessionName))
                {
                    sessionName = Utils.Format("Session {0}", sessionId);
                }

                // create instance of session.
                session = CreateSession(
                    context,
                    m_server,
                    serverCertificate,
                    authenticationToken,
                    serverNonce,
                    sessionName,
                    clientDescription,
                    endpointUrl,
                    clientCertificate,
                    revisedSessionTimeout,
                    maxResponseMessageSize,
                    m_maxRequestAge,
                    m_maxBrowseContinuationPoints);

                // get the session id.
                sessionId = session.Id;
                
                // save session.
                m_sessions.Add(authenticationToken, session);
            }

            // raise session related event.
            RaiseSessionEvent(session, SessionEventReason.Created);       
                    
            // return session.
            return session;
        }
 private void HostNameCTRL_HostSelected(object sender, SelectHostCtrlEventArgs e)
 {
     try
     {
         if (m_hostname != e.Hostname)
         {
             m_hostname = e.Hostname;
             ServersCTRL.Initialize(m_hostname, m_configuration);
             m_server = null;
             OkBTN.IsEnabled = false;
         }
     }
     catch (Exception exception)
     {
         GuiUtils.HandleException(String.Empty, GuiUtils.CallerName(), exception);
     }
 }
Exemple #51
0
        /// <summary>
        /// Translates the discovery URLs based on the client url and returns an updated ApplicationDescription.
        /// </summary>
        /// <param name="clientUrl">The client URL.</param>
        /// <param name="description">The application description.</param>
        /// <param name="baseAddresses">The base addresses.</param>
        /// <param name="applicationName">The localized application name.</param>
        /// <returns>A copy of the application description</returns>
        protected ApplicationDescription TranslateApplicationDescription(
            Uri clientUrl,
            ApplicationDescription description,
            IList<BaseAddress> baseAddresses,
            LocalizedText applicationName)
        {
            // get the discovery urls.
            StringCollection discoveryUrls = new StringCollection();

            foreach (BaseAddress baseAddress in baseAddresses)
            {
                discoveryUrls.Add(GetBestDiscoveryUrl(clientUrl, baseAddress));
            }

            // copy the description.
            ApplicationDescription copy = new ApplicationDescription();

            copy.ApplicationName = description.ApplicationName;
            copy.ApplicationUri = description.ApplicationUri;
            copy.ApplicationType = description.ApplicationType;
            copy.ProductUri = description.ProductUri;
            copy.GatewayServerUri = description.DiscoveryProfileUri;
            copy.DiscoveryUrls = discoveryUrls;

            if (!LocalizedText.IsNullOrEmpty(applicationName))
            {
                copy.ApplicationName = applicationName;
            }

            // return the copy.
            return copy;
        }
Exemple #52
0
        /// <summary>
        /// try to create application
        /// </summary>
        /// <returns>true if successful</returns>
        public bool TryApplicationCreate()
        {
            this.LastException = null;

            if (!this.IsClusterRunning)
            {
                return false;
            }

            if (this.control.Package.ApplicationAddress == null)
            {
                log.Error("ApplicationAddress is null");
                return false;
            }

            if (this.control.Package.ApplicationTypeName == null)
            {
                log.Error("ApplicationTypeName is null");
                return false;
            }

            if (this.control.Package.ApplicationVersion == null)
            {
                log.Error("ApplicationVersion is null");
                return false;
            }

            NameValueCollection nvc = GetApplicationParameters(this.control.Package);
            ApplicationDescription d = new ApplicationDescription(new Uri(this.control.Package.ApplicationAddress), this.control.Package.ApplicationTypeName, this.control.Package.ApplicationVersion, nvc);

            int retryLimit = Defaults.WaitRetryLimit;
            while (retryLimit-- > 0)
            {
                try
                {
                    this.fc.ApplicationManager
                      .CreateApplicationAsync(d, Defaults.WaitDelay, CancellationToken.None)
                      .Wait();

                    log.Info("Application create successful");
                    return true;
                }
                catch (AggregateException ae)
                {
                    this.LastException = ae;

                    if (!this.IsRetry("CreateApplication", ae.InnerException))
                    {
                        return false;
                    }
                }
                catch (Exception e)
                {
                    this.LastException = e;

                    if (!this.IsRetry("CreateApplication", e))
                    {
                        return false;
                    }
                }

                log.Info("Application create failed, retrying...");
                Task.Delay(Defaults.WaitDelay).Wait();
            }

            log.Error("CreateApplication failed too many times");
            return false;
        }