Exemple #1
0
        public static EndpointDescription CreateEndpointDescription(UAServer myServer)
        {
            // create the endpoint description.
            EndpointDescription endpointDescription = null;

            try
            {
                string discoveryUrl = myServer.ServerName;
                //OA 2018-04-27
                if (!discoveryUrl.StartsWith(Utils.UriSchemeOpcTcp) && !discoveryUrl.StartsWith(Utils.UriSchemeHttps))
                //if (!discoveryUrl.StartsWith(Utils.UriSchemeOpcTcp))
                {
                    if (!discoveryUrl.EndsWith("/discovery"))
                    {
                        discoveryUrl += "/discovery";
                    }
                }

                // parse the selected URL.
                Uri uri = new Uri(discoveryUrl);

                // set a short timeout because this is happening in the drop down event.
                EndpointConfiguration configuration = EndpointConfiguration.Create();
                configuration.OperationTimeout = 5000;

                //OA 2018-04-27 https
                if (discoveryUrl.StartsWith(Utils.UriSchemeHttps))
                {
                    configuration.OperationTimeout = 0;
                }
                //

                // Connect to the server's discovery endpoint and find the available configuration.
                using (DiscoveryClient client = DiscoveryClient.Create(uri, configuration))
                {
                    EndpointDescriptionCollection endpoints = client.GetEndpoints(null);

                    // select the best endpoint to use based on the selected URL and the UseSecurity checkbox.
                    for (int ii = 0; ii < endpoints.Count; ii++)
                    {
                        EndpointDescription endpoint = endpoints[ii];

                        // check for a match on the URL scheme.
                        if (endpoint.EndpointUrl.StartsWith(uri.Scheme))
                        {
                            // check if security was requested.
                            if (!myServer.SecurityPolicy.Equals("None"))
                            {
                                if (endpoint.SecurityMode == MessageSecurityMode.None)
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                if (endpoint.SecurityMode != MessageSecurityMode.None)
                                {
                                    continue;
                                }
                            }

                            // pick the first available endpoint by default.
                            if (endpointDescription == null)
                            {
                                endpointDescription = endpoint;
                            }

                            // The security level is a relative measure assigned by the server to the
                            // endpoints that it returns. Clients should always pick the highest level
                            // unless they have a reason not too.
                            if (endpoint.SecurityLevel > endpointDescription.SecurityLevel)
                            {
                                endpointDescription = endpoint;
                            }
                        }
                    }

                    // pick the first available endpoint by default.
                    if (endpointDescription == null && endpoints.Count > 0)
                    {
                        endpointDescription = endpoints[0];
                    }
                }

                // if a server is behind a firewall it may return URLs that are not accessible to the client.
                // This problem can be avoided by assuming that the domain in the URL used to call
                // GetEndpoints can be used to access any of the endpoints. This code makes that conversion.
                // Note that the conversion only makes sense if discovery uses the same protocol as the endpoint.

                Uri endpointUrl = Utils.ParseUri(endpointDescription.EndpointUrl);



                if (endpointUrl != null && endpointUrl.Scheme == uri.Scheme)
                {
                    UriBuilder builder = new UriBuilder(endpointUrl);
                    builder.Host = uri.DnsSafeHost;
                    builder.Port = uri.Port;
                    endpointDescription.EndpointUrl = builder.ToString();
                }
            }
            catch
            {
                endpointDescription             = new EndpointDescription();
                endpointDescription.EndpointUrl = myServer.ServerName;

                //ABA 2014-10-10
                if (myServer.SecurityPolicy.Equals("None"))
                {
                    endpointDescription.SecurityPolicyUri = SecurityPolicies.None;
                }
                //Commented by MM 03/07/2019
                //else if (myServer.SecurityPolicy.Equals("Basic128Rsa15"))
                //{
                //    endpointDescription.SecurityPolicyUri = SecurityPolicies.Basic128Rsa15;
                //}
                else if (myServer.SecurityPolicy.Equals("Basic256Sha256"))
                {
                    endpointDescription.SecurityPolicyUri = SecurityPolicies.Basic256Sha256;
                }
                else if (myServer.SecurityPolicy.Equals("Basic256"))
                {
                    endpointDescription.SecurityPolicyUri = SecurityPolicies.Basic256;
                }

                try
                {
                    MessageSecurityMode myMode;
                    myMode = (MessageSecurityMode)Enum.Parse(typeof(MessageSecurityMode), myServer.SecurityMode, false);
                    //endpointDescription.SecurityMode      = MessageSecurityMode.SignAndEncrypt;
                    endpointDescription.SecurityMode = myMode;
                }
                catch
                {
                    endpointDescription.SecurityMode = MessageSecurityMode.None;
                }

                // specify the transport profile.
                if (myServer.Protocol.Equals("opc.tcp"))
                {
                    endpointDescription.TransportProfileUri = Profiles.UaTcpTransport;
                }
                //added OA 2018-04-27
                else if (myServer.Protocol.Equals("http"))
                {
                    //OA-2018-06-18  endpointDescription.TransportProfileUri = Profiles.WsHttpXmlOrBinaryTransport;
                }
                else //added OA 2018-04-27
                {
                    endpointDescription.TransportProfileUri = Profiles.HttpsBinaryTransport; //OA-2018-06-18 HttpsXmlOrBinaryTransport;
                }
                //else  //OA 2018-04-27
                //{
                //    endpointDescription.TransportProfileUri = Profiles.WsHttpXmlOrBinaryTransport;
                //}

                if (myServer.UserIdentity.Equals(UserIdentityType.Certificate))
                {
                    // load the the server certificate from the local certificate store.
                    CertificateIdentifier certificateIdentifier = new CertificateIdentifier();

                    certificateIdentifier.StoreType = CertificateStoreType.X509Store; //OA-2018-06-18 .Windows;

                    if (!String.IsNullOrEmpty(myServer.CertificationStore))
                    {
                        //certificateIdentifier.StorePath = "LocalMachine\\UA Applications";
                        certificateIdentifier.StorePath = myServer.CertificationStore;
                    }
                    else
                    {
                        using (System.IO.FileStream fs = System.IO.File.OpenRead(myServer.CertificationPath))
                        {
                            byte[] bytes = new byte[fs.Length];
                            fs.Read(bytes, 0, Convert.ToInt32(fs.Length));

                            certificateIdentifier.RawData = bytes;
                        }
                    }

                    //certificateIdentifier.SubjectName = "ONBServer";//commented by HHA 12/11//2019

                    //OA-2018-06-25
                    //X509Certificate2 serverCertificate =  certificateIdentifier.Find();
                    X509Certificate2 serverCertificate = certificateIdentifier.Find().Result;

                    if (serverCertificate == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadCertificateInvalid, "Could not find server certificate: {0}", certificateIdentifier.SubjectName);
                    }

                    endpointDescription.ServerCertificate = serverCertificate.GetRawCertData();
                }
            }

            return(endpointDescription);
        }
