Search in sources :

Example 1 with DefaultTrustListManager

use of org.eclipse.milo.opcua.stack.core.security.DefaultTrustListManager in project tech-pdai-spring-demos by realpdai.

the class OpcUaClientServiceImpl method getOpcUaClientSSLConfig.

/**
 * @param opcUaProperties opcUaProperties
 * @return ssl client config
 * @throws java.security.KeyStoreException         KeyStore Exception
 * @throws java.io.IOException                     IO Exception
 * @throws java.security.cert.CertificateException Certificate Exception
 * @throws java.security.NoSuchAlgorithmException  NoSuchAlgorithm Exception
 * @throws java.security.UnrecoverableKeyException UnrecoverableKey Exception
 */
private OpcUaSSLConfig getOpcUaClientSSLConfig(OpcUaProperties opcUaProperties) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException {
    OpcUaSSLConfig sslConfig = new OpcUaSSLConfig();
    // load keys from security dir
    Path securityTempDir = Paths.get(System.getProperty("java.io.tmpdir"), "client", "security");
    Files.createDirectories(securityTempDir);
    if (!Files.exists(securityTempDir)) {
        log.error("unable to create security dir: " + securityTempDir);
    }
    File pkiDir = securityTempDir.resolve("pki").toFile();
    log.info("security dir: {}", securityTempDir.toAbsolutePath());
    log.info("security pki dir: {}", pkiDir.getAbsolutePath());
    KeyStore keyStore = KeyStore.getInstance(opcUaProperties.getClient().getSslCertificateType());
    Path serverKeyStore = securityTempDir.resolve(opcUaProperties.getClient().getSslCertificateFile());
    log.info("Loading KeyStore at {}", serverKeyStore);
    try (InputStream in = Files.newInputStream(serverKeyStore)) {
        keyStore.load(in, opcUaProperties.getClient().getSslCertificatePwd().toCharArray());
    }
    // setup certificate
    Key clientPrivateKey = keyStore.getKey(opcUaProperties.getClient().getSslCertificateAlias(), opcUaProperties.getClient().getSslCertificatePwd().toCharArray());
    if (clientPrivateKey instanceof PrivateKey) {
        sslConfig.setCertificate((X509Certificate) keyStore.getCertificate(opcUaProperties.getClient().getSslCertificateAlias()));
        sslConfig.setCertificateChain(Arrays.stream(keyStore.getCertificateChain(opcUaProperties.getClient().getSslCertificateAlias())).map(X509Certificate.class::cast).toArray(X509Certificate[]::new));
        PublicKey serverPublicKey = sslConfig.getCertificate().getPublicKey();
        sslConfig.setClientKeyPair(new KeyPair(serverPublicKey, (PrivateKey) clientPrivateKey));
    }
    // client validator
    DefaultTrustListManager trustListManager = new DefaultTrustListManager(pkiDir);
    sslConfig.setCertificateValidator(new DefaultClientCertificateValidator(trustListManager));
    return sslConfig;
}
Also used : Path(java.nio.file.Path) KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) DefaultTrustListManager(org.eclipse.milo.opcua.stack.core.security.DefaultTrustListManager) InputStream(java.io.InputStream) PublicKey(java.security.PublicKey) OpcUaSSLConfig(tech.pdai.opcua.milo.client.config.OpcUaSSLConfig) File(java.io.File) KeyStore(java.security.KeyStore) DefaultClientCertificateValidator(org.eclipse.milo.opcua.stack.client.security.DefaultClientCertificateValidator) Key(java.security.Key) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) X509Certificate(java.security.cert.X509Certificate)

Example 2 with DefaultTrustListManager

use of org.eclipse.milo.opcua.stack.core.security.DefaultTrustListManager 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 DefaultTrustListManager

use of org.eclipse.milo.opcua.stack.core.security.DefaultTrustListManager in project milo by eclipse.

the class OpcUaServerConfigTest method testCopy.

@Test
public void testCopy() throws IOException {
    DefaultTrustListManager trustListManager = new DefaultTrustListManager(Files.createTempDir());
    ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    OpcUaServerConfig original = OpcUaServerConfig.builder().setCertificateManager(new DefaultCertificateManager()).setTrustListManager(trustListManager).setCertificateValidator(new DefaultServerCertificateValidator(trustListManager)).setIdentityValidator(AnonymousIdentityValidator.INSTANCE).setBuildInfo(new BuildInfo("a", "b", "c", "d", "e", DateTime.MIN_VALUE)).setLimits(new OpcUaServerConfigLimits() {
    }).setScheduledExecutorService(scheduledExecutorService).build();
    OpcUaServerConfig copy = OpcUaServerConfig.copy(original).build();
    assertEquals(copy.getIdentityValidator(), original.getIdentityValidator());
    assertEquals(copy.getBuildInfo(), original.getBuildInfo());
    assertEquals(copy.getLimits(), original.getLimits());
    assertEquals(copy.getScheduledExecutorService(), original.getScheduledExecutorService());
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) DefaultTrustListManager(org.eclipse.milo.opcua.stack.core.security.DefaultTrustListManager) DefaultCertificateManager(org.eclipse.milo.opcua.stack.core.security.DefaultCertificateManager) BuildInfo(org.eclipse.milo.opcua.stack.core.types.structured.BuildInfo) DefaultServerCertificateValidator(org.eclipse.milo.opcua.stack.server.security.DefaultServerCertificateValidator) Test(org.testng.annotations.Test)

Example 4 with DefaultTrustListManager

use of org.eclipse.milo.opcua.stack.core.security.DefaultTrustListManager in project milo by eclipse.

the class ClientExampleRunner method createClient.

private OpcUaClient createClient() throws Exception {
    Path securityTempDir = Paths.get(System.getProperty("java.io.tmpdir"), "client", "security");
    Files.createDirectories(securityTempDir);
    if (!Files.exists(securityTempDir)) {
        throw new Exception("unable to create security dir: " + securityTempDir);
    }
    File pkiDir = securityTempDir.resolve("pki").toFile();
    LoggerFactory.getLogger(getClass()).info("security dir: {}", securityTempDir.toAbsolutePath());
    LoggerFactory.getLogger(getClass()).info("security pki dir: {}", pkiDir.getAbsolutePath());
    KeyStoreLoader loader = new KeyStoreLoader().load(securityTempDir);
    trustListManager = new DefaultTrustListManager(pkiDir);
    DefaultClientCertificateValidator certificateValidator = new DefaultClientCertificateValidator(trustListManager);
    return OpcUaClient.create(clientExample.getEndpointUrl(), endpoints -> endpoints.stream().filter(clientExample.endpointFilter()).findFirst(), configBuilder -> configBuilder.setApplicationName(LocalizedText.english("eclipse milo opc-ua client")).setApplicationUri("urn:eclipse:milo:examples:client").setKeyPair(loader.getClientKeyPair()).setCertificate(loader.getClientCertificate()).setCertificateChain(loader.getClientCertificateChain()).setCertificateValidator(certificateValidator).setIdentityProvider(clientExample.getIdentityProvider()).setRequestTimeout(uint(5000)).build());
}
Also used : Path(java.nio.file.Path) DefaultTrustListManager(org.eclipse.milo.opcua.stack.core.security.DefaultTrustListManager) File(java.io.File) DefaultClientCertificateValidator(org.eclipse.milo.opcua.stack.client.security.DefaultClientCertificateValidator) ExecutionException(java.util.concurrent.ExecutionException)

Example 5 with DefaultTrustListManager

use of org.eclipse.milo.opcua.stack.core.security.DefaultTrustListManager 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)

Aggregations

DefaultTrustListManager (org.eclipse.milo.opcua.stack.core.security.DefaultTrustListManager)5 File (java.io.File)4 KeyPair (java.security.KeyPair)3 X509Certificate (java.security.cert.X509Certificate)3 DefaultCertificateManager (org.eclipse.milo.opcua.stack.core.security.DefaultCertificateManager)3 BuildInfo (org.eclipse.milo.opcua.stack.core.types.structured.BuildInfo)3 DefaultServerCertificateValidator (org.eclipse.milo.opcua.stack.server.security.DefaultServerCertificateValidator)3 Path (java.nio.file.Path)2 OpcUaServer (org.eclipse.milo.opcua.sdk.server.OpcUaServer)2 OpcUaServerConfig (org.eclipse.milo.opcua.sdk.server.api.config.OpcUaServerConfig)2 DefaultClientCertificateValidator (org.eclipse.milo.opcua.stack.client.security.DefaultClientCertificateValidator)2 UaRuntimeException (org.eclipse.milo.opcua.stack.core.UaRuntimeException)2 SelfSignedHttpsCertificateBuilder (org.eclipse.milo.opcua.stack.core.util.SelfSignedHttpsCertificateBuilder)2 EndpointConfiguration (org.eclipse.milo.opcua.stack.server.EndpointConfiguration)2 InputStream (java.io.InputStream)1 Key (java.security.Key)1 KeyStore (java.security.KeyStore)1 PrivateKey (java.security.PrivateKey)1 PublicKey (java.security.PublicKey)1 ExecutionException (java.util.concurrent.ExecutionException)1