private async Task <ApplicationConfiguration> Load(ApplicationInstance application, int basePort) { #if !USE_FILE_CONFIG // load the application configuration. ApplicationConfiguration config = await application.LoadApplicationConfiguration(true).ConfigureAwait(false); #else string root = Path.Combine("%LocalApplicationData%", "OPC"); string gdsRoot = Path.Combine(root, "GDS"); var gdsConfig = new GlobalDiscoveryServerConfiguration() { AuthoritiesStorePath = Path.Combine(gdsRoot, "authorities"), ApplicationCertificatesStorePath = Path.Combine(gdsRoot, "applications"), DefaultSubjectNameContext = "O=OPC Foundation", CertificateGroups = new CertificateGroupConfigurationCollection() { new CertificateGroupConfiguration() { Id = "Default", CertificateType = "RsaSha256ApplicationCertificateType", SubjectName = "CN=GDS Test CA, O=OPC Foundation", BaseStorePath = Path.Combine(gdsRoot, "CA", "default"), DefaultCertificateHashSize = 256, DefaultCertificateKeySize = 2048, DefaultCertificateLifetime = 12, CACertificateHashSize = 512, CACertificateKeySize = 4096, CACertificateLifetime = 60 } }, DatabaseStorePath = Path.Combine(gdsRoot, "gdsdb.json") }; // build the application configuration. ApplicationConfiguration config = await application .Build( "urn:localhost:opcfoundation.org:GlobalDiscoveryTestServer", "http://opcfoundation.org/UA/GlobalDiscoveryTestServer") .AsServer(new string[] { "opc.tcp://localhost:58810/GlobalDiscoveryTestServer" }) .AddUserTokenPolicy(UserTokenType.Anonymous) .AddUserTokenPolicy(UserTokenType.UserName) .SetDiagnosticsEnabled(true) .AddServerCapabilities("GDS") .AddServerProfile("http://opcfoundation.org/UA-Profile/Server/GlobalDiscoveryAndCertificateManagement2017") .SetShutdownDelay(0) .AddSecurityConfiguration( "CN=Global Discovery Test Server, O=OPC Foundation, DC=localhost", gdsRoot) .SetAutoAcceptUntrustedCertificates(true) .SetRejectSHA1SignedCertificates(false) .SetRejectUnknownRevocationStatus(true) .SetMinimumCertificateKeySize(1024) .AddExtension <GlobalDiscoveryServerConfiguration>(null, gdsConfig) .SetDeleteOnLoad(true) .SetOutputFilePath(Path.Combine(root, "Logs", "Opc.Ua.Gds.Tests.log.txt")) .SetTraceMasks(519) .Create().ConfigureAwait(false); #endif TestUtils.PatchBaseAddressesPorts(config, basePort); return(config); }
/// <summary> /// Load the default client configuration. /// </summary> public async Task LoadClientConfiguration(string clientName = "TestClient") { ApplicationInstance application = new ApplicationInstance { ApplicationName = clientName }; string pkiRoot = "%LocalApplicationData%/OPC/pki"; // build the application configuration. Config = await application .Build( "urn:localhost:opcfoundation.org:" + clientName, "http://opcfoundation.org/UA/" + clientName) .AsClient() .AddSecurityConfiguration( "CN=" + clientName + ", O=OPC Foundation, DC=localhost", pkiRoot) .SetAutoAcceptUntrustedCertificates(true) .SetRejectSHA1SignedCertificates(false) .SetMinimumCertificateKeySize(1024) .SetOutputFilePath(pkiRoot + "/Logs/Opc.Ua.Client.Tests.log.txt") .SetTraceMasks(TraceMasks) .Create().ConfigureAwait(false); // check the application certificate. bool haveAppCertificate = await application.CheckApplicationInstanceCertificate(true, 0).ConfigureAwait(false); if (!haveAppCertificate) { throw new Exception("Application instance certificate invalid!"); } ReverseConnectManager = new ReverseConnectManager(); }
public async Task TestNoFileConfigAsServerX509Store() { #if NETCOREAPP2_1_OR_GREATER // this test fails on macOS, ignore if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Assert.Ignore("X509Store trust lists not supported on mac OS."); } #endif var applicationInstance = new ApplicationInstance() { ApplicationName = ApplicationName }; Assert.NotNull(applicationInstance); ApplicationConfiguration config = await applicationInstance.Build(ApplicationUri, ProductUri) .AsServer(new string[] { "opc.tcp://localhost:51000" }) .AddUnsecurePolicyNone() .AddSignAndEncryptPolicies() .AddUserTokenPolicy(UserTokenType.UserName) .AsClient() .SetDefaultSessionTimeout(10000) .AddSecurityConfiguration(SubjectName, CertificateStoreType.X509Store) .Create().ConfigureAwait(false); Assert.NotNull(config); bool certOK = await applicationInstance.CheckApplicationInstanceCertificate(true, 0).ConfigureAwait(false); using (ICertificateStore store = applicationInstance.ApplicationConfiguration.SecurityConfiguration.TrustedPeerCertificates.OpenStore()) { await store.Add(applicationInstance.ApplicationConfiguration.SecurityConfiguration.ApplicationCertificate.Certificate); } Assert.True(certOK); }
public async Task TestNoFileConfigAsClientAndServer() { var applicationInstance = new ApplicationInstance() { ApplicationName = ApplicationName }; Assert.NotNull(applicationInstance); ApplicationConfiguration config = await applicationInstance.Build(ApplicationUri, ProductUri) .SetMaxBufferSize(32768) .AsServer(new string[] { EndpointUrl }) .AddUnsecurePolicyNone() .AddSignPolicies() .AddSignAndEncryptPolicies() .AddPolicy(MessageSecurityMode.Sign, SecurityPolicies.Basic256) .SetDiagnosticsEnabled(true) .AsClient() .AddSecurityConfiguration(SubjectName, CertificateStoreType.Directory, CertificateStoreType.X509Store) .Create().ConfigureAwait(false); Assert.NotNull(config); bool certOK = await applicationInstance.CheckApplicationInstanceCertificate(true, 0).ConfigureAwait(false); Assert.True(certOK); }
public async Task TestNoFileConfigAsServerX509Store() { #if NETCOREAPP2_1_OR_GREATER // this test fails on macOS, ignore if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Assert.Ignore("X509Store trust lists not supported on mac OS."); } #endif var applicationInstance = new ApplicationInstance() { ApplicationName = ApplicationName }; Assert.NotNull(applicationInstance); ApplicationConfiguration config = await applicationInstance.Build(ApplicationUri, ProductUri) .AsServer(new string[] { EndpointUrl }) .AddUnsecurePolicyNone() .AddSignAndEncryptPolicies() .AddUserTokenPolicy(UserTokenType.UserName) .AsClient() .SetDefaultSessionTimeout(10000) .AddSecurityConfiguration(SubjectName, CertificateStoreType.X509Store) .Create().ConfigureAwait(false); Assert.NotNull(config); var applicationCertificate = applicationInstance.ApplicationConfiguration.SecurityConfiguration.ApplicationCertificate; bool deleteAfterUse = applicationCertificate.Certificate != null; bool certOK = await applicationInstance.CheckApplicationInstanceCertificate(true, 0).ConfigureAwait(false); Assert.True(certOK); using (ICertificateStore store = applicationInstance.ApplicationConfiguration.SecurityConfiguration.TrustedPeerCertificates.OpenStore()) { // store public key in trusted store var rawData = applicationCertificate.Certificate.RawData; await store.Add(new X509Certificate2(rawData)); } if (deleteAfterUse) { var thumbprint = applicationCertificate.Certificate.Thumbprint; using (ICertificateStore store = applicationCertificate.OpenStore()) { bool success = await store.Delete(thumbprint); Assert.IsTrue(success); } using (ICertificateStore store = applicationInstance.ApplicationConfiguration.SecurityConfiguration.TrustedPeerCertificates.OpenStore()) { bool success = await store.Delete(thumbprint); Assert.IsTrue(success); } } }
public void TestBadNoApplicationNameConfigAsServer() { var applicationInstance = new ApplicationInstance(); Assert.NotNull(applicationInstance); Assert.ThrowsAsync <ServiceResultException>(async() => await applicationInstance.Build(ApplicationUri, ProductUri) .AsServer(new string[] { "opc.tcp://localhost:51000" }) .AddSecurityConfiguration(SubjectName) .Create() ); }
public async Task InvalidConfiguration() { var applicationInstance = new ApplicationInstance() { ApplicationName = ClientFixture.Config.ApplicationName }; Assert.NotNull(applicationInstance); ApplicationConfiguration config = await applicationInstance.Build(ClientFixture.Config.ApplicationUri, ClientFixture.Config.ProductUri) .AsClient() .AddSecurityConfiguration(ClientFixture.Config.SecurityConfiguration.ApplicationCertificate.SubjectName) .Create().ConfigureAwait(false); }
public async Task TestNoFileConfigAsClient() { var applicationInstance = new ApplicationInstance() { ApplicationName = ApplicationName }; Assert.NotNull(applicationInstance); ApplicationConfiguration config = await applicationInstance.Build(ApplicationUri, ProductUri) .AsClient() .AddSecurityConfiguration(SubjectName, m_pkiRoot) .Create().ConfigureAwait(false); Assert.NotNull(config); bool certOK = await applicationInstance.CheckApplicationInstanceCertificate(true, 0).ConfigureAwait(false); Assert.True(certOK); }
public async Task TestNoFileConfigAsServerMaximal() { var applicationInstance = new ApplicationInstance() { ApplicationName = ApplicationName }; Assert.NotNull(applicationInstance); ApplicationConfiguration config = await applicationInstance.Build(ApplicationUri, ProductUri) .SetTransportQuotas(new TransportQuotas() { OperationTimeout = 10000 }) .AsServer(new string[] { EndpointUrl }) .AddSignPolicies() .AddSignAndEncryptPolicies() .AddUnsecurePolicyNone() .AddPolicy(MessageSecurityMode.Sign, SecurityPolicies.Basic256) .AddPolicy(MessageSecurityMode.Sign, SecurityPolicies.Basic128Rsa15) .AddPolicy(MessageSecurityMode.SignAndEncrypt, SecurityPolicies.Basic256) .AddPolicy(MessageSecurityMode.SignAndEncrypt, SecurityPolicies.Basic128Rsa15) .AddUserTokenPolicy(UserTokenType.Anonymous) .AddUserTokenPolicy(UserTokenType.UserName) .AddUserTokenPolicy(new UserTokenPolicy(UserTokenType.Certificate) { SecurityPolicyUri = SecurityPolicies.Basic256Sha256 }) .SetDiagnosticsEnabled(true) .SetPublishingResolution(100) .AddSecurityConfiguration(SubjectName, m_pkiRoot) .SetAddAppCertToTrustedStore(true) .SetAutoAcceptUntrustedCertificates(true) .SetMinimumCertificateKeySize(1024) .SetRejectSHA1SignedCertificates(false) .SetSendCertificateChain(true) .SetSuppressNonceValidationErrors(true) .SetRejectUnknownRevocationStatus(true) .Create().ConfigureAwait(false); Assert.NotNull(config); bool certOK = await applicationInstance.CheckApplicationInstanceCertificate(true, 0).ConfigureAwait(false); Assert.True(certOK); }
public async Task TestNoFileConfigAsServerMinimal() { var applicationInstance = new ApplicationInstance() { ApplicationName = ApplicationName }; Assert.NotNull(applicationInstance); ApplicationConfiguration config = await applicationInstance.Build(ApplicationUri, ProductUri) .SetOperationTimeout(10000) .AsServer(new string[] { EndpointUrl }) .AddSecurityConfiguration(SubjectName, m_pkiRoot) .Create().ConfigureAwait(false); Assert.NotNull(config); bool certOK = await applicationInstance.CheckApplicationInstanceCertificate(true, 0).ConfigureAwait(false); Assert.True(certOK); }
public async Task TestNoFileConfigAsServerCustom() { var applicationInstance = new ApplicationInstance() { ApplicationName = ApplicationName }; Assert.NotNull(applicationInstance); ApplicationConfiguration config = await applicationInstance.Build(ApplicationUri, ProductUri) .AsServer(new string[] { EndpointUrl, "https://localhost:51001" }, new string[] { "opc.tcp://192.168.1.100:51000" }) .AddSecurityConfiguration(SubjectName, m_pkiRoot) .SetAddAppCertToTrustedStore(true) .Create().ConfigureAwait(false); Assert.NotNull(config); bool certOK = await applicationInstance.CheckApplicationInstanceCertificate(true, 0).ConfigureAwait(false); Assert.True(certOK); }
/// <summary> /// Load the default client configuration. /// </summary> public async Task LoadClientConfiguration(string pkiRoot = null, string clientName = "TestClient") { ApplicationInstance application = new ApplicationInstance { ApplicationName = clientName }; pkiRoot = pkiRoot ?? Path.Combine("%LocalApplicationData%", "OPC", "pki"); // build the application configuration. Config = await application .Build( "urn:localhost:opcfoundation.org:" + clientName, "http://opcfoundation.org/UA/" + clientName) .AsClient() .SetClientOperationLimits(new OperationLimits { MaxNodesPerBrowse = kDefaultOperationLimits, MaxNodesPerRead = kDefaultOperationLimits, MaxMonitoredItemsPerCall = kDefaultOperationLimits, MaxNodesPerWrite = kDefaultOperationLimits }) .AddSecurityConfiguration( "CN=" + clientName + ", O=OPC Foundation, DC=localhost", pkiRoot) .SetAutoAcceptUntrustedCertificates(true) .SetRejectSHA1SignedCertificates(false) .SetMinimumCertificateKeySize(1024) .SetOutputFilePath(Path.Combine(pkiRoot, "Logs", "Opc.Ua.Client.Tests.log.txt")) .SetTraceMasks(TraceMasks) .Create().ConfigureAwait(false); // check the application certificate. bool haveAppCertificate = await application.CheckApplicationInstanceCertificate(true, 0).ConfigureAwait(false); if (!haveAppCertificate) { throw new Exception("Application instance certificate invalid!"); } ReverseConnectManager = new ReverseConnectManager(); }
public async Task LoadClientConfiguration(int port = -1) { ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance { ApplicationName = "Global Discovery Client", ApplicationType = ApplicationType.Client, ConfigSectionName = "Opc.Ua.GlobalDiscoveryTestClient" }; #if USE_FILE_CONFIG // load the application configuration. Config = await application.LoadApplicationConfiguration(false).ConfigureAwait(false); #else string root = Path.Combine("%LocalApplicationData%", "OPC"); string pkiRoot = Path.Combine(root, "pki"); var clientConfig = new GlobalDiscoveryTestClientConfiguration() { GlobalDiscoveryServerUrl = "opc.tcp://localhost:58810/GlobalDiscoveryTestServer", AppUserName = "******", AppPassword = "******", AdminUserName = "******", AdminPassword = "******" }; // build the application configuration. Config = await application .Build( "urn:localhost:opcfoundation.org:GlobalDiscoveryTestClient", "http://opcfoundation.org/UA/GlobalDiscoveryTestClient") .AsClient() .AddSecurityConfiguration( "CN=Global Discovery Test Client, O=OPC Foundation, DC=localhost", pkiRoot) .SetAutoAcceptUntrustedCertificates(true) .SetRejectSHA1SignedCertificates(false) .SetRejectUnknownRevocationStatus(true) .SetMinimumCertificateKeySize(1024) .AddExtension <GlobalDiscoveryTestClientConfiguration>(null, clientConfig) .SetOutputFilePath(Path.Combine(root, "Logs", "Opc.Ua.Gds.Tests.log.txt")) .SetTraceMasks(519) .Create().ConfigureAwait(false); #endif // check the application certificate. bool haveAppCertificate = await application.CheckApplicationInstanceCertificate(true, 0).ConfigureAwait(false); if (!haveAppCertificate) { throw new Exception("Application instance certificate invalid!"); } Config.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation); GlobalDiscoveryTestClientConfiguration gdsClientConfiguration = application.ApplicationConfiguration.ParseExtension <GlobalDiscoveryTestClientConfiguration>(); m_client = new GlobalDiscoveryServerClient(application, gdsClientConfiguration.GlobalDiscoveryServerUrl) { EndpointUrl = TestUtils.PatchOnlyGDSEndpointUrlPort(gdsClientConfiguration.GlobalDiscoveryServerUrl, port) }; if (String.IsNullOrEmpty(gdsClientConfiguration.AppUserName)) { AppUser = new UserIdentity(new AnonymousIdentityToken()); } else { AppUser = new UserIdentity(gdsClientConfiguration.AppUserName, gdsClientConfiguration.AppPassword); } AdminUser = new UserIdentity(gdsClientConfiguration.AdminUserName, gdsClientConfiguration.AdminPassword); }
public async Task TestBadApplicationInstance() { // no app name var applicationInstance = new ApplicationInstance(); Assert.NotNull(applicationInstance); Assert.ThrowsAsync <ServiceResultException>(async() => await applicationInstance.Build(ApplicationUri, ProductUri) .AsServer(new string[] { EndpointUrl }) .AddSecurityConfiguration(SubjectName, m_pkiRoot) .Create() ); // discoveryserver can not be combined with client/server applicationInstance = new ApplicationInstance() { ApplicationName = ApplicationName, ApplicationType = ApplicationType.DiscoveryServer }; Assert.ThrowsAsync <ArgumentException>(async() => await applicationInstance.Build(ApplicationUri, ProductUri) .AsClient() .AddSecurityConfiguration(SubjectName, m_pkiRoot) .Create() ); Assert.ThrowsAsync <ArgumentException>(async() => await applicationInstance.Build(ApplicationUri, ProductUri) .AsServer(new string[] { EndpointUrl }) .AddSecurityConfiguration(SubjectName, m_pkiRoot) .Create() ); // server overrides client settings applicationInstance = new ApplicationInstance() { ApplicationName = ApplicationName, ApplicationType = ApplicationType.Client }; var config = await applicationInstance.Build(ApplicationUri, ProductUri) .AsServer(new string[] { EndpointUrl }) .AddSecurityConfiguration(SubjectName, m_pkiRoot) .Create(); Assert.AreEqual(ApplicationType.Server, applicationInstance.ApplicationType); // client overrides server setting applicationInstance = new ApplicationInstance() { ApplicationName = ApplicationName, ApplicationType = ApplicationType.Server }; await applicationInstance.Build(ApplicationUri, ProductUri) .AsClient() .AddSecurityConfiguration(SubjectName, m_pkiRoot) .Create(); Assert.AreEqual(ApplicationType.Client, applicationInstance.ApplicationType); // invalid sec policy testing applicationInstance = new ApplicationInstance() { ApplicationName = ApplicationName }; // invalid use, use AddUnsecurePolicyNone instead Assert.ThrowsAsync <ArgumentException>(async() => await applicationInstance.Build(ApplicationUri, ProductUri) .AsServer(new string[] { EndpointUrl }) .AddPolicy(MessageSecurityMode.None, SecurityPolicies.None) .AddSecurityConfiguration(SubjectName, m_pkiRoot) .Create() ); // invalid mix sign / none Assert.ThrowsAsync <ArgumentException>(async() => await applicationInstance.Build(ApplicationUri, ProductUri) .AsServer(new string[] { EndpointUrl }) .AddPolicy(MessageSecurityMode.Sign, SecurityPolicies.None) .AddSecurityConfiguration(SubjectName) .Create() ); // invalid policy Assert.ThrowsAsync <ArgumentException>(async() => await applicationInstance.Build(ApplicationUri, ProductUri) .AsServer(new string[] { EndpointUrl }) .AddPolicy(MessageSecurityMode.Sign, "123") .AddSecurityConfiguration(SubjectName, m_pkiRoot) .Create() ); // invalid user token policy Assert.ThrowsAsync <ArgumentNullException>(async() => await applicationInstance.Build(ApplicationUri, ProductUri) .AsServer(new string[] { EndpointUrl }) .AddUserTokenPolicy(null) .AddSecurityConfiguration(SubjectName, m_pkiRoot) .Create() ); }
/// <summary> /// Create the configuration and start the server. /// </summary> private async Task InternalStartServerAsync(TextWriter writer, int port) { ApplicationInstance application = new ApplicationInstance { ApplicationName = typeof(T).Name, ApplicationType = ApplicationType.Server }; // create the application configuration. Use temp path for cert stores. var pkiRoot = Path.GetTempPath() + Path.GetRandomFileName(); var endpointUrl = $"{UriScheme}://localhost:{port}/" + typeof(T).Name; var serverConfig = application.Build( "urn:localhost:UA:" + typeof(T).Name, "uri:opcfoundation.org:" + typeof(T).Name) .AsServer( new string[] { endpointUrl }); if (SecurityNone) { serverConfig.AddUnsecurePolicyNone(); } if (endpointUrl.StartsWith(Utils.UriSchemeHttps, StringComparison.InvariantCultureIgnoreCase)) { serverConfig.AddPolicy(MessageSecurityMode.SignAndEncrypt, SecurityPolicies.Basic256Sha256); } else if (endpointUrl.StartsWith(Utils.UriSchemeOpcTcp, StringComparison.InvariantCultureIgnoreCase)) { // add deprecated policies for opc.tcp tests serverConfig.AddPolicy(MessageSecurityMode.Sign, SecurityPolicies.Basic128Rsa15) .AddPolicy(MessageSecurityMode.Sign, SecurityPolicies.Basic256) .AddPolicy(MessageSecurityMode.SignAndEncrypt, SecurityPolicies.Basic128Rsa15) .AddPolicy(MessageSecurityMode.SignAndEncrypt, SecurityPolicies.Basic256) .AddSignPolicies() .AddSignAndEncryptPolicies(); } if (OperationLimits) { serverConfig.SetOperationLimits(new OperationLimits() { MaxNodesPerBrowse = 2500, MaxNodesPerRead = 250, MaxNodesPerWrite = 250, MaxNodesPerMethodCall = 500, MaxMonitoredItemsPerCall = 1000, MaxNodesPerTranslateBrowsePathsToNodeIds = 1000 }); } if (ReverseConnectTimeout != 0) { serverConfig.SetReverseConnect(new ReverseConnectServerConfiguration() { ConnectInterval = ReverseConnectTimeout / 4, ConnectTimeout = ReverseConnectTimeout, RejectTimeout = ReverseConnectTimeout / 4 }); } ApplicationConfiguration config = await serverConfig.AddSecurityConfiguration( "CN=" + typeof(T).Name + ", C=US, S=Arizona, O=OPC Foundation, DC=localhost", pkiRoot) .SetAutoAcceptUntrustedCertificates(AutoAccept) .Create().ConfigureAwait(false); if (writer != null) { m_traceLogger = NUnitTraceLogger.Create(writer, config, TraceMasks); } // check the application certificate. bool haveAppCertificate = await application.CheckApplicationInstanceCertificate( true, CertificateFactory.DefaultKeySize, CertificateFactory.DefaultLifeTime).ConfigureAwait(false); if (!haveAppCertificate) { throw new Exception("Application instance certificate invalid!"); } // start the server. T server = new T(); await application.Start(server).ConfigureAwait(false); Server = server; Port = port; }
public async Task LoadClientConfiguration(int port = -1) { ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); ApplicationInstance application = new ApplicationInstance { ApplicationName = "Server Configuration Push Test Client", ApplicationType = ApplicationType.Client, ConfigSectionName = "Opc.Ua.ServerConfigurationPushTestClient" }; #if USE_FILE_CONFIG // load the application configuration. Config = await application.LoadApplicationConfiguration(false).ConfigureAwait(false); #else string root = Path.Combine("%LocalApplicationData%", "OPC"); string pkiRoot = Path.Combine(root, "pki"); var clientConfig = new ServerConfigurationPushTestClientConfiguration() { ServerUrl = "opc.tcp://localhost:58810/GlobalDiscoveryTestServer", AppUserName = "", AppPassword = "", SysAdminUserName = "******", SysAdminPassword = "******", TempStorePath = Path.Combine(pkiRoot, "temp") }; var transportQuotas = new TransportQuotas() { OperationTimeout = 120000, MaxStringLength = 1048576, MaxByteStringLength = 1048576, MaxArrayLength = 65535, MaxMessageSize = 4194304, MaxBufferSize = 65535, ChannelLifetime = 300000, SecurityTokenLifetime = 3600000, }; // build the application configuration. Config = await application .Build( "urn:localhost:opcfoundation.org:ServerConfigurationPushTestClient", "http://opcfoundation.org/UA/ServerConfigurationPushTestClient") .SetTransportQuotas(transportQuotas) .AsClient() .AddSecurityConfiguration( "CN=Server Configuration Push Test Client, O=OPC Foundation", pkiRoot) .SetAutoAcceptUntrustedCertificates(true) .SetRejectSHA1SignedCertificates(false) .SetRejectUnknownRevocationStatus(true) .SetMinimumCertificateKeySize(1024) .AddExtension <ServerConfigurationPushTestClientConfiguration>(null, clientConfig) .SetOutputFilePath(pkiRoot + "/Logs/Opc.Ua.Gds.Tests.log.txt") .SetTraceMasks(Utils.TraceMasks.Error) .Create().ConfigureAwait(false); #endif // check the application certificate. bool haveAppCertificate = await application.CheckApplicationInstanceCertificate(true, 0).ConfigureAwait(false); if (!haveAppCertificate) { throw new Exception("Application instance certificate invalid!"); } Config.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation); ServerConfigurationPushTestClientConfiguration clientConfiguration = application.ApplicationConfiguration.ParseExtension <ServerConfigurationPushTestClientConfiguration>(); _client = new ServerPushConfigurationClient(application) { EndpointUrl = TestUtils.PatchOnlyGDSEndpointUrlPort(clientConfiguration.ServerUrl, port) }; if (String.IsNullOrEmpty(clientConfiguration.AppUserName)) { AppUser = new UserIdentity(new AnonymousIdentityToken()); } else { AppUser = new UserIdentity(clientConfiguration.AppUserName, clientConfiguration.AppPassword); } SysAdminUser = new UserIdentity(clientConfiguration.SysAdminUserName, clientConfiguration.SysAdminPassword); TempStorePath = clientConfiguration.TempStorePath; }
public async Task LoadConfiguration(string pkiRoot = null) { Application = new ApplicationInstance { ApplicationName = typeof(T).Name, ApplicationType = ApplicationType.Server }; // create the application configuration. Use temp path for cert stores. pkiRoot = pkiRoot ?? Path.GetTempPath() + Path.GetRandomFileName(); var endpointUrl = $"{UriScheme}://localhost:0/" + typeof(T).Name; var serverConfig = Application.Build( "urn:localhost:UA:" + typeof(T).Name, "uri:opcfoundation.org:" + typeof(T).Name) .AsServer( new string[] { endpointUrl }); if (SecurityNone) { serverConfig.AddUnsecurePolicyNone(); } if (endpointUrl.StartsWith(Utils.UriSchemeHttps, StringComparison.InvariantCultureIgnoreCase)) { serverConfig.AddPolicy(MessageSecurityMode.SignAndEncrypt, SecurityPolicies.Basic256Sha256); } else if (endpointUrl.StartsWith(Utils.UriSchemeOpcTcp, StringComparison.InvariantCultureIgnoreCase)) { // add deprecated policies for opc.tcp tests serverConfig.AddPolicy(MessageSecurityMode.Sign, SecurityPolicies.Basic128Rsa15) .AddPolicy(MessageSecurityMode.Sign, SecurityPolicies.Basic256) .AddPolicy(MessageSecurityMode.SignAndEncrypt, SecurityPolicies.Basic128Rsa15) .AddPolicy(MessageSecurityMode.SignAndEncrypt, SecurityPolicies.Basic256) .AddSignPolicies() .AddSignAndEncryptPolicies(); } if (OperationLimits) { serverConfig.SetOperationLimits(new OperationLimits() { MaxNodesPerBrowse = 2500, MaxNodesPerRead = 250, MaxNodesPerWrite = 250, MaxNodesPerMethodCall = 500, MaxMonitoredItemsPerCall = 1000, MaxNodesPerTranslateBrowsePathsToNodeIds = 1000 }); } if (ReverseConnectTimeout != 0) { serverConfig.SetReverseConnect(new ReverseConnectServerConfiguration() { ConnectInterval = ReverseConnectTimeout / 4, ConnectTimeout = ReverseConnectTimeout, RejectTimeout = ReverseConnectTimeout / 4 }); } Config = await serverConfig.AddSecurityConfiguration( "CN=" + typeof(T).Name + ", C=US, S=Arizona, O=OPC Foundation, DC=localhost", pkiRoot) .SetAutoAcceptUntrustedCertificates(AutoAccept) .Create().ConfigureAwait(false); }
//TODO [TestCase(InvalidCertType.KeySize1024, true, false)] public async Task TestInvalidAppCertChainDoNotRecreate(InvalidCertType certType, bool server, bool suppress) { // pki directory root for test runs. var pkiRoot = Path.GetTempPath() + Path.GetRandomFileName() + Path.DirectorySeparatorChar; var applicationInstance = new ApplicationInstance() { ApplicationName = ApplicationName }; Assert.NotNull(applicationInstance); ApplicationConfiguration config; if (server) { config = await applicationInstance.Build(ApplicationUri, ProductUri) .AsServer(new string[] { "opc.tcp://localhost:12345/Configuration" }) .AddSecurityConfiguration(SubjectName, pkiRoot) .Create().ConfigureAwait(false); } else { config = await applicationInstance.Build(ApplicationUri, ProductUri) .AsClient() .AddSecurityConfiguration(SubjectName, pkiRoot) .Create().ConfigureAwait(false); } Assert.NotNull(config); CertificateIdentifier applicationCertificate = applicationInstance.ApplicationConfiguration.SecurityConfiguration.ApplicationCertificate; Assert.IsNull(applicationCertificate.Certificate); var testCerts = CreateInvalidCertChain(certType); if (certType != InvalidCertType.NoIssuer) { using (var issuerCert = testCerts[1]) { Assert.NotNull(issuerCert); Assert.False(issuerCert.HasPrivateKey); issuerCert.AddToStore( applicationInstance.ApplicationConfiguration.SecurityConfiguration.TrustedIssuerCertificates.StoreType, applicationInstance.ApplicationConfiguration.SecurityConfiguration.TrustedIssuerCertificates.StorePath ); } } X509Certificate2 publicKey = null; using (var testCert = testCerts[0]) { Assert.NotNull(testCert); Assert.True(testCert.HasPrivateKey); testCert.AddToStore( applicationCertificate.StoreType, applicationCertificate.StorePath ); publicKey = new X509Certificate2(testCert.RawData); } using (publicKey) { if (suppress) { bool certOK = await applicationInstance.CheckApplicationInstanceCertificate(true, 0) .ConfigureAwait(false); Assert.True(certOK); Assert.AreEqual(publicKey, applicationCertificate.Certificate); } else { var sre = Assert.ThrowsAsync <ServiceResultException>(async() => await applicationInstance.CheckApplicationInstanceCertificate(true, 0).ConfigureAwait(false)); Assert.AreEqual(StatusCodes.BadConfigurationError, sre.StatusCode); } } }
/// <summary> /// Build the opc ua stack application configuration /// </summary> public static async Task <ApplicationConfiguration> BuildApplicationConfigurationAsync( this IClientServicesConfig opcConfig, IIdentity identity, CertificateValidationEventHandler handler, ILogger logger) { if (string.IsNullOrWhiteSpace(opcConfig.ApplicationName)) { throw new ArgumentNullException(nameof(opcConfig.ApplicationName)); } // wait with the configuration until network is up for (var retry = 0; retry < 3; retry++) { if (NetworkInterface.GetIsNetworkAvailable()) { break; } else { await Task.Delay(3000); } } var appInstance = new ApplicationInstance { ApplicationName = opcConfig.ApplicationName, ApplicationType = ApplicationType.Client, }; try { await Retry.WithLinearBackoff(null, new CancellationToken(), async() => { // try to resolve the hostname var hostname = !string.IsNullOrWhiteSpace(identity?.Gateway) ? identity.Gateway : !string.IsNullOrWhiteSpace(identity?.DeviceId) ? identity.DeviceId : Utils.GetHostName(); var appBuilder = appInstance .Build( opcConfig.ApplicationUri.Replace("urn:localhost", $"urn:{hostname}"), opcConfig.ProductUri) .SetTransportQuotas(opcConfig.ToTransportQuotas()) .AsClient(); var appConfig = await opcConfig .BuildSecurityConfiguration( appBuilder, appInstance.ApplicationConfiguration, hostname) .ConfigureAwait(false); appConfig.CertificateValidator.CertificateValidation += handler; var ownCertificate = appConfig.SecurityConfiguration.ApplicationCertificate.Certificate; if (ownCertificate == null) { logger.Information("No application own certificate found. Creating a self-signed " + "own certificate valid since yesterday for {defaultLifeTime} months, with a " + "{defaultKeySize} bit key and {defaultHashSize} bit hash.", CertificateFactory.DefaultLifeTime, CertificateFactory.DefaultKeySize, CertificateFactory.DefaultHashSize); } else { logger.Information("Own certificate Subject '{subject}' (thumbprint: {thumbprint}) loaded.", ownCertificate.Subject, ownCertificate.Thumbprint); } var hasAppCertificate = await appInstance .CheckApplicationInstanceCertificate( true, CertificateFactory.DefaultKeySize, CertificateFactory.DefaultLifeTime) .ConfigureAwait(false); if (!hasAppCertificate || appConfig.SecurityConfiguration.ApplicationCertificate.Certificate == null) { logger.Error("Failed to load or create application own certificate."); throw new InvalidConfigurationException("OPC UA application own certificate invalid"); } if (ownCertificate == null) { ownCertificate = appConfig.SecurityConfiguration.ApplicationCertificate.Certificate; logger.Information("Own certificate Subject '{subject}' (thumbprint: {thumbprint}) created.", ownCertificate.Subject, ownCertificate.Thumbprint); } await ShowCertificateStoreInformationAsync(appConfig, logger) .ConfigureAwait(false); }, e => true, 5); } catch (Exception e) { throw new InvalidConfigurationException("OPC UA configuration not valid", e); } return(appInstance.ApplicationConfiguration); }