Exemple #2
0
        public static async Task <int> Main(string[] args)
        {
            TextWriter output = Console.Out;

            output.WriteLine("{0} OPC UA Reference Server", Utils.IsRunningOnMono() ? "Mono" : ".NET Core");

            // The application name and config file names
            var applicationName   = Utils.IsRunningOnMono() ? "MonoReferenceServer" : "ConsoleReferenceServer";
            var configSectionName = Utils.IsRunningOnMono() ? "Quickstarts.MonoReferenceServer" : "Quickstarts.ReferenceServer";

            // command line options
            bool   showHelp         = false;
            bool   autoAccept       = false;
            bool   logConsole       = false;
            bool   appLog           = false;
            bool   renewCertificate = false;
            string password         = null;
            int    timeout          = -1;

            var usage = Utils.IsRunningOnMono() ? $"Usage: mono {applicationName}.exe [OPTIONS]" : $"Usage: dotnet {applicationName}.dll [OPTIONS]";

            Mono.Options.OptionSet options = new Mono.Options.OptionSet {
                usage,
                { "h|help", "show this message and exit", h => showHelp = h != null },
                { "a|autoaccept", "auto accept certificates (for testing only)", a => autoAccept = a != null },
                { "c|console", "log to console", c => logConsole = c != null },
                { "l|log", "log app output", c => appLog = c != null },
                { "p|password="******"optional password for private key", (string p) => password = p },
                { "r|renew", "renew application certificate", r => renewCertificate = r != null },
                { "t|timeout=", "timeout in seconds to exit application", (int t) => timeout = t * 1000 },
            };

            try
            {
                // parse command line and set options
                ConsoleUtils.ProcessCommandLine(output, args, options, ref showHelp);

                if (logConsole && appLog)
                {
                    output = new LogWriter();
                }

                // create the UA server
                var server = new UAServer <ReferenceServer>(output)
                {
                    AutoAccept = autoAccept,
                    Password   = password
                };

                // load the server configuration, validate certificates
                output.WriteLine("Loading configuration from {0}.", configSectionName);
                await server.LoadAsync(applicationName, configSectionName).ConfigureAwait(false);

                // setup the logging
                ConsoleUtils.ConfigureLogging(server.Configuration, applicationName, logConsole, LogLevel.Information);

                // check or renew the certificate
                output.WriteLine("Check the certificate.");
                await server.CheckCertificateAsync(renewCertificate).ConfigureAwait(false);

                // start the server
                output.WriteLine("Start the server.");
                await server.StartAsync().ConfigureAwait(false);

                output.WriteLine("Server started. Press Ctrl-C to exit...");

                // wait for timeout or Ctrl-C
                var  quitEvent = ConsoleUtils.CtrlCHandler();
                bool ctrlc     = quitEvent.WaitOne(timeout);

                // stop server. May have to wait for clients to disconnect.
                output.WriteLine("Server stopped. Waiting for exit...");
                await server.StopAsync().ConfigureAwait(false);

                return((int)ExitCode.Ok);
            }
            catch (ErrorExitException eee)
            {
                output.WriteLine("The application exits with error: {0}", eee.Message);
                return((int)eee.ExitCode);
            }
        }
Exemple #3
0
        static void Main()
        {
            string m_cmmdLine = Environment.CommandLine;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (m_cmmdLine.ToLower().Contains(str_debug_install_argument))
            {
                CASApplicationInstance.InstallServer(Assembly.GetExecutingAssembly().Location);
            }
            if (m_cmmdLine.ToLower().Contains(str_debug_uninstall_argument))
            {
                CASApplicationInstance.UnInstallServer(Assembly.GetExecutingAssembly().Location);
            }
            CASApplicationInstance  application = new CASApplicationInstance();
            ConfigurationEditorMain config      = new ConfigurationEditorMain();

            try
            {
                if (!Environment.UserInteractive)
                {
                    Directory.SetCurrentDirectory(new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName);
                    if (application.ProcessCommandLine())
                    {
                        return;
                    }
                    application.StartAsService(new UAServer());
                    return;
                }
            }
            catch (Exception e)
            {
                Utils.Trace(e, "Unexpected error starting service.");
                return;
            }
#if DEBUG
            MessageBox.Show("Attach debug point");
#endif
            if (m_cmmdLine.ToLower().Contains(str_installic_argument))
            {
                try
                {
                    LibInstaller.InstallLicense(true);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("License installation has failed, reason: " + ex.Message);
                }
            }
            UAServer server = new UAServer();
            try
            {
                FileInfo configFI = RelativeFilePathsCalculator.GetAbsolutePathToFileInApplicationDataFolder(Settings.Default.ConfigurationFilePath);
                config.ReadConfiguration(configFI);
                if (config.Configuration == null)
                {
                    throw new ArgumentNullException("Cannot read configuration");
                }
                BaseDirectoryHelper.Instance.SetBaseDirectoryProvider(new BaseDirectoryProvider(configFI.DirectoryName));
                ApplicationCertificate.CheckApplicationInstanceCertificate(config.Configuration, 1024, (x, y) => true, true); //TODO add logging function or user interface.
                ApplicationCertificate.OverrideUaTcpImplementation(config.Configuration);
                server.Start(config.Configuration);
                Application.Run(new ServerForm(server, config.Configuration, application));
            }
            catch (Exception e)
            {
                HandleException("UA Server", e);
            }
            finally
            {
                server.Stop();
            }
        }
        public async Task <Session> CreateSession(OPCUAServer server, string sessionName)
        {
            try
            {
                lock (dicOfSession)
                {
                    if (dicOfSession.ContainsKey(sessionName))
                    {
                        return(dicOfSession[sessionName]);
                    }
                }


                #region OPCUAServer
                UAServer objUAServer = new UAServer();
                objUAServer.Protocol           = server.protocol;
                objUAServer.SecurityMode       = server.securityMode;
                objUAServer.SecurityPolicy     = server.securityMode;
                objUAServer.SecurityPolicy     = server.securityPolicy;
                objUAServer.UserIdentityString = server.UserIdentityString;
                objUAServer.ServerName         = server.serverName;
                try
                {
                    objUAServer.UserIdentity = (UserIdentityType)Enum.Parse(typeof(UserIdentityType), objUAServer.UserIdentityString);
                }
                catch
                {
                    if (objUAServer.UserIdentityString.Equals("Anonymous"))
                    {
                        objUAServer.UserIdentity = UserIdentityType.Anonymous;
                    }
                    else if (objUAServer.UserIdentityString.Equals("UserName"))
                    {
                        objUAServer.UserIdentity = UserIdentityType.UserName;
                    }
                    else
                    {
                        objUAServer.UserIdentity = UserIdentityType.Certificate;
                    }
                }

                if (objUAServer.UserIdentity.Equals(UserIdentityType.Certificate))
                {
                    objUAServer.IsSecurityStoreEnabled = false;
                    objUAServer.CertificationPath      = server.certificationPath;
                    objUAServer.CertificationPassword  = server.certificationPassword;
                }
                else if (objUAServer.UserIdentity.Equals(UserIdentityType.UserName))
                {
                    objUAServer.UserName     = server.userName;
                    objUAServer.UserPassword = server.userPassword;
                }
                #endregion

                await CheckAndLoadConfiguration();

                // Create the configuration.
                ApplicationConfiguration configuration = _appConfiguration; // Helpers.CreateClientConfiguration(myServer);

                // Create the endpoint description.
                EndpointDescription endpointDescription = Helpers.CreateEndpointDescription(objUAServer);

                // Create the endpoint configuration (use the application configuration to provide default values).
                EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(configuration);

                // The default timeout for a requests sent using the channel.
                endpointConfiguration.OperationTimeout = 300000;

                // Use the pure binary encoding on the wire.
                //OA-2018-04-11
                // endpointConfiguration.UseBinaryEncoding = true;
                if (objUAServer.MessageEncoding.ToLower().Equals("binary"))
                {
                    endpointConfiguration.UseBinaryEncoding = true;
                }
                else
                {
                    endpointConfiguration.UseBinaryEncoding = false;
                }

                IUserIdentity identity;


                var t = _appConfiguration.SecurityConfiguration.ApplicationCertificate.Find(true);
                X509Certificate2 clientCertificate = t.Result;

                UserTokenPolicy poly;


                if (objUAServer.UserIdentity.Equals(UserIdentityType.UserName))
                {
                    identity = new UserIdentity(objUAServer.UserName, objUAServer.UserPassword);
                    poly     = new UserTokenPolicy(UserTokenType.UserName);
                    //added by kais wali
                    bool exist = false;
                    foreach (UserTokenPolicy poltemp in endpointDescription.UserIdentityTokens)
                    {
                        if (poltemp.TokenType.ToString() == poly.TokenType.ToString())
                        {
                            exist = true;
                            break;
                        }
                    }
                    if (!exist)
                    {
                        endpointDescription.UserIdentityTokens.Add(poly);
                    }
                }
                else if (objUAServer.UserIdentity.Equals(UserIdentityType.Certificate))
                {
                    CertificateIdentifier certificateIdentifier = new CertificateIdentifier();
                    X509Certificate2      currentCertificate;
                    certificateIdentifier.StoreType = CertificateStoreType.Directory;
                    currentCertificate = new X509Certificate2(objUAServer.CertificationPath, objUAServer.CertificationPassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
                    if (currentCertificate == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadCertificateInvalid, "Could not find certificate: {0}", certificateIdentifier.SubjectName);
                    }
                    identity = new UserIdentity(currentCertificate);
                    //

                    poly = new UserTokenPolicy(UserTokenType.Certificate);
                    //added by kais wali
                    bool exist = false;
                    foreach (UserTokenPolicy poltemp in endpointDescription.UserIdentityTokens)
                    {
                        if (poltemp.TokenType.ToString() == poly.TokenType.ToString())
                        {
                            exist = true;
                            break;
                        }
                    }
                    if (!exist)
                    {
                        endpointDescription.UserIdentityTokens.Add(poly);
                    }
                }
                else
                {
                    identity = new UserIdentity();
                    poly     = new UserTokenPolicy(UserTokenType.Anonymous);
                    //added by kais wali
                    bool exist = false;
                    foreach (UserTokenPolicy poltemp in endpointDescription.UserIdentityTokens)
                    {
                        if (poltemp.TokenType.ToString() == poly.TokenType.ToString())
                        {
                            exist = true;
                            break;
                        }
                    }
                    if (!exist)
                    {
                        endpointDescription.UserIdentityTokens.Add(poly);
                    }
                }

                // Create the endpoint.
                ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration);

                // Update endpoint description using the discovery endpoint.
                // create message context.
                ServiceMessageContext messageContext = configuration.CreateMessageContext();

                //Set to true in default configuration (If the user have not configured an OPC UA Server in the ONBS)
                endpoint.UpdateBeforeConnect = false;
                // update endpoint description using the discovery endpoint.

                //OA-2018-06-19 Commented

                /*if (endpoint.UpdateBeforeConnect)
                 * {
                 *  BindingFactory bindingFactory = BindingFactory.Create(configuration, messageContext);
                 *  endpoint.UpdateFromServer(bindingFactory);
                 *
                 *  endpointDescription = endpoint.Description;
                 *  endpointConfiguration = endpoint.Configuration;
                 * }*/

                // Set up a callback to handle certificate validation errors.
                //  configuration.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation);


                // initialize the channel which will be created with the server.
                ITransportChannel channel = SessionChannel.Create(
                    configuration,
                    endpointDescription,
                    endpointConfiguration,
                    //clientCertificateChain,
                    clientCertificate,
                    messageContext);

                // create the session object.
                //OA-2017-08-15
                Session m_session = new Session(channel, configuration, endpoint, clientCertificate);
                //m_session = new Session(channel, configuration, endpoint, null);

                //OA-2017-09-20
                byte[] certificateData = endpoint.Description.ServerCertificate;
                //islem Commented serverCertificate
                if (certificateData != null) //OA-2018-04-27
                                             //serverCertificate = Utils.ParseCertificateBlob(certificateData);
                                             //

                {
                    m_session.ReturnDiagnostics = DiagnosticsMasks.All;
                }

                // Register keep alive callback.
                //islem Commented KeepAlive
                // m_session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive);

                // create the session.
                try
                {
                    m_session.Open(sessionName, 60000, identity, null);
                    dicOfSession.Add(sessionName, m_session);//OA-2017-09-20
                }
                catch (Exception e)
                {
                }

                return(m_session);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Exemple #5
0
        public static async Task <int> Main(string[] args)
        {
            TextWriter output = Console.Out;

            output.WriteLine("{0} OPC UA Reference Server", Utils.IsRunningOnMono() ? "Mono" : ".NET Core");

            output.WriteLine("OPC UA library: {0} @ {1} -- {2}",
                             Utils.GetAssemblyBuildNumber(),
                             Utils.GetAssemblyTimestamp().ToString("G", CultureInfo.InvariantCulture),
                             Utils.GetAssemblySoftwareVersion());

            // The application name and config file names
            var applicationName   = Utils.IsRunningOnMono() ? "MonoReferenceServer" : "ConsoleReferenceServer";
            var configSectionName = Utils.IsRunningOnMono() ? "Quickstarts.MonoReferenceServer" : "Quickstarts.ReferenceServer";

            // command line options
            bool   showHelp         = false;
            bool   autoAccept       = false;
            bool   logConsole       = false;
            bool   appLog           = false;
            bool   renewCertificate = false;
            bool   shadowConfig     = false;
            bool   cttMode          = false;
            string password         = null;
            int    timeout          = -1;

            var usage = Utils.IsRunningOnMono() ? $"Usage: mono {applicationName}.exe [OPTIONS]" : $"Usage: dotnet {applicationName}.dll [OPTIONS]";

            Mono.Options.OptionSet options = new Mono.Options.OptionSet {
                usage,
                { "h|help", "show this message and exit", h => showHelp = h != null },
                { "a|autoaccept", "auto accept certificates (for testing only)", a => autoAccept = a != null },
                { "c|console", "log to console", c => logConsole = c != null },
                { "l|log", "log app output", c => appLog = c != null },
                { "p|password="******"optional password for private key", (string p) => password = p },
                { "r|renew", "renew application certificate", r => renewCertificate = r != null },
                { "t|timeout=", "timeout in seconds to exit application", (int t) => timeout = t * 1000 },
                { "s|shadowconfig", "create configuration in pki root", s => shadowConfig = s != null },
                { "ctt", "CTT mode, use to preset alarms for CTT testing.", c => cttMode = c != null },
            };

            try
            {
                // parse command line and set options
                ConsoleUtils.ProcessCommandLine(output, args, options, ref showHelp);

                if (logConsole && appLog)
                {
                    output = new LogWriter();
                }

                // create the UA server
                var server = new UAServer <ReferenceServer>(output)
                {
                    AutoAccept = autoAccept,
                    Password   = password
                };

                // load the server configuration, validate certificates
                output.WriteLine("Loading configuration from {0}.", configSectionName);
                await server.LoadAsync(applicationName, configSectionName).ConfigureAwait(false);

                // use the shadow config to map the config to an externally accessible location
                if (shadowConfig)
                {
                    output.WriteLine("Using shadow configuration.");
                    var shadowPath = Directory.GetParent(Path.GetDirectoryName(
                                                             Utils.ReplaceSpecialFolderNames(server.Configuration.TraceConfiguration.OutputFilePath))).FullName;
                    var shadowFilePath = Path.Combine(shadowPath, Path.GetFileName(server.Configuration.SourceFilePath));
                    if (!File.Exists(shadowFilePath))
                    {
                        output.WriteLine("Create a copy of the config in the shadow location.");
                        File.Copy(server.Configuration.SourceFilePath, shadowFilePath, true);
                    }
                    output.WriteLine("Reloading configuration from {0}.", shadowFilePath);
                    await server.LoadAsync(applicationName, Path.Combine(shadowPath, configSectionName)).ConfigureAwait(false);
                }

                // setup the logging
                ConsoleUtils.ConfigureLogging(server.Configuration, applicationName, logConsole, LogLevel.Information);

                // check or renew the certificate
                output.WriteLine("Check the certificate.");
                await server.CheckCertificateAsync(renewCertificate).ConfigureAwait(false);

                // Create and add the node managers
                server.Create(Servers.Utils.NodeManagerFactories);

                // start the server
                output.WriteLine("Start the server.");
                await server.StartAsync().ConfigureAwait(false);

                // Apply custom settings for CTT testing
                if (cttMode)
                {
                    output.WriteLine("Apply settings for CTT.");
                    // start Alarms and other settings for CTT test
                    Quickstarts.Servers.Utils.ApplyCTTMode(output, server.Server);
                }

                output.WriteLine("Server started. Press Ctrl-C to exit...");

                // wait for timeout or Ctrl-C
                var  quitEvent = ConsoleUtils.CtrlCHandler();
                bool ctrlc     = quitEvent.WaitOne(timeout);

                // stop server. May have to wait for clients to disconnect.
                output.WriteLine("Server stopped. Waiting for exit...");
                await server.StopAsync().ConfigureAwait(false);

                return((int)ExitCode.Ok);
            }
            catch (ErrorExitException eee)
            {
                output.WriteLine("The application exits with error: {0}", eee.Message);
                return((int)eee.ExitCode);
            }
        }