Search in sources :

Example 1 with SelfSignedHttpsCertificateBuilder

use of org.eclipse.milo.opcua.stack.core.util.SelfSignedHttpsCertificateBuilder in project OpenMUC by isc-konstanz.

the class OpcServer method activate.

@Activate
public void activate() throws Exception {
    logger.info("Activating OPC UA Server");
    File securityTempDir = new File(System.getProperty("java.io.tmpdir"), "security");
    if (!securityTempDir.exists() && !securityTempDir.mkdirs()) {
        throw new Exception("Unable to create security temp dir: " + securityTempDir);
    }
    logger.debug("OPC UA security temp dir: {}", securityTempDir.getAbsolutePath());
    KeyStoreLoader loader = new KeyStoreLoader().load(securityTempDir);
    DefaultCertificateManager certificateManager = new DefaultCertificateManager(loader.getServerKeyPair(), loader.getServerCertificateChain());
    File pkiDir = securityTempDir.toPath().resolve("pki").toFile();
    DefaultTrustListManager trustListManager = new DefaultTrustListManager(pkiDir);
    logger.debug("OPC UA pki dir: {}", pkiDir.getAbsolutePath());
    DefaultServerCertificateValidator certificateValidator = new DefaultServerCertificateValidator(trustListManager);
    KeyPair httpsKeyPair = SelfSignedCertificateGenerator.generateRsaKeyPair(2048);
    SelfSignedHttpsCertificateBuilder httpsCertificateBuilder = new SelfSignedHttpsCertificateBuilder(httpsKeyPair);
    httpsCertificateBuilder.setCommonName(HostnameUtil.getHostname());
    HostnameUtil.getHostnames("0.0.0.0").forEach(httpsCertificateBuilder::addDnsName);
    X509Certificate httpsCertificate = httpsCertificateBuilder.build();
    // UsernameIdentityValidator identityValidator = new UsernameIdentityValidator(true, authChallenge -> {
    // String username = authChallenge.getUsername();
    // String password = authChallenge.getPassword();
    // 
    // boolean userOk = "user".equals(username) && "password1".equals(password);
    // boolean adminOk = "admin".equals(username) && "password2".equals(password);
    // 
    // return userOk || adminOk;
    // });
    // 
    // X509IdentityValidator x509IdentityValidator = new X509IdentityValidator(c -> true);
    // If you need to use multiple certificates you'll have to be smarter than this.
    X509Certificate certificate = certificateManager.getCertificates().stream().findFirst().orElseThrow(() -> new UaRuntimeException(StatusCodes.Bad_ConfigurationError, "no certificate found"));
    // The configured application URI must match the one in the certificate(s)
    String applicationUri = CertificateUtil.getSanUri(certificate).orElseThrow(() -> new UaRuntimeException(StatusCodes.Bad_ConfigurationError, "certificate is missing the application URI"));
    Set<EndpointConfiguration> endpointConfigurations = createEndpointConfigurations(certificate);
    OpcUaServerConfig serverConfig = OpcUaServerConfig.builder().setApplicationUri(applicationUri).setApplicationName(LocalizedText.english("OpenMUC OPC UA Server")).setEndpoints(endpointConfigurations).setBuildInfo(new BuildInfo("urn:openmuc:server", "openmuc", "openmuc server", OpcUaServer.SDK_VERSION, "", new DateTime(System.currentTimeMillis()))).setCertificateManager(certificateManager).setTrustListManager(trustListManager).setCertificateValidator(certificateValidator).setHttpsKeyPair(httpsKeyPair).setHttpsCertificate(httpsCertificate).setProductUri("urn:openmuc:server").build();
    server = new OpcUaServer(serverConfig);
    server.startup();
}
Also used : KeyPair(java.security.KeyPair) OpcUaServer(org.eclipse.milo.opcua.sdk.server.OpcUaServer) OpcUaServerConfig(org.eclipse.milo.opcua.sdk.server.api.config.OpcUaServerConfig) UaRuntimeException(org.eclipse.milo.opcua.stack.core.UaRuntimeException) UaException(org.eclipse.milo.opcua.stack.core.UaException) X509Certificate(java.security.cert.X509Certificate) DateTime(org.eclipse.milo.opcua.stack.core.types.builtin.DateTime) UaRuntimeException(org.eclipse.milo.opcua.stack.core.UaRuntimeException) DefaultTrustListManager(org.eclipse.milo.opcua.stack.core.security.DefaultTrustListManager) SelfSignedHttpsCertificateBuilder(org.eclipse.milo.opcua.stack.core.util.SelfSignedHttpsCertificateBuilder) DefaultCertificateManager(org.eclipse.milo.opcua.stack.core.security.DefaultCertificateManager) BuildInfo(org.eclipse.milo.opcua.stack.core.types.structured.BuildInfo) EndpointConfiguration(org.eclipse.milo.opcua.stack.server.EndpointConfiguration) File(java.io.File) DefaultServerCertificateValidator(org.eclipse.milo.opcua.stack.server.security.DefaultServerCertificateValidator) Activate(org.osgi.service.component.annotations.Activate)

