-
Notifications
You must be signed in to change notification settings - Fork 413
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Łukasz Dywicki <[email protected]>
- Loading branch information
Showing
3 changed files
with
266 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
238 changes: 238 additions & 0 deletions
238
plc4j/drivers/opcua/src/test/java/org/eclipse/milo/examples/server/TestMiloServer.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,238 @@ | ||
/* | ||
* Licensed to the Apache Software Foundation (ASF) under one | ||
* or more contributor license agreements. See the NOTICE file | ||
* distributed with this work for additional information | ||
* regarding copyright ownership. The ASF licenses this file | ||
* to you under the Apache License, Version 2.0 (the | ||
* "License"); you may not use this file except in compliance | ||
* with the License. You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, | ||
* software distributed under the License is distributed on an | ||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
* KIND, either express or implied. See the License for the | ||
* specific language governing permissions and limitations | ||
* under the License. | ||
*/ | ||
|
||
package org.eclipse.milo.examples.server; | ||
|
||
import static com.google.common.collect.Lists.newArrayList; | ||
import static org.eclipse.milo.opcua.sdk.server.api.config.OpcUaServerConfig.USER_TOKEN_POLICY_ANONYMOUS; | ||
import static org.eclipse.milo.opcua.sdk.server.api.config.OpcUaServerConfig.USER_TOKEN_POLICY_USERNAME; | ||
import static org.eclipse.milo.opcua.sdk.server.api.config.OpcUaServerConfig.USER_TOKEN_POLICY_X509; | ||
|
||
import java.io.File; | ||
import java.nio.file.Files; | ||
import java.nio.file.Path; | ||
import java.nio.file.Paths; | ||
import java.security.KeyPair; | ||
import java.security.cert.X509Certificate; | ||
import java.util.ArrayList; | ||
import java.util.LinkedHashSet; | ||
import java.util.List; | ||
import java.util.Set; | ||
import java.util.concurrent.CompletableFuture; | ||
import org.eclipse.milo.opcua.sdk.server.OpcUaServer; | ||
import org.eclipse.milo.opcua.sdk.server.api.config.OpcUaServerConfig; | ||
import org.eclipse.milo.opcua.sdk.server.identity.CompositeValidator; | ||
import org.eclipse.milo.opcua.sdk.server.identity.UsernameIdentityValidator; | ||
import org.eclipse.milo.opcua.sdk.server.identity.X509IdentityValidator; | ||
import org.eclipse.milo.opcua.sdk.server.util.HostnameUtil; | ||
import org.eclipse.milo.opcua.stack.core.StatusCodes; | ||
import org.eclipse.milo.opcua.stack.core.UaRuntimeException; | ||
import org.eclipse.milo.opcua.stack.core.security.DefaultCertificateManager; | ||
import org.eclipse.milo.opcua.stack.core.security.DefaultTrustListManager; | ||
import org.eclipse.milo.opcua.stack.core.security.SecurityPolicy; | ||
import org.eclipse.milo.opcua.stack.core.transport.TransportProfile; | ||
import org.eclipse.milo.opcua.stack.core.types.builtin.DateTime; | ||
import org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText; | ||
import org.eclipse.milo.opcua.stack.core.types.enumerated.MessageSecurityMode; | ||
import org.eclipse.milo.opcua.stack.core.types.structured.BuildInfo; | ||
import org.eclipse.milo.opcua.stack.core.util.CertificateUtil; | ||
import org.eclipse.milo.opcua.stack.core.util.SelfSignedCertificateGenerator; | ||
import org.eclipse.milo.opcua.stack.core.util.SelfSignedHttpsCertificateBuilder; | ||
import org.eclipse.milo.opcua.stack.server.EndpointConfiguration; | ||
import org.eclipse.milo.opcua.stack.server.security.DefaultServerCertificateValidator; | ||
import org.slf4j.LoggerFactory; | ||
|
||
/** | ||
* A test server implementation which. | ||
*/ | ||
public class TestMiloServer { | ||
|
||
private static final int TCP_BIND_PORT = 12686; | ||
private static final int HTTPS_BIND_PORT = 8443; | ||
|
||
private final OpcUaServer server; | ||
private final ExampleNamespace exampleNamespace; | ||
|
||
public TestMiloServer() throws Exception { | ||
Path securityTempDir = Paths.get(System.getProperty("java.io.tmpdir"), "server", "security"); | ||
Files.createDirectories(securityTempDir); | ||
if (!Files.exists(securityTempDir)) { | ||
throw new Exception("unable to create security temp 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); | ||
|
||
DefaultCertificateManager certificateManager = new DefaultCertificateManager( | ||
loader.getServerKeyPair(), | ||
loader.getServerCertificateChain() | ||
); | ||
|
||
DefaultTrustListManager trustListManager = new DefaultTrustListManager(pkiDir); | ||
trustListManager.setTrustedCertificates(new ArrayList<>(certificateManager.getCertificates())); | ||
|
||
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("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) | ||
.setHttpsCertificateChain(new X509Certificate[]{httpsCertificate}) | ||
.setIdentityValidator(new CompositeValidator(identityValidator, x509IdentityValidator)) | ||
.setProductUri("urn:eclipse:milo:example-server") | ||
.build(); | ||
|
||
server = new OpcUaServer(serverConfig); | ||
|
||
exampleNamespace = new ExampleNamespace(server); | ||
exampleNamespace.startup(); | ||
} | ||
|
||
private Set<EndpointConfiguration> createEndpointConfigurations(X509Certificate certificate) { | ||
Set<EndpointConfiguration> endpointConfigurations = new LinkedHashSet<>(); | ||
|
||
List<String> bindAddresses = newArrayList(); | ||
bindAddresses.add("0.0.0.0"); | ||
|
||
Set<String> hostnames = new LinkedHashSet<>(); | ||
hostnames.add(HostnameUtil.getHostname()); | ||
hostnames.addAll(HostnameUtil.getHostnames("0.0.0.0")); | ||
|
||
for (String bindAddress : bindAddresses) { | ||
for (String hostname : hostnames) { | ||
EndpointConfiguration.Builder builder = EndpointConfiguration.newBuilder() | ||
.setBindAddress(bindAddress) | ||
.setHostname(hostname) | ||
.setPath("/milo") | ||
.setCertificate(certificate) | ||
.addTokenPolicies( | ||
USER_TOKEN_POLICY_ANONYMOUS, | ||
USER_TOKEN_POLICY_USERNAME, | ||
USER_TOKEN_POLICY_X509 | ||
); | ||
|
||
|
||
EndpointConfiguration.Builder noSecurityBuilder = builder.copy() | ||
.setSecurityPolicy(SecurityPolicy.None) | ||
.setSecurityMode(MessageSecurityMode.None); | ||
|
||
endpointConfigurations.add(buildTcpEndpoint(noSecurityBuilder)); | ||
|
||
// TCP Basic256Sha256 / SignAndEncrypt | ||
endpointConfigurations.add(buildTcpEndpoint( | ||
builder.copy() | ||
.setSecurityPolicy(SecurityPolicy.Basic256Sha256) | ||
.setSecurityMode(MessageSecurityMode.SignAndEncrypt)) | ||
); | ||
// TCP Basic128Rsa15 / SignAndEncrypt | ||
endpointConfigurations.add(buildTcpEndpoint( | ||
builder.copy() | ||
.setSecurityPolicy(SecurityPolicy.Basic128Rsa15) | ||
.setSecurityMode(MessageSecurityMode.SignAndEncrypt)) | ||
); | ||
|
||
EndpointConfiguration.Builder discoveryBuilder = builder.copy() | ||
.setPath("/milo/discovery") | ||
.setSecurityPolicy(SecurityPolicy.None) | ||
.setSecurityMode(MessageSecurityMode.None); | ||
|
||
endpointConfigurations.add(buildTcpEndpoint(discoveryBuilder)); | ||
} | ||
} | ||
|
||
return endpointConfigurations; | ||
} | ||
|
||
private static EndpointConfiguration buildTcpEndpoint(EndpointConfiguration.Builder base) { | ||
return base.copy() | ||
.setTransportProfile(TransportProfile.TCP_UASC_UABINARY) | ||
.setBindPort(TCP_BIND_PORT) | ||
.build(); | ||
} | ||
|
||
public OpcUaServer getServer() { | ||
return server; | ||
} | ||
|
||
public CompletableFuture<OpcUaServer> startup() { | ||
return server.startup(); | ||
} | ||
|
||
public CompletableFuture<OpcUaServer> shutdown() { | ||
exampleNamespace.shutdown(); | ||
|
||
return server.shutdown(); | ||
} | ||
|
||
} |