This is an automated email from the ASF dual-hosted git repository. davsclaus pushed a commit to branch CAMEL-27709-milo-server-certificate-validator in repository https://gitbox.apache.org/repos/asf/camel.git
commit 8aa389c5c6c45f523d57b7259203fd6d7e47d9b8 Author: Claus Ibsen <[email protected]> AuthorDate: Fri Nov 27 17:59:14 2026 +0100 CAMEL-27709: camel-milo - the certificateValidator option of milo-server fails the server start Since the Eclipse Milo 1.0 migration, a custom certificateValidator made the server fail to start with a NullPointerException in DefaultCertificateManager, and with defaultCertificateValidator also set the custom validator was ignored. With Milo 1.x the server validates a client certificate with the validator of the certificate group of the server certificate. When certificateValidator is set, the certificate manager of the server is now wrapped so that its certificate groups use the custom validator. Without a certificate manager, or with both certificateValidator and defaultCertificateValidator set, the server fails to start with a clear message. Also re-enable MonitorItemMultiConnectionsCertTest (the clients that cannot connect now report their node without communication, and it uses a TempDir), give certificateValidator a description, and document the system property org.apache.camel.milo.server.default.enableAnonymous. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Claus Ibsen <[email protected]> --- .../camel/catalog/components/milo-server.json | 4 +- .../camel/catalog/docs/milo-server-component.adoc | 32 ++++ .../camel/component/milo/server/milo-server.json | 4 +- .../src/main/docs/milo-server-component.adoc | 32 ++++ .../component/milo/server/MiloServerComponent.java | 78 ++++++--- .../CertificateValidatorCertificateManager.java | 156 +++++++++++++++++ .../milo/MonitorItemMultiConnectionsCertTest.java | 22 +-- .../milo/ServerClientCertificateValidatorTest.java | 152 +++++++++++++++++ .../server/MiloServerCertificateValidatorTest.java | 187 +++++++++++++++++++++ .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 11 ++ .../dsl/MiloServerComponentBuilderFactory.java | 11 +- 11 files changed, 653 insertions(+), 36 deletions(-) diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/milo-server.json b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/milo-server.json index 787eb33ee111..0b75044003ae 100644 --- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/milo-server.json +++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/milo-server.json @@ -36,8 +36,8 @@ "lazyStartProducer": { "index": 9, "kind": "property", "displayName": "Lazy Start Producer", "group": "producer", "label": "producer", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail [...] "autowiredEnabled": { "index": 10, "kind": "property", "displayName": "Autowired Enabled", "group": "advanced", "label": "advanced", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": true, "description": "Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching [...] "certificate": { "index": 11, "kind": "property", "displayName": "Certificate", "group": "security", "label": "security", "required": false, "type": "object", "javaType": "java.security.cert.X509Certificate", "deprecated": false, "autowired": false, "secret": false, "description": "The certificate of the server, as a java.security.cert.X509Certificate, which the endpoints of the server announce." }, - "certificateManager": { "index": 12, "kind": "property", "displayName": "Certificate Manager", "group": "security", "label": "security", "required": false, "type": "object", "javaType": "org.eclipse.milo.opcua.stack.core.security.CertificateManager", "deprecated": false, "autowired": false, "secret": false, "description": "To use a custom org.eclipse.milo.opcua.stack.core.security.CertificateManager that holds the certificate and the key pair of the server. Not used when certificateV [...] - "certificateValidator": { "index": 13, "kind": "property", "displayName": "Certificate Validator", "group": "security", "label": "security", "required": false, "type": "object", "javaType": "org.eclipse.milo.opcua.stack.core.security.CertificateValidator", "deprecated": false, "autowired": false, "secret": false, "description": "Validator for client certificates" }, + "certificateManager": { "index": 12, "kind": "property", "displayName": "Certificate Manager", "group": "security", "label": "security", "required": false, "type": "object", "javaType": "org.eclipse.milo.opcua.stack.core.security.CertificateManager", "deprecated": false, "autowired": false, "secret": false, "description": "To use a custom org.eclipse.milo.opcua.stack.core.security.CertificateManager that holds the certificate and the key pair of the server. Not used when defaultCerti [...] + "certificateValidator": { "index": 13, "kind": "property", "displayName": "Certificate Validator", "group": "security", "label": "security", "required": false, "type": "object", "javaType": "org.eclipse.milo.opcua.stack.core.security.CertificateValidator", "deprecated": false, "autowired": false, "secret": false, "description": "To use a custom org.eclipse.milo.opcua.stack.core.security.CertificateValidator that validates the certificates of the OPC UA clients, instead of the validat [...] "defaultCertificateValidator": { "index": 14, "kind": "property", "displayName": "Default Certificate Validator", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "description": "The directory of a file based trust list for the certificates of the OPC UA clients, in the layout used by Eclipse Milo: trusted certificates in trusted\/certs, their CRLs in trusted\/crl, [...] "enableAnonymousAuthentication": { "index": 15, "kind": "property", "displayName": "Enable Anonymous Authentication", "group": "security", "label": "security", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Whether the endpoints of the server offer the Anonymous user token policy, for clients that connect without a user name." }, "securityPolicies": { "index": 16, "kind": "property", "displayName": "Security Policies", "group": "security", "label": "security", "required": false, "type": "object", "javaType": "java.util.Set<org.eclipse.milo.opcua.stack.core.security.SecurityPolicy>", "deprecated": false, "autowired": false, "secret": false, "description": "The security policies of the endpoints of the server, as a Set of org.eclipse.milo.opcua.stack.core.security.SecurityPolicy. Only None and Basic256Sha256 cr [...] diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/milo-server-component.adoc b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/milo-server-component.adoc index da00d090509f..c43aa08dce7a 100644 --- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/milo-server-component.adoc +++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/milo-server-component.adoc @@ -102,6 +102,38 @@ When configuring security for the OPC UA server, the following considerations ap * The component supports both certificate-based and username/password authentication * Security policies can be configured using the `securityPolicies` or `securityPoliciesById` options +==== Validating the certificates of the clients + +On an endpoint with a security policy other than `None`, the server validates the certificate of each client. +Use one of these options: + +* `defaultCertificateValidator`: the directory of a file based trust list. The server accepts the client + certificates that are trusted in that directory (or issued by a trusted CA), and puts the rejected ones in + `rejected/certs`. +* `certificateValidator`: a custom `CertificateValidator`, for example from the registry + (`#myCertificateValidator`). It needs `certificateManager`, which holds the certificate and the key pair of the server. The + server validates the client certificates with this validator instead of the validators of the certificate groups + of `certificateManager`. + +The two options cannot be used together: when both are set, the server fails to start. + +For example, with a certificate manager, the server certificate and a validator bound in the registry: + +[source,properties] +---- +camel.component.milo-server.certificate-manager = #myCertificateManager +camel.component.milo-server.certificate = #myServerCertificate +camel.component.milo-server.certificate-validator = #myCertificateValidator +camel.component.milo-server.security-policies-by-id = Basic256Sha256 +---- + +==== Anonymous clients for development + +When neither `userAuthenticationCredentials` nor `enableAnonymousAuthentication` is set, the JVM system property +`org.apache.camel.milo.server.default.enableAnonymous=true` makes the endpoints of the server offer the Anonymous +user token policy (next to UserName and X509), and lets clients connect without a user name. +The property is off by default. It is meant for development and testing only: do not set it in production. + ==== Milo 1.0.5 Migration Notes With Milo 1.0.5, several security-related API changes were introduced: diff --git a/components/camel-milo/src/generated/resources/META-INF/org/apache/camel/component/milo/server/milo-server.json b/components/camel-milo/src/generated/resources/META-INF/org/apache/camel/component/milo/server/milo-server.json index 787eb33ee111..0b75044003ae 100644 --- a/components/camel-milo/src/generated/resources/META-INF/org/apache/camel/component/milo/server/milo-server.json +++ b/components/camel-milo/src/generated/resources/META-INF/org/apache/camel/component/milo/server/milo-server.json @@ -36,8 +36,8 @@ "lazyStartProducer": { "index": 9, "kind": "property", "displayName": "Lazy Start Producer", "group": "producer", "label": "producer", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail [...] "autowiredEnabled": { "index": 10, "kind": "property", "displayName": "Autowired Enabled", "group": "advanced", "label": "advanced", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": true, "description": "Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching [...] "certificate": { "index": 11, "kind": "property", "displayName": "Certificate", "group": "security", "label": "security", "required": false, "type": "object", "javaType": "java.security.cert.X509Certificate", "deprecated": false, "autowired": false, "secret": false, "description": "The certificate of the server, as a java.security.cert.X509Certificate, which the endpoints of the server announce." }, - "certificateManager": { "index": 12, "kind": "property", "displayName": "Certificate Manager", "group": "security", "label": "security", "required": false, "type": "object", "javaType": "org.eclipse.milo.opcua.stack.core.security.CertificateManager", "deprecated": false, "autowired": false, "secret": false, "description": "To use a custom org.eclipse.milo.opcua.stack.core.security.CertificateManager that holds the certificate and the key pair of the server. Not used when certificateV [...] - "certificateValidator": { "index": 13, "kind": "property", "displayName": "Certificate Validator", "group": "security", "label": "security", "required": false, "type": "object", "javaType": "org.eclipse.milo.opcua.stack.core.security.CertificateValidator", "deprecated": false, "autowired": false, "secret": false, "description": "Validator for client certificates" }, + "certificateManager": { "index": 12, "kind": "property", "displayName": "Certificate Manager", "group": "security", "label": "security", "required": false, "type": "object", "javaType": "org.eclipse.milo.opcua.stack.core.security.CertificateManager", "deprecated": false, "autowired": false, "secret": false, "description": "To use a custom org.eclipse.milo.opcua.stack.core.security.CertificateManager that holds the certificate and the key pair of the server. Not used when defaultCerti [...] + "certificateValidator": { "index": 13, "kind": "property", "displayName": "Certificate Validator", "group": "security", "label": "security", "required": false, "type": "object", "javaType": "org.eclipse.milo.opcua.stack.core.security.CertificateValidator", "deprecated": false, "autowired": false, "secret": false, "description": "To use a custom org.eclipse.milo.opcua.stack.core.security.CertificateValidator that validates the certificates of the OPC UA clients, instead of the validat [...] "defaultCertificateValidator": { "index": 14, "kind": "property", "displayName": "Default Certificate Validator", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "description": "The directory of a file based trust list for the certificates of the OPC UA clients, in the layout used by Eclipse Milo: trusted certificates in trusted\/certs, their CRLs in trusted\/crl, [...] "enableAnonymousAuthentication": { "index": 15, "kind": "property", "displayName": "Enable Anonymous Authentication", "group": "security", "label": "security", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Whether the endpoints of the server offer the Anonymous user token policy, for clients that connect without a user name." }, "securityPolicies": { "index": 16, "kind": "property", "displayName": "Security Policies", "group": "security", "label": "security", "required": false, "type": "object", "javaType": "java.util.Set<org.eclipse.milo.opcua.stack.core.security.SecurityPolicy>", "deprecated": false, "autowired": false, "secret": false, "description": "The security policies of the endpoints of the server, as a Set of org.eclipse.milo.opcua.stack.core.security.SecurityPolicy. Only None and Basic256Sha256 cr [...] diff --git a/components/camel-milo/src/main/docs/milo-server-component.adoc b/components/camel-milo/src/main/docs/milo-server-component.adoc index da00d090509f..c43aa08dce7a 100644 --- a/components/camel-milo/src/main/docs/milo-server-component.adoc +++ b/components/camel-milo/src/main/docs/milo-server-component.adoc @@ -102,6 +102,38 @@ When configuring security for the OPC UA server, the following considerations ap * The component supports both certificate-based and username/password authentication * Security policies can be configured using the `securityPolicies` or `securityPoliciesById` options +==== Validating the certificates of the clients + +On an endpoint with a security policy other than `None`, the server validates the certificate of each client. +Use one of these options: + +* `defaultCertificateValidator`: the directory of a file based trust list. The server accepts the client + certificates that are trusted in that directory (or issued by a trusted CA), and puts the rejected ones in + `rejected/certs`. +* `certificateValidator`: a custom `CertificateValidator`, for example from the registry + (`#myCertificateValidator`). It needs `certificateManager`, which holds the certificate and the key pair of the server. The + server validates the client certificates with this validator instead of the validators of the certificate groups + of `certificateManager`. + +The two options cannot be used together: when both are set, the server fails to start. + +For example, with a certificate manager, the server certificate and a validator bound in the registry: + +[source,properties] +---- +camel.component.milo-server.certificate-manager = #myCertificateManager +camel.component.milo-server.certificate = #myServerCertificate +camel.component.milo-server.certificate-validator = #myCertificateValidator +camel.component.milo-server.security-policies-by-id = Basic256Sha256 +---- + +==== Anonymous clients for development + +When neither `userAuthenticationCredentials` nor `enableAnonymousAuthentication` is set, the JVM system property +`org.apache.camel.milo.server.default.enableAnonymous=true` makes the endpoints of the server offer the Anonymous +user token policy (next to UserName and X509), and lets clients connect without a user name. +The property is off by default. It is meant for development and testing only: do not set it in production. + ==== Milo 1.0.5 Migration Notes With Milo 1.0.5, several security-related API changes were introduced: diff --git a/components/camel-milo/src/main/java/org/apache/camel/component/milo/server/MiloServerComponent.java b/components/camel-milo/src/main/java/org/apache/camel/component/milo/server/MiloServerComponent.java index 25032c4f042d..0949e0b13389 100644 --- a/components/camel-milo/src/main/java/org/apache/camel/component/milo/server/MiloServerComponent.java +++ b/components/camel-milo/src/main/java/org/apache/camel/component/milo/server/MiloServerComponent.java @@ -41,6 +41,7 @@ import org.apache.camel.Endpoint; import org.apache.camel.RuntimeCamelException; import org.apache.camel.component.milo.KeyStoreLoader; import org.apache.camel.component.milo.server.internal.CamelNamespace; +import org.apache.camel.component.milo.server.internal.CertificateValidatorCertificateManager; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.annotations.Component; import org.apache.camel.support.DefaultComponent; @@ -114,8 +115,9 @@ public class MiloServerComponent extends DefaultComponent { private Boolean enableAnonymousAuthentication; @Metadata(label = "security", description = "To use a custom org.eclipse.milo.opcua.stack.core.security.CertificateManager that holds the" - + " certificate and the key pair of the server. Not used when certificateValidator or" - + " defaultCertificateValidator is set.") + + " certificate and the key pair of the server. Not used when defaultCertificateValidator is" + + " set. When certificateValidator is set, the certificate groups of this certificate manager" + + " validate the certificates of the clients with that validator.") private CertificateManager certificateManager; @Metadata(label = "security", description = "A comma-separated list of the security policies of the endpoints of the server, as URIs or as" @@ -145,7 +147,11 @@ public class MiloServerComponent extends DefaultComponent { + " Rejected certificates are put in rejected/certs. The directories are created if they do not" + " exist.") private String defaultCertificateValidator; - @Metadata(label = "security") + @Metadata(label = "security", + description = "To use a custom org.eclipse.milo.opcua.stack.core.security.CertificateValidator that validates" + + " the certificates of the OPC UA clients, instead of the validators of the certificate groups" + + " of certificateManager. Requires certificateManager, which holds the certificate of the" + + " server. Cannot be used together with defaultCertificateValidator.") private CertificateValidator certificateValidator; @Metadata(label = "security", description = "The certificate of the server, as a java.security.cert.X509Certificate, which the endpoints of" @@ -158,6 +164,8 @@ public class MiloServerComponent extends DefaultComponent { // FIXME - migration to CertificateGroup @Metadata(label = "security") private CertificateGroup certificateGroup; + // the validator of the file based trust list of defaultCertificateValidator + private CertificateValidator trustListCertificateValidator; public MiloServerComponent() { this.opcServerConfig = null; @@ -202,6 +210,13 @@ public class MiloServerComponent extends DefaultComponent { // this.certificateGroup = createCertificateGroup(); + if (certificateValidator != null && defaultCertificateValidator != null) { + throw new IllegalArgumentException( + "The options certificateValidator and defaultCertificateValidator of the milo-server component cannot" + + " be used together. Use certificateValidator with certificateManager," + + " or defaultCertificateValidator alone."); + } + OpcUaServerConfigBuilder serverConfig = this.opcServerConfig != null ? this.opcServerConfig : createDefaultConfiguration(); @@ -233,26 +248,48 @@ public class MiloServerComponent extends DefaultComponent { serverConfig.setEndpoints(createEndpointConfigs(null, securityPolicies)); } - if (certificateValidator != null) { - LOG.debug("Using validator: {}", certificateValidator); - if (certificateValidator instanceof Closeable closeable) { - runOnStop(() -> { - try { - LOG.debug("Closing: {}", certificateValidator); - closeable.close(); - } catch (IOException e) { - LOG.debug("Failed to close. This exception is ignored.", e); - } - }); - } - // serverConfig.setCertificateValidator(certificateValidator); - // // FIXME - moved to certificateManager + if (trustListCertificateValidator != null) { + // the file based trust list of defaultCertificateValidator + LOG.debug("Using validator: {}", trustListCertificateValidator); + closeOnStop(trustListCertificateValidator); serverConfig.setCertificateManager( new DefaultCertificateManager(this.certificateQuarantine, this.certificateGroup)); } // build final configuration - return serverConfig.build(); + final OpcUaServerConfig config = serverConfig.build(); + + if (certificateValidator == null) { + return config; + } + + // with Milo 1.x, the server validates the certificate of a client with the validator of the certificate + // group of the server certificate, so the certificate groups of the certificate manager use the custom + // validator + final CertificateManager baseCertificateManager = config.getCertificateManager(); + if (baseCertificateManager == null) { + throw new IllegalArgumentException( + "The option certificateValidator of the milo-server component requires the option certificateManager," + + " which holds the certificate of the server."); + } + LOG.debug("Using validator: {}", certificateValidator); + closeOnStop(certificateValidator); + final CertificateManager validatingCertificateManager + = new CertificateValidatorCertificateManager(baseCertificateManager, certificateValidator); + return OpcUaServerConfig.copy(config, builder -> builder.setCertificateManager(validatingCertificateManager)); + } + + private void closeOnStop(final CertificateValidator validator) { + if (validator instanceof Closeable closeable) { + runOnStop(() -> { + try { + LOG.debug("Closing: {}", validator); + closeable.close(); + } catch (IOException e) { + LOG.debug("Failed to close. This exception is ignored.", e); + } + }); + } } private OpcUaServerConfigBuilder createDefaultConfiguration() { @@ -625,7 +662,8 @@ public class MiloServerComponent extends DefaultComponent { this.certificateQuarantine = this.createCertificateQuarantine(certificateConfigurationPath); - this.certificateValidator = new DefaultServerCertificateValidator(trustListManager, certificateQuarantine); + this.trustListCertificateValidator + = new DefaultServerCertificateValidator(trustListManager, certificateQuarantine); this.certificateGroup = DefaultApplicationGroup.createAndInitialize( trustListManager, @@ -636,7 +674,7 @@ public class MiloServerComponent extends DefaultComponent { return new X509Certificate[] { certificate }; } }, - certificateValidator); + trustListCertificateValidator); } catch (Exception e) { throw new RuntimeCamelException(e); diff --git a/components/camel-milo/src/main/java/org/apache/camel/component/milo/server/internal/CertificateValidatorCertificateManager.java b/components/camel-milo/src/main/java/org/apache/camel/component/milo/server/internal/CertificateValidatorCertificateManager.java new file mode 100644 index 000000000000..b54d29d827e5 --- /dev/null +++ b/components/camel-milo/src/main/java/org/apache/camel/component/milo/server/internal/CertificateValidatorCertificateManager.java @@ -0,0 +1,156 @@ +/* + * 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.apache.camel.component.milo.server.internal; + +import java.security.KeyPair; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +import org.eclipse.milo.opcua.stack.core.security.CertificateFactory; +import org.eclipse.milo.opcua.stack.core.security.CertificateGroup; +import org.eclipse.milo.opcua.stack.core.security.CertificateManager; +import org.eclipse.milo.opcua.stack.core.security.CertificateQuarantine; +import org.eclipse.milo.opcua.stack.core.security.CertificateValidator; +import org.eclipse.milo.opcua.stack.core.security.TrustListManager; +import org.eclipse.milo.opcua.stack.core.types.builtin.ByteString; +import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId; + +/** + * A {@link CertificateManager} that delegates to another certificate manager, but whose certificate groups validate the + * certificates of the clients with the given {@link CertificateValidator}. + * <p> + * With Eclipse Milo 1.x, the server validates the certificate of a client with the validator of the certificate group + * of the server certificate, see {@link CertificateGroup#getCertificateValidator()}. + */ +public final class CertificateValidatorCertificateManager implements CertificateManager { + + private final CertificateManager delegate; + private final CertificateValidator certificateValidator; + + public CertificateValidatorCertificateManager(final CertificateManager delegate, + final CertificateValidator certificateValidator) { + this.delegate = Objects.requireNonNull(delegate); + this.certificateValidator = Objects.requireNonNull(certificateValidator); + } + + public CertificateManager getDelegate() { + return delegate; + } + + public CertificateValidator getCertificateValidator() { + return certificateValidator; + } + + @Override + public Optional<KeyPair> getKeyPair(final ByteString thumbprint) { + return delegate.getKeyPair(thumbprint); + } + + @Override + public Optional<X509Certificate> getCertificate(final ByteString thumbprint) { + return delegate.getCertificate(thumbprint); + } + + @Override + public Optional<X509Certificate[]> getCertificateChain(final ByteString thumbprint) { + return delegate.getCertificateChain(thumbprint); + } + + @Override + public Optional<CertificateGroup> getCertificateGroup(final ByteString thumbprint) { + return delegate.getCertificateGroup(thumbprint).map(this::wrap); + } + + @Override + public Optional<CertificateGroup> getCertificateGroup(final NodeId certificateGroupId) { + return delegate.getCertificateGroup(certificateGroupId).map(this::wrap); + } + + @Override + public List<CertificateGroup> getCertificateGroups() { + return delegate.getCertificateGroups().stream().map(this::wrap).toList(); + } + + @Override + public CertificateQuarantine getCertificateQuarantine() { + return delegate.getCertificateQuarantine(); + } + + private CertificateGroup wrap(final CertificateGroup group) { + return new ValidatorCertificateGroup(group, certificateValidator); + } + + private static final class ValidatorCertificateGroup implements CertificateGroup { + + private final CertificateGroup delegate; + private final CertificateValidator certificateValidator; + + private ValidatorCertificateGroup(final CertificateGroup delegate, final CertificateValidator certificateValidator) { + this.delegate = delegate; + this.certificateValidator = certificateValidator; + } + + @Override + public NodeId getCertificateGroupId() { + return delegate.getCertificateGroupId(); + } + + @Override + public List<NodeId> getSupportedCertificateTypeIds() { + return delegate.getSupportedCertificateTypeIds(); + } + + @Override + public TrustListManager getTrustListManager() { + return delegate.getTrustListManager(); + } + + @Override + public List<Entry> getCertificateEntries() { + return delegate.getCertificateEntries(); + } + + @Override + public Optional<KeyPair> getKeyPair(final NodeId certificateTypeId) { + return delegate.getKeyPair(certificateTypeId); + } + + @Override + public Optional<X509Certificate[]> getCertificateChain(final NodeId certificateTypeId) { + return delegate.getCertificateChain(certificateTypeId); + } + + @Override + public void updateCertificate( + final NodeId certificateTypeId, final KeyPair keyPair, final X509Certificate[] certificateChain) + throws Exception { + delegate.updateCertificate(certificateTypeId, keyPair, certificateChain); + } + + @Override + public CertificateFactory getCertificateFactory() { + return delegate.getCertificateFactory(); + } + + @Override + public CertificateValidator getCertificateValidator() { + return certificateValidator; + } + } +} diff --git a/components/camel-milo/src/test/java/org/apache/camel/component/milo/MonitorItemMultiConnectionsCertTest.java b/components/camel-milo/src/test/java/org/apache/camel/component/milo/MonitorItemMultiConnectionsCertTest.java index 66add5b219a4..6d2931bef0e1 100644 --- a/components/camel-milo/src/test/java/org/apache/camel/component/milo/MonitorItemMultiConnectionsCertTest.java +++ b/components/camel-milo/src/test/java/org/apache/camel/component/milo/MonitorItemMultiConnectionsCertTest.java @@ -30,9 +30,9 @@ import org.apache.camel.component.milo.server.MiloServerComponent; import org.apache.camel.component.mock.MockEndpoint; import org.eclipse.milo.opcua.stack.core.security.SecurityPolicy; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; +import org.junit.jupiter.api.io.TempDir; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,7 +41,6 @@ import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; /** * Testing monitoring items over multiple connections */ -@Disabled("due to Milo 1.0.5 API migration - certificate-based authentication needs further investigation") public class MonitorItemMultiConnectionsCertTest extends AbstractMiloServerTest { private static final String DIRECT_START_1 = "direct:start1"; @@ -85,6 +84,9 @@ public class MonitorItemMultiConnectionsCertTest extends AbstractMiloServerTest @Produce(DIRECT_START_1) protected ProducerTemplate producer1; + @TempDir + Path baseDir; + @BeforeEach public void setup(TestInfo testInfo) { final var displayName = testInfo.getDisplayName(); @@ -97,7 +99,6 @@ public class MonitorItemMultiConnectionsCertTest extends AbstractMiloServerTest protected void configureMiloServer(final MiloServerComponent server) throws Exception { super.configureMiloServer(server); - final Path baseDir = Paths.get("target/testing/cert/default"); final Path trusted = baseDir.resolve("trusted/certs"); Files.createDirectories(trusted); @@ -129,15 +130,16 @@ public class MonitorItemMultiConnectionsCertTest extends AbstractMiloServerTest // item 1 ... only this one receives this.test1Endpoint.setExpectedCount(1); - this.test1Endpoint.setSleepForEmptyTest(5_000); + testBody(this.test1Endpoint.message(0), assertGoodValue("Foo")); - // item 2 - this.test2Endpoint.setExpectedCount(0); - this.test2Endpoint.setSleepForEmptyTest(5_000); + // item 2 and 3 cannot connect: they only report their node without communication + this.test2Endpoint.setExpectedCount(1); + testBody(this.test2Endpoint.message(0), assertNoCommunication()); + this.test2Endpoint.setAssertPeriod(5_000); - // item 3 - this.test3Endpoint.setExpectedCount(0); - this.test3Endpoint.setSleepForEmptyTest(5_000); + this.test3Endpoint.setExpectedCount(1); + testBody(this.test3Endpoint.message(0), assertNoCommunication()); + this.test3Endpoint.setAssertPeriod(5_000); // set server value this.producer1.sendBody("Foo"); diff --git a/components/camel-milo/src/test/java/org/apache/camel/component/milo/ServerClientCertificateValidatorTest.java b/components/camel-milo/src/test/java/org/apache/camel/component/milo/ServerClientCertificateValidatorTest.java new file mode 100644 index 000000000000..6b7ee89f26d1 --- /dev/null +++ b/components/camel-milo/src/test/java/org/apache/camel/component/milo/ServerClientCertificateValidatorTest.java @@ -0,0 +1,152 @@ +/* + * 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.apache.camel.component.milo; + +import java.security.cert.X509Certificate; +import java.util.EnumSet; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.apache.camel.EndpointInject; +import org.apache.camel.Produce; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.RoutesBuilder; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.milo.call.TestCertificateFactory; +import org.apache.camel.component.milo.server.MiloServerComponent; +import org.apache.camel.component.mock.MockEndpoint; +import org.eclipse.milo.opcua.stack.core.StatusCodes; +import org.eclipse.milo.opcua.stack.core.UaException; +import org.eclipse.milo.opcua.stack.core.security.CertificateValidator; +import org.eclipse.milo.opcua.stack.core.security.DefaultApplicationGroup; +import org.eclipse.milo.opcua.stack.core.security.DefaultCertificateManager; +import org.eclipse.milo.opcua.stack.core.security.MemoryCertificateQuarantine; +import org.eclipse.milo.opcua.stack.core.security.MemoryCertificateStore; +import org.eclipse.milo.opcua.stack.core.security.MemoryTrustListManager; +import org.eclipse.milo.opcua.stack.core.security.SecurityPolicy; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The milo-server component validates the certificates of the clients with its certificateValidator option. + */ +class ServerClientCertificateValidatorTest extends AbstractMiloServerTest { + + private static final String DIRECT_START = "direct:start"; + + private static final String MILO_SERVER_ITEM = "milo-server:myitem1"; + + // the client trusts the server: the validation of the client certificate by the server is under test here + private static final String MILO_CLIENT = "milo-client:opc.tcp://foo:bar@localhost:@@port@@?node=" + + NodeIds.nodeValue(MiloServerComponent.DEFAULT_NAMESPACE_URI, "myitem1") + + "&keyStoreUrl=file:src/test/resources/keystore&keyStorePassword=testtest" + + "&keyPassword=test&keyAlias=test&allowedSecurityPolicies=Basic256Sha256" + + "&trustAllCertificates=true" + + "&discoveryEndpointSuffix=/discovery&overrideHost=true"; + + private final SwitchableCertificateValidator certificateValidator = new SwitchableCertificateValidator(); + + @EndpointInject("mock:accepted") + MockEndpoint acceptedEndpoint; + + @EndpointInject("mock:rejected") + MockEndpoint rejectedEndpoint; + + @Produce(DIRECT_START) + ProducerTemplate producer; + + @Override + protected void configureMiloServer(final MiloServerComponent server) throws Exception { + super.configureMiloServer(server); + + // the certificate group of the server accepts any client, so only the custom validator can reject one + final DefaultApplicationGroup certificateGroup = DefaultApplicationGroup.createAndInitialize( + new MemoryTrustListManager(), new MemoryCertificateStore(), new TestCertificateFactory(), + new CertificateValidator.InsecureCertificateValidator()); + + server.setApplicationUri("urn:eclipse:milo:test"); + server.setCertificateManager(new DefaultCertificateManager(new MemoryCertificateQuarantine(), certificateGroup)); + server.setCertificate(certificateGroup.getCertificateEntries().get(0).certificateChain[0]); + server.setCertificateValidator(this.certificateValidator); + server.setSecurityPolicies(EnumSet.of(SecurityPolicy.Basic256Sha256)); + server.setUsernameSecurityPolicyUri(SecurityPolicy.Basic256Sha256); + } + + @Override + protected RoutesBuilder createRouteBuilder() { + return new RouteBuilder() { + @Override + public void configure() { + from(DIRECT_START).to(MILO_SERVER_ITEM); + + // the test starts the consumers, each with its own connection + from(resolve(MILO_CLIENT + "&clientId=accepted")).routeId("accepted").autoStartup(false) + .to("mock:accepted"); + from(resolve(MILO_CLIENT + "&clientId=rejected")).routeId("rejected").autoStartup(false) + .to("mock:rejected"); + } + }; + } + + @Test + void serverValidatesClientCertificatesWithTheCustomValidator() throws Exception { + final X509Certificate clientCertificate = loadDefaultTestKey().getCertificate(); + + // the value is written before the consumers start, so it is the first notification of a client that connects + this.producer.sendBody("Foo"); + + // the validator accepts the client + this.acceptedEndpoint.setMinimumExpectedMessageCount(1); + testBody(this.acceptedEndpoint.message(0), assertGoodValue("Foo")); + context.getRouteController().startRoute("accepted"); + this.acceptedEndpoint.assertIsSatisfied(); + + assertFalse(this.certificateValidator.validated.isEmpty(), "The custom certificate validator was not used"); + assertEquals(clientCertificate, this.certificateValidator.validated.get(0).get(0)); + + // the validator rejects the client: it cannot connect, and reports its node without communication + this.certificateValidator.accept.set(false); + final int validationsBefore = this.certificateValidator.validated.size(); + this.rejectedEndpoint.setExpectedCount(1); + testBody(this.rejectedEndpoint.message(0), assertNoCommunication()); + context.getRouteController().startRoute("rejected"); + this.rejectedEndpoint.assertIsSatisfied(); + + assertTrue(this.certificateValidator.validated.size() > validationsBefore, + "The custom certificate validator was not used for the rejected client"); + } + + private static final class SwitchableCertificateValidator implements CertificateValidator { + + private final AtomicBoolean accept = new AtomicBoolean(true); + private final List<List<X509Certificate>> validated = new CopyOnWriteArrayList<>(); + + @Override + public void validateCertificateChain( + final List<X509Certificate> certificateChain, final String applicationUri, final String[] validHostNames) + throws UaException { + this.validated.add(List.copyOf(certificateChain)); + if (!this.accept.get()) { + throw new UaException(StatusCodes.Bad_SecurityChecksFailed); + } + } + } +} diff --git a/components/camel-milo/src/test/java/org/apache/camel/component/milo/server/MiloServerCertificateValidatorTest.java b/components/camel-milo/src/test/java/org/apache/camel/component/milo/server/MiloServerCertificateValidatorTest.java new file mode 100644 index 000000000000..a1f1be7e727d --- /dev/null +++ b/components/camel-milo/src/test/java/org/apache/camel/component/milo/server/MiloServerCertificateValidatorTest.java @@ -0,0 +1,187 @@ +/* + * 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.apache.camel.component.milo.server; + +import java.nio.file.Path; +import java.security.cert.X509Certificate; +import java.util.EnumSet; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.camel.CamelContext; +import org.apache.camel.component.milo.call.TestCertificateFactory; +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.test.AvailablePortFinder; +import org.eclipse.milo.opcua.stack.core.StatusCodes; +import org.eclipse.milo.opcua.stack.core.UaException; +import org.eclipse.milo.opcua.stack.core.security.CertificateGroup; +import org.eclipse.milo.opcua.stack.core.security.CertificateManager; +import org.eclipse.milo.opcua.stack.core.security.CertificateValidator; +import org.eclipse.milo.opcua.stack.core.security.DefaultApplicationGroup; +import org.eclipse.milo.opcua.stack.core.security.DefaultCertificateManager; +import org.eclipse.milo.opcua.stack.core.security.MemoryCertificateQuarantine; +import org.eclipse.milo.opcua.stack.core.security.MemoryCertificateStore; +import org.eclipse.milo.opcua.stack.core.security.MemoryTrustListManager; +import org.eclipse.milo.opcua.stack.core.security.SecurityPolicy; +import org.eclipse.milo.opcua.stack.core.util.CertificateUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * The certificateValidator option of the milo-server component: the server starts with it, and the server validates the + * certificates of the clients with it. + */ +class MiloServerCertificateValidatorTest { + + @RegisterExtension + AvailablePortFinder.Port port = AvailablePortFinder.find(); + + @TempDir + Path trustList; + + private final AtomicInteger validations = new AtomicInteger(); + + private final CertificateValidator denyAll = new CertificateValidator() { + @Override + public void validateCertificateChain( + List<X509Certificate> certificateChain, String applicationUri, String[] validHostNames) + throws UaException { + validations.incrementAndGet(); + throw new UaException(StatusCodes.Bad_SecurityChecksFailed); + } + }; + + private CamelContext context; + + @AfterEach + void stopContext() { + if (context != null) { + context.stop(); + } + } + + @Test + void serverStartsWithCustomValidator() throws Exception { + final DefaultApplicationGroup certificateGroup = createCertificateGroup(); + final X509Certificate serverCertificate = certificateGroup.getCertificateEntries().get(0).certificateChain[0]; + + final MiloServerComponent server = createServer(); + server.setCertificateManager(new DefaultCertificateManager(new MemoryCertificateQuarantine(), certificateGroup)); + server.setCertificate(serverCertificate); + server.setCertificateValidator(denyAll); + + startServer(server); + + assertNotNull(server.getServer(), "The OPC UA server should have been started"); + + // the server looks the certificate group up by the thumbprint of its own certificate, and validates the + // client certificate with the validator of that group + final CertificateManager certificateManager = server.getServer().getConfig().getCertificateManager(); + final CertificateGroup group = certificateManager + .getCertificateGroup(CertificateUtil.thumbprint(serverCertificate)) + .orElseThrow(); + final UaException e = assertThrows(UaException.class, + () -> group.getCertificateValidator().validateCertificateChain( + List.of(serverCertificate), null, null)); + assertEquals(StatusCodes.Bad_SecurityChecksFailed, e.getStatusCode().getValue()); + assertEquals(1, validations.get(), "The custom certificate validator should have been called"); + + // the key pair and certificate of the server still come from the certificate manager + assertTrue(certificateManager.getKeyPair(CertificateUtil.thumbprint(serverCertificate)).isPresent()); + assertFalse(certificateManager.getCertificateGroups().isEmpty()); + for (CertificateGroup each : certificateManager.getCertificateGroups()) { + assertEquals(denyAll, each.getCertificateValidator()); + } + } + + @Test + void customValidatorRequiresCertificateManager() { + final MiloServerComponent server = createServer(); + // the security policy None needs no certificate of the server + server.setSecurityPolicies(EnumSet.of(SecurityPolicy.None)); + server.setCertificateValidator(denyAll); + + assertStartFails(server, "requires the option certificateManager"); + } + + @Test + void customAndDefaultValidatorCannotBeUsedTogether() throws Exception { + final MiloServerComponent server = createServerWithCertificate(); + server.setCertificateValidator(denyAll); + server.setDefaultCertificateValidator(trustList.toString()); + + assertStartFails(server, "cannot be used together"); + } + + @Test + void defaultAndCustomValidatorCannotBeUsedTogether() throws Exception { + final MiloServerComponent server = createServerWithCertificate(); + server.setDefaultCertificateValidator(trustList.toString()); + server.setCertificateValidator(denyAll); + + assertStartFails(server, "cannot be used together"); + } + + private MiloServerComponent createServer() { + final MiloServerComponent server = new MiloServerComponent(); + server.setBindAddresses("localhost"); + server.setPort(port.getPort()); + server.setSecurityPolicies(EnumSet.of(SecurityPolicy.Basic256Sha256)); + return server; + } + + private MiloServerComponent createServerWithCertificate() throws Exception { + final DefaultApplicationGroup certificateGroup = createCertificateGroup(); + final MiloServerComponent server = createServer(); + server.setCertificateManager(new DefaultCertificateManager(new MemoryCertificateQuarantine(), certificateGroup)); + server.setCertificate(certificateGroup.getCertificateEntries().get(0).certificateChain[0]); + return server; + } + + private void startServer(final MiloServerComponent server) { + context = new DefaultCamelContext(); + context.addComponent("milo-server", server); + context.start(); + server.start(); + } + + private void assertStartFails(final MiloServerComponent server, final String expectedMessage) { + final Exception e = assertThrows(Exception.class, () -> startServer(server)); + + for (Throwable cause = e; cause != null; cause = cause.getCause()) { + if (cause instanceof IllegalArgumentException && cause.getMessage().contains(expectedMessage)) { + return; + } + } + fail("Expected an IllegalArgumentException with: " + expectedMessage, e); + } + + private static DefaultApplicationGroup createCertificateGroup() throws Exception { + return DefaultApplicationGroup.createAndInitialize( + new MemoryTrustListManager(), new MemoryCertificateStore(), new TestCertificateFactory(), + new CertificateValidator.InsecureCertificateValidator()); + } +} diff --git a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc index 25708c2cd51b..8dfbce83ebed 100644 --- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc +++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc @@ -12297,6 +12297,17 @@ With `allowUrlBody=true`, a body that does not start with `version: 1` and is no with a space or a relative name, now fails with an `InvalidPayloadException`, as a URL with an unknown scheme already did. Before, it failed with an `IllegalArgumentException`. A URL that cannot be fetched keeps its own exception. +=== camel-milo - certificateValidator of milo-server is used again, and cannot be combined with defaultCertificateValidator + +Since Camel 4.16, the `certificateValidator` option of the milo-server component failed the start of the server with a +`NullPointerException`, unless `defaultCertificateValidator` was set too, and then the custom validator was ignored. +The server now validates the certificates of the clients with `certificateValidator`. It needs `certificateManager`, +which holds the certificate of the server, and the server fails to start with a clear message without it. + +Setting both `certificateValidator` and `defaultCertificateValidator` now fails the start of the server with an +`IllegalArgumentException`. Keep only one of them: `defaultCertificateValidator` for a file based trust list, or +`certificateValidator` with `certificateManager` for a custom validator. + === Kamelets - removed Kamelets The Kamelet catalog (camel-kamelets 4.24) removes Kamelets that could not work on Camel 4.23 or 4.24: diff --git a/dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/MiloServerComponentBuilderFactory.java b/dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/MiloServerComponentBuilderFactory.java index 8771d67a46f0..059adc8eb839 100644 --- a/dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/MiloServerComponentBuilderFactory.java +++ b/dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/MiloServerComponentBuilderFactory.java @@ -284,7 +284,9 @@ public interface MiloServerComponentBuilderFactory { * To use a custom * org.eclipse.milo.opcua.stack.core.security.CertificateManager that * holds the certificate and the key pair of the server. Not used when - * certificateValidator or defaultCertificateValidator is set. + * defaultCertificateValidator is set. When certificateValidator is set, + * the certificate groups of this certificate manager validate the + * certificates of the clients with that validator. * * The option is a: * <code>org.eclipse.milo.opcua.stack.core.security.CertificateManager</code> type. @@ -300,7 +302,12 @@ public interface MiloServerComponentBuilderFactory { } /** - * Validator for client certificates. + * To use a custom + * org.eclipse.milo.opcua.stack.core.security.CertificateValidator that + * validates the certificates of the OPC UA clients, instead of the + * validators of the certificate groups of certificateManager. Requires + * certificateManager, which holds the certificate of the server. Cannot + * be used together with defaultCertificateValidator. * * The option is a: * <code>org.eclipse.milo.opcua.stack.core.security.CertificateValidator</code> type.