Example 2 with SelfSignedHttpsCertificateBuilder

use of org.eclipse.milo.opcua.stack.core.util.SelfSignedHttpsCertificateBuilder in project milo by eclipse.

the class TestServer method create.

public static OpcUaServer create(int port) throws Exception {
    File securityTempDir = new File(System.getProperty("java.io.tmpdir"), "security");
    if (!securityTempDir.exists() && !securityTempDir.mkdirs()) {
        throw new Exception("unable to create security temp dir: " + securityTempDir);
    }
    LoggerFactory.getLogger(TestServer.class).info("security temp dir: {}", securityTempDir.getAbsolutePath());
    KeyStoreLoader loader = new KeyStoreLoader().load(securityTempDir);
    DefaultCertificateManager certificateManager = new DefaultCertificateManager(loader.getServerKeyPair(), loader.getServerCertificateChain());
    File pkiDir = securityTempDir.toPath().resolve("pki").toFile();
    DefaultTrustListManager trustListManager = new DefaultTrustListManager(pkiDir);
    LoggerFactory.getLogger(TestServer.class).info("pki dir: {}", pkiDir.getAbsolutePath());
    DefaultServerCertificateValidator certificateValidator = new DefaultServerCertificateValidator(trustListManager);
    KeyPair httpsKeyPair = SelfSignedCertificateGenerator.generateRsaKeyPair(2048);
    SelfSignedHttpsCertificateBuilder httpsCertificateBuilder = new SelfSignedHttpsCertificateBuilder(httpsKeyPair);
    httpsCertificateBuilder.setCommonName(HostnameUtil.getHostname());
    HostnameUtil.getHostnames("localhost", false).forEach(httpsCertificateBuilder::addDnsName);
    X509Certificate httpsCertificate = httpsCertificateBuilder.build();
    UsernameIdentityValidator identityValidator = new UsernameIdentityValidator(true, authChallenge -> {
        String username = authChallenge.getUsername();
        String password = authChallenge.getPassword();
        boolean user1 = "user1".equals(username) && "password".equals(password);
        boolean user2 = "user2".equals(username) && "password".equals(password);
        boolean admin = "admin".equals(username) && "password".equals(password);
        return user1 || user2 || admin;
    });
    // If you need to use multiple certificates you'll have to be smarter than this.
    X509Certificate certificate = certificateManager.getCertificates().stream().findFirst().orElseThrow(() -> new UaRuntimeException(StatusCodes.Bad_ConfigurationError, "no certificate found"));
    // The configured application URI must match the one in the certificate(s)
    String applicationUri = CertificateUtil.getSanUri(certificate).orElseThrow(() -> new UaRuntimeException(StatusCodes.Bad_ConfigurationError, "certificate is missing the application URI"));
    Set<EndpointConfiguration> endpointConfigurations = createEndpointConfigurations(certificate, port);
    OpcUaServerConfig serverConfig = OpcUaServerConfig.builder().setApplicationUri(applicationUri).setApplicationName(LocalizedText.english("Eclipse Milo OPC UA Example Server")).setEndpoints(endpointConfigurations).setBuildInfo(new BuildInfo("urn:eclipse:milo:example-server", "eclipse", "eclipse milo example server", OpcUaServer.SDK_VERSION, "", DateTime.now())).setCertificateManager(certificateManager).setTrustListManager(trustListManager).setCertificateValidator(certificateValidator).setHttpsKeyPair(httpsKeyPair).setHttpsCertificate(httpsCertificate).setIdentityValidator(identityValidator).setProductUri("urn:eclipse:milo:example-server").build();
    return new OpcUaServer(serverConfig);
}
Also used : KeyPair(java.security.KeyPair) OpcUaServer(org.eclipse.milo.opcua.sdk.server.OpcUaServer) OpcUaServerConfig(org.eclipse.milo.opcua.sdk.server.api.config.OpcUaServerConfig) UaRuntimeException(org.eclipse.milo.opcua.stack.core.UaRuntimeException) X509Certificate(java.security.cert.X509Certificate) UaRuntimeException(org.eclipse.milo.opcua.stack.core.UaRuntimeException) DefaultTrustListManager(org.eclipse.milo.opcua.stack.core.security.DefaultTrustListManager) SelfSignedHttpsCertificateBuilder(org.eclipse.milo.opcua.stack.core.util.SelfSignedHttpsCertificateBuilder) UsernameIdentityValidator(org.eclipse.milo.opcua.sdk.server.identity.UsernameIdentityValidator) DefaultCertificateManager(org.eclipse.milo.opcua.stack.core.security.DefaultCertificateManager) BuildInfo(org.eclipse.milo.opcua.stack.core.types.structured.BuildInfo) EndpointConfiguration(org.eclipse.milo.opcua.stack.server.EndpointConfiguration) File(java.io.File) DefaultServerCertificateValidator(org.eclipse.milo.opcua.stack.server.security.DefaultServerCertificateValidator)

Example 3 with SelfSignedHttpsCertificateBuilder

use of org.eclipse.milo.opcua.stack.core.util.SelfSignedHttpsCertificateBuilder in project milo by eclipse.

the class StackIntegrationTest method setUpClientServer.

@BeforeSuite
public void setUpClientServer() throws Exception {
    super.setUp();
    int tcpBindPort = getTcpBindPort();
    int httpsBindPort = getHttpsBindPort();
    KeyPair httpsKeyPair = SelfSignedCertificateGenerator.generateRsaKeyPair(2048);
    X509Certificate httpsCertificate = new SelfSignedHttpsCertificateBuilder(httpsKeyPair).setCommonName("localhost").build();
    List<String> bindAddresses = newArrayList();
    bindAddresses.add("localhost");
    List<String> hostnames = newArrayList();
    hostnames.add("localhost");
    Set<EndpointConfiguration> endpointConfigurations = new LinkedHashSet<>();
    for (String bindAddress : bindAddresses) {
        for (String hostname : hostnames) {
            EndpointConfiguration.Builder base = EndpointConfiguration.newBuilder().setBindAddress(bindAddress).setHostname(hostname).setPath("/test").setCertificate(serverCertificate).addTokenPolicies(USER_TOKEN_POLICY_ANONYMOUS);
            // TCP Transport Endpoints
            endpointConfigurations.add(base.copy().setBindPort(tcpBindPort).setSecurityPolicy(SecurityPolicy.None).setSecurityMode(MessageSecurityMode.None).setTransportProfile(TransportProfile.TCP_UASC_UABINARY).build());
            endpointConfigurations.add(base.copy().setBindPort(tcpBindPort).setSecurityPolicy(SecurityPolicy.Basic256Sha256).setSecurityMode(MessageSecurityMode.SignAndEncrypt).setTransportProfile(TransportProfile.TCP_UASC_UABINARY).build());
            // HTTPS Transport Endpoints
            endpointConfigurations.add(base.copy().setBindPort(httpsBindPort).setSecurityPolicy(SecurityPolicy.None).setSecurityMode(MessageSecurityMode.None).setTransportProfile(TransportProfile.HTTPS_UABINARY).build());
            endpointConfigurations.add(base.copy().setBindPort(httpsBindPort).setSecurityPolicy(SecurityPolicy.Basic256Sha256).setSecurityMode(MessageSecurityMode.SignAndEncrypt).setTransportProfile(TransportProfile.HTTPS_UABINARY).build());
        }
    }
    UaStackServerConfig serverConfig = configureServer(UaStackServerConfig.builder().setEndpoints(endpointConfigurations).setCertificateManager(serverCertificateManager).setCertificateValidator(serverCertificateValidator).setHttpsKeyPair(httpsKeyPair).setHttpsCertificate(httpsCertificate)).build();
    stackServer = new UaStackServer(serverConfig);
    stackServer.startup().get();
    String discoveryUrl = getDiscoveryUrl();
    EndpointDescription endpoint = selectEndpoint(DiscoveryClient.getEndpoints(discoveryUrl).thenApply(endpoints -> {
        endpoints.forEach(e -> logger.info("discovered endpoint: {}", e.getEndpointUrl()));
        return endpoints;
    }).get());
    UaStackClientConfig clientConfig = configureClient(UaStackClientConfig.builder().setEndpoint(endpoint).setKeyPair(clientKeyPair).setCertificate(clientCertificate).setRequestTimeout(uint(5000))).build();
    stackClient = UaStackClient.create(clientConfig);
    stackClient.connect().get();
}
Also used : LinkedHashSet(java.util.LinkedHashSet) KeyPair(java.security.KeyPair) UaStackServerConfig(org.eclipse.milo.opcua.stack.server.UaStackServerConfig) EndpointDescription(org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription) UaStackClientConfig(org.eclipse.milo.opcua.stack.client.UaStackClientConfig) Unsigned.uint(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint) X509Certificate(java.security.cert.X509Certificate) SelfSignedHttpsCertificateBuilder(org.eclipse.milo.opcua.stack.core.util.SelfSignedHttpsCertificateBuilder) EndpointConfiguration(org.eclipse.milo.opcua.stack.server.EndpointConfiguration) UaStackServer(org.eclipse.milo.opcua.stack.server.UaStackServer) BeforeSuite(org.testng.annotations.BeforeSuite)

Aggregations

KeyPair (java.security.KeyPair)3 X509Certificate (java.security.cert.X509Certificate)3 SelfSignedHttpsCertificateBuilder (org.eclipse.milo.opcua.stack.core.util.SelfSignedHttpsCertificateBuilder)3 EndpointConfiguration (org.eclipse.milo.opcua.stack.server.EndpointConfiguration)3 File (java.io.File)2 OpcUaServer (org.eclipse.milo.opcua.sdk.server.OpcUaServer)2 OpcUaServerConfig (org.eclipse.milo.opcua.sdk.server.api.config.OpcUaServerConfig)2 UaRuntimeException (org.eclipse.milo.opcua.stack.core.UaRuntimeException)2 DefaultCertificateManager (org.eclipse.milo.opcua.stack.core.security.DefaultCertificateManager)2 DefaultTrustListManager (org.eclipse.milo.opcua.stack.core.security.DefaultTrustListManager)2 BuildInfo (org.eclipse.milo.opcua.stack.core.types.structured.BuildInfo)2 DefaultServerCertificateValidator (org.eclipse.milo.opcua.stack.server.security.DefaultServerCertificateValidator)2 LinkedHashSet (java.util.LinkedHashSet)1 UsernameIdentityValidator (org.eclipse.milo.opcua.sdk.server.identity.UsernameIdentityValidator)1 UaStackClientConfig (org.eclipse.milo.opcua.stack.client.UaStackClientConfig)1 UaException (org.eclipse.milo.opcua.stack.core.UaException)1 DateTime (org.eclipse.milo.opcua.stack.core.types.builtin.DateTime)1 Unsigned.uint (org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint)1 EndpointDescription (org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription)1 UaStackServer (org.eclipse.milo.opcua.stack.server.UaStackServer)1