[
https://issues.apache.org/jira/browse/QPID-8773?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18153440#comment-18153440
]
ASF GitHub Bot commented on QPID-8773:
--------------------------------------
dakirily commented on code in PR #464:
URL: https://github.com/apache/qpid-broker-j/pull/464#discussion_r4754012642
##########
broker-plugins/certificate-generator-bouncycastle/src/main/java/org/apache/qpid/server/security/certificate/bouncycastle/BouncyCastleCertificateGenerator.java:
##########
@@ -0,0 +1,263 @@
+/*
+ *
+ * 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.qpid.server.security.certificate.bouncycastle;
+
+import java.math.BigInteger;
+import java.net.InetAddress;
+import java.security.GeneralSecurityException;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidParameterException;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.NoSuchAlgorithmException;
+import java.security.PrivateKey;
+import java.security.ProviderException;
+import java.security.SecureRandom;
+import java.security.Signature;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.util.Date;
+import java.util.stream.Stream;
+
+import org.bouncycastle.asn1.DEROctetString;
+import org.bouncycastle.asn1.x509.BasicConstraints;
+import org.bouncycastle.asn1.x509.Extension;
+import org.bouncycastle.asn1.x509.GeneralName;
+import org.bouncycastle.asn1.x509.GeneralNames;
+import org.bouncycastle.cert.CertIOException;
+import org.bouncycastle.cert.X509v3CertificateBuilder;
+import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
+import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
+import org.bouncycastle.operator.ContentSigner;
+import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder;
+import org.bouncycastle.operator.OperatorCreationException;
+import org.bouncycastle.operator.RuntimeOperatorException;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.qpid.server.security.certificate.CertificateGenerator;
+import org.apache.qpid.server.security.certificate.CertificateRequest;
+import org.apache.qpid.server.security.certificate.GeneratedCertificate;
+
+/**
+ * Builds self-signed certificates with the Bouncy Castle certificate API.
+ * <p>
+ * Bouncy Castle is used only to assemble and encode the certificate. Key pair
generation, signing, random numbers
+ * and certificate parsing use the default JCA provider selection; no Bouncy
Castle provider is created or registered.
+ */
+final class BouncyCastleCertificateGenerator implements CertificateGenerator
+{
+ private static final Logger LOGGER =
LoggerFactory.getLogger(BouncyCastleCertificateGenerator.class);
+
+ private static final boolean IS_CA = false;
+ private static final boolean CRITICAL = true;
+
+ /**
+ * Uses the Bouncy Castle code the generator needs without performing any
cryptographic operation.
+ *
+ * @throws LinkageError if a Bouncy Castle library is missing from the
classpath or incompatible
+ */
+ static void checkLibraries()
+ {
+ new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
+ new GeneralNames(new GeneralName[] { new
GeneralName(GeneralName.dNSName, "localhost"),
+ new
GeneralName(GeneralName.iPAddress, new DEROctetString(new byte[4])) });
+ new BasicConstraints(false);
+ new JcaContentSignerBuilder("SHA256withRSA");
+ new JcaX509CertificateConverter();
+ // loads the builder class without building a certificate
+ LOGGER.debug("Bouncy Castle certificate builder {} is available",
JcaX509v3CertificateBuilder.class.getName());
+ }
+
+ @Override
+ public GeneratedCertificate generate(final CertificateRequest request)
throws GeneralSecurityException
+ {
+ try
+ {
+ return generateCertificate(request);
+ }
+ catch (LinkageError e)
+ {
+ // a Bouncy Castle class is missing or incompatible with the one
this plugin was built against
+ throw new GeneralSecurityException("The Bouncy Castle libraries on
the classpath are incomplete or "
+ + "incompatible: " + e, e);
+ }
+ catch (ProviderException e)
+ {
+ // a JCA provider reports some failures unchecked, for example a
FIPS provider whose self-test fails
+ throw new GeneralSecurityException("The security provider failed:
" + e, e);
+ }
+ }
+
+ private GeneratedCertificate generateCertificate(final CertificateRequest
request) throws GeneralSecurityException
+ {
+ final KeyPairGenerator keyPairGenerator =
KeyPairGenerator.getInstance(request.getKeyAlgorithm());
+ try
+ {
+ keyPairGenerator.initialize(request.getKeyLength());
+ }
+ catch (InvalidParameterException e)
+ {
+ throw new
InvalidAlgorithmParameterException(String.format("Unsupported key length %d for
'%s'",
+ request.getKeyLength(), request.getKeyAlgorithm()), e);
+ }
+
+ final KeyPair keyPair = keyPairGenerator.generateKeyPair();
+ final PrivateKey privateKey = keyPair.getPrivate();
+
+ final ContentSigner contentSigner =
createContentSigner(request.getSignatureAlgorithm(), privateKey);
+
+ final GeneralName[] subjectAlternativeNames =
Stream.concat(request.getDnsNames().stream()
+ .map(dnsName -> new GeneralName(GeneralName.dNSName,
dnsName)),
+ request.getAddresses().stream()
+ // the raw bytes, because Bouncy Castle cannot parse the
textual form of a scoped IPv6 address
+ // (fe80::1%1); the scope is local to the host and is not
part of the certificate
+ .map(address -> new GeneralName(GeneralName.iPAddress, new
DEROctetString(address.getAddress()))))
+ .toArray(GeneralName[]::new);
+
+ // RFC 5280 requires a positive serial number
+ final BigInteger serialNumber = new BigInteger(64, new
SecureRandom()).add(BigInteger.ONE);
+
+ final X509Certificate certificate;
+ try
+ {
+ final X509v3CertificateBuilder certificateBuilder =
+ new JcaX509v3CertificateBuilder(request.getSubject(),
serialNumber,
+
Date.from(request.getNotBefore()), Date.from(request.getNotAfter()),
+ request.getSubject(),
keyPair.getPublic())
+ .addExtension(Extension.basicConstraints, CRITICAL,
new BasicConstraints(IS_CA));
+ // RFC 5280 does not allow an empty subject alternative name
extension
+ if (subjectAlternativeNames.length > 0)
+ {
+
certificateBuilder.addExtension(Extension.subjectAlternativeName, false,
+ new
GeneralNames(subjectAlternativeNames));
+ }
+
+ // no provider is set, so the certificate is parsed by the default
JCA CertificateFactory
+ certificate = new
JcaX509CertificateConverter().getCertificate(certificateBuilder.build(contentSigner));
+ }
+ catch (CertIOException e)
+ {
+ throw new CertificateException("Unable to build certificate", e);
+ }
+ catch (RuntimeOperatorException e)
+ {
+ // thrown when the JCA provider fails to sign the certificate
+ throw securityException(e, "Unable to sign certificate");
+ }
+
+ // logged at info, as the providers come from the default JCA
selection and this is the only record of them;
+ // certificates are generated only when a keystore has no stored
certificate: on creation, on regeneration,
+ // or when opened without one
+ LOGGER.info("Generated self-signed certificate '{}': key pair provider
'{}', signature provider '{}', "
Review Comment:
The INFO log arguments call `signatureProvider()`, which creates a second
`Signature` and calls `initSign()`. This happens even when logging is off. The
saved counting-provider test records two signing initializations for one
certificate signature. There is only one actual signature, but the extra
initialization may still cost work or open another provider session.
The reported signer and certificate factory also come from separate lookups,
so they do not prove which engines produced the certificate. Please log the
providers from the engines that actually ran where possible, and leave out
provider fields that the builders do not expose. Guard any remaining optional
logging work.
##########
doc/java-broker/src/docbkx/management/managing/Java-Broker-Management-Managing-Keystores.xml:
##########
@@ -144,6 +147,64 @@
</itemizedlist>
</para>
</section>
+ <section
xml:id="Java-Broker-Management-Managing-Keystores-Certificate-Generators">
Review Comment:
Default JCA selection leaves each service to the host's provider
configuration. With BCFIPS first and in approved-only mode, it still was
possible to sign an `MD5withRSA` certificate through SunRsaSign. Provider
priority alone does not prevent fallback.
Please make the limits clear in the documentation.
##########
broker-core/src/main/java/org/apache/qpid/server/security/certificate/CertificateGenerators.java:
##########
@@ -0,0 +1,276 @@
+/*
+ *
+ * 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.qpid.server.security.certificate;
+
+import java.security.GeneralSecurityException;
+import java.security.NoSuchAlgorithmException;
+import java.util.Map;
+import java.util.ServiceConfigurationError;
+import java.util.TreeMap;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.qpid.server.plugin.QpidServiceLoader;
+import org.apache.qpid.server.util.ServerScopedRuntimeException;
+
+/**
+ * Selects the certificate generator used by the JVM.
+ * <p>
+ * The certificate generator is selected when the Broker starts, and otherwise
on first use. The selection rules are:
+ * <ul>
+ * <li>when {@value #PROPERTY} is set, the factory of that type is used;
startup fails if it is not installed
+ * or cannot create its generator for any reason</li>
+ * <li>when the property is not set and several factories are installed,
startup fails</li>
+ * <li>when the property is not set and no factory is installed,
certificate generation is unavailable</li>
+ * <li>when the property is not set and exactly one factory is installed,
it is used; if it cannot create its
+ * generator because a library it requires is missing or incompatible, a
warning is logged and certificate
+ * generation is unavailable, while any other failure, including a failed
static initialisation, makes startup
+ * fail</li>
+ * </ul>
+ * A selection that fails is not kept, so the next use selects again.
+ */
+public final class CertificateGenerators
+{
+ public static final String PROPERTY = "qpid.security.certificateGenerator";
+
+ static final String NOT_INSTALLED = "no certificate generator is installed
and enabled. Add the "
+ + "qpid-broker-plugins-certificate-generator-bouncycastle plugin
and the Bouncy Castle libraries "
+ + "(bcprov, bcpkix and bcutil) to the classpath, or use a keystore
with a supplied certificate";
+
+ private static final Logger LOGGER =
LoggerFactory.getLogger(CertificateGenerators.class);
+
+ private static final Object LOCK = new Object();
+
+ // guarded by LOCK
+ private static Selection _selection;
+
+ private CertificateGenerators()
+ {
+ }
+
+ /**
+ * Selects the certificate generator again, so that the current value of
{@value #PROPERTY} is used even if a
+ * generator was selected before, for example by an earlier Broker in the
same JVM.
+ *
+ * @throws IllegalArgumentException if the configuration does not identify
a single generator
+ * @throws ServerScopedRuntimeException if the factories cannot be loaded
or the generator cannot be created
+ */
+ public static void initialise()
+ {
+ synchronized (LOCK)
+ {
+ _selection = null;
+ selection();
+ }
+ }
+
+ /**
+ * Selects the certificate generator, if not already selected.
+ *
+ * @return true if a certificate generator is available
+ * @throws IllegalArgumentException if the configuration does not identify
a single generator
+ * @throws ServerScopedRuntimeException if the factories cannot be loaded
or the generator cannot be created
+ */
+ public static boolean isAvailable()
+ {
+ return selection().generator() != null;
+ }
+
+ /**
+ * Selects the certificate generator, if not already selected. Use the
result both to check availability and
+ * to report the reason, as the selection may change between two calls.
+ *
+ * @return why certificate generation is unavailable, or null if it is
available
+ * @throws IllegalArgumentException if the configuration does not identify
a single generator
+ * @throws ServerScopedRuntimeException if the factories cannot be loaded
or the generator cannot be created
+ */
+ public static String getUnavailableReason()
+ {
+ return selection().unavailableReason();
+ }
+
+ /**
+ * @return the selected certificate generator
+ * @throws NoSuchAlgorithmException if no certificate generator is
available
+ */
+ public static CertificateGenerator get() throws NoSuchAlgorithmException
+ {
+ final Selection selection = selection();
+ if (selection.generator() == null)
+ {
+ throw new NoSuchAlgorithmException("Certificate generation is
unavailable: "
+ +
selection.unavailableReason());
+ }
+ return selection.generator();
+ }
+
+ private static Selection selection()
+ {
+ // not used on a hot path, so no lock-free fast path is needed
+ synchronized (LOCK)
+ {
+ if (_selection == null)
+ {
+ _selection = select(discover(), System.getProperty(PROPERTY));
+ }
+ return _selection;
+ }
+ }
+
+ private static Iterable<CertificateGeneratorFactory> discover()
+ {
+ try
+ {
+ return new
QpidServiceLoader().instancesOf(CertificateGeneratorFactory.class);
+ }
+ catch (ServiceConfigurationError | LinkageError e)
+ {
+ throw new ServerScopedRuntimeException("Unable to load certificate
generator factories", e);
+ }
+ }
+
+ static Selection select(final Iterable<CertificateGeneratorFactory>
discovered, final String requestedType)
+ {
+ final Map<String, CertificateGeneratorFactory> factories = new
TreeMap<>();
+ for (final CertificateGeneratorFactory factory : discovered)
+ {
+ final CertificateGeneratorFactory existing =
factories.putIfAbsent(factory.getType(), factory);
+ if (existing != null)
+ {
+ throw new IllegalArgumentException(String.format(
+ "Certificate generator type '%s' is provided by both
%s and %s",
+ factory.getType(), existing.getClass().getName(),
factory.getClass().getName()));
+ }
+ }
+
+ if (requestedType != null && !requestedType.isBlank())
+ {
+ final CertificateGeneratorFactory factory =
factories.get(requestedType);
+ if (factory == null)
+ {
+ throw new IllegalArgumentException(String.format(
+ "Unknown certificate generator '%s' set in '%s', only
the following types are supported: %s",
+ requestedType, PROPERTY, factories.keySet()));
+ }
+ try
+ {
+ return create(factory);
+ }
+ catch (GeneralSecurityException | LinkageError e)
+ {
+ throw new ServerScopedRuntimeException(String.format(
+ "Certificate generator '%s' set in '%s' could not be
created", requestedType, PROPERTY), e);
+ }
+ }
+
+ if (factories.size() > 1)
+ {
+ throw new IllegalArgumentException(String.format(
+ "Several certificate generators are installed %s, set '%s'
to select one",
+ factories.keySet(), PROPERTY));
+ }
+
+ if (factories.isEmpty())
+ {
+ LOGGER.info("No certificate generator is installed and enabled, "
+ + "generation of self-signed certificates is
unavailable");
+ return Selection.unavailable(NOT_INSTALLED);
+ }
+
+ final CertificateGeneratorFactory factory =
factories.values().iterator().next();
+ try
+ {
+ return create(factory);
+ }
+ catch (ExceptionInInitializerError e)
Review Comment:
With automatic selection, the same broken installation can give two
different startup results. Using `bc-fips` 2.1.0 with standard 1.86 `bcpkix`
and `bcutil`, the first `initialise()` marks generation unavailable
after `NoSuchFieldError`. A second call in the same class loader throws a
startup exception because Java now reports the failed class initialization as
`NoClassDefFoundError`.
This is an incompatible library set, so it is a smaller concern than
changing a live broker's generator. Still, please keep the automatic
missing/incompatible-library outcome consistent on retry and retain the
original cause. An explicit choice should fail on both attempts. A test that
initializes twice would cover it.
##########
broker-core/src/main/java/org/apache/qpid/server/security/certificate/CertificateGenerators.java:
##########
@@ -0,0 +1,276 @@
+/*
+ *
+ * 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.qpid.server.security.certificate;
+
+import java.security.GeneralSecurityException;
+import java.security.NoSuchAlgorithmException;
+import java.util.Map;
+import java.util.ServiceConfigurationError;
+import java.util.TreeMap;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.qpid.server.plugin.QpidServiceLoader;
+import org.apache.qpid.server.util.ServerScopedRuntimeException;
+
+/**
+ * Selects the certificate generator used by the JVM.
+ * <p>
+ * The certificate generator is selected when the Broker starts, and otherwise
on first use. The selection rules are:
+ * <ul>
+ * <li>when {@value #PROPERTY} is set, the factory of that type is used;
startup fails if it is not installed
+ * or cannot create its generator for any reason</li>
+ * <li>when the property is not set and several factories are installed,
startup fails</li>
+ * <li>when the property is not set and no factory is installed,
certificate generation is unavailable</li>
+ * <li>when the property is not set and exactly one factory is installed,
it is used; if it cannot create its
+ * generator because a library it requires is missing or incompatible, a
warning is logged and certificate
+ * generation is unavailable, while any other failure, including a failed
static initialisation, makes startup
+ * fail</li>
+ * </ul>
+ * A selection that fails is not kept, so the next use selects again.
+ */
+public final class CertificateGenerators
+{
+ public static final String PROPERTY = "qpid.security.certificateGenerator";
+
+ static final String NOT_INSTALLED = "no certificate generator is installed
and enabled. Add the "
+ + "qpid-broker-plugins-certificate-generator-bouncycastle plugin
and the Bouncy Castle libraries "
+ + "(bcprov, bcpkix and bcutil) to the classpath, or use a keystore
with a supplied certificate";
+
+ private static final Logger LOGGER =
LoggerFactory.getLogger(CertificateGenerators.class);
+
+ private static final Object LOCK = new Object();
+
+ // guarded by LOCK
+ private static Selection _selection;
+
+ private CertificateGenerators()
+ {
+ }
+
+ /**
+ * Selects the certificate generator again, so that the current value of
{@value #PROPERTY} is used even if a
+ * generator was selected before, for example by an earlier Broker in the
same JVM.
+ *
+ * @throws IllegalArgumentException if the configuration does not identify
a single generator
+ * @throws ServerScopedRuntimeException if the factories cannot be loaded
or the generator cannot be created
+ */
+ public static void initialise()
Review Comment:
`initialise()` clears a static selection each time a broker starts. Brokers
that share the same copy of broker-core therefore share a choice that a later
startup can replace.
Issue can be reproduced with two embedded brokers and different thread
context class loaders. Broker A started with the BC plugin and generated a
certificate. Broker B then started without the plugin. Both brokers stayed
ACTIVE, but A could no longer create an `AutoGeneratedSelfSigned` keystore.
Please keep the chosen generator with its broker or system configuration,
and use that same instance for both the availability check and generation.
Please cover overlapping broker lifetimes and shutdown/restart in a test.
##########
broker-core/src/main/java/org/apache/qpid/server/security/AutoGeneratedSelfSignedKeyStoreImpl.java:
##########
Review Comment:
The keystore already assumes that a private key can be saved as PKCS#8 and
loaded again. Its save order also already writes the certificate attribute
before encoding the private key. Those parts were pre-existing.
The new interface now allows another generator to return a signing key whose
`getEncoded()` returns null. The current contract tests accept such a key.
Please check that the key has a usable PKCS#8 encoding and prepare both
encodings before replacing the current pair or changing its stored attributes.
A bad generator result should give a clear configuration error and leave the
old pair usable. Please also add a regression test for that case.
##########
systests/qpid-systests-http-management/src/test/java/org/apache/qpid/tests/http/endtoend/keystore/AutoGeneratedSelfSignedKeyStoreTest.java:
##########
@@ -0,0 +1,74 @@
+/*
+ *
+ * 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.qpid.tests.http.endtoend.keystore;
+
+import static jakarta.servlet.http.HttpServletResponse.SC_CREATED;
+import static jakarta.servlet.http.HttpServletResponse.SC_OK;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+
+import java.io.ByteArrayInputStream;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.util.Base64;
+import java.util.Map;
+
+import javax.security.auth.x500.X500Principal;
+
+import org.junit.jupiter.api.Test;
+
+import org.apache.qpid.server.security.AutoGeneratedSelfSignedKeyStore;
+import org.apache.qpid.tests.http.HttpTestBase;
+
+/** Certificate generation by a running broker with the Bouncy Castle
certificate generator plugin installed. */
+public class AutoGeneratedSelfSignedKeyStoreTest extends HttpTestBase
Review Comment:
The no-generator recovery behavior is useful. In local tests it was possible
to successfully reopen an already populated store in fresh processes without
the plugin or BC jars, and the recovered key manager exposed the stored
certificate. A rejected regeneration also left that stored pair usable on
another restart.
Please add that sequence to the supplied tests. The new HTTP test checks the
certificate returned by management after create and regenerate; it does not
cover recovery without the libraries or a real TLS handshake.
##########
broker-plugins/certificate-generator-bouncycastle/src/main/java/org/apache/qpid/server/security/certificate/bouncycastle/BouncyCastleCertificateGenerator.java:
##########
@@ -0,0 +1,263 @@
+/*
+ *
+ * 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.qpid.server.security.certificate.bouncycastle;
+
+import java.math.BigInteger;
+import java.net.InetAddress;
+import java.security.GeneralSecurityException;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidParameterException;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.NoSuchAlgorithmException;
+import java.security.PrivateKey;
+import java.security.ProviderException;
+import java.security.SecureRandom;
+import java.security.Signature;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.util.Date;
+import java.util.stream.Stream;
+
+import org.bouncycastle.asn1.DEROctetString;
+import org.bouncycastle.asn1.x509.BasicConstraints;
+import org.bouncycastle.asn1.x509.Extension;
+import org.bouncycastle.asn1.x509.GeneralName;
+import org.bouncycastle.asn1.x509.GeneralNames;
+import org.bouncycastle.cert.CertIOException;
+import org.bouncycastle.cert.X509v3CertificateBuilder;
+import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
+import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
+import org.bouncycastle.operator.ContentSigner;
+import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder;
+import org.bouncycastle.operator.OperatorCreationException;
+import org.bouncycastle.operator.RuntimeOperatorException;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.qpid.server.security.certificate.CertificateGenerator;
+import org.apache.qpid.server.security.certificate.CertificateRequest;
+import org.apache.qpid.server.security.certificate.GeneratedCertificate;
+
+/**
+ * Builds self-signed certificates with the Bouncy Castle certificate API.
+ * <p>
+ * Bouncy Castle is used only to assemble and encode the certificate. Key pair
generation, signing, random numbers
+ * and certificate parsing use the default JCA provider selection; no Bouncy
Castle provider is created or registered.
+ */
+final class BouncyCastleCertificateGenerator implements CertificateGenerator
+{
+ private static final Logger LOGGER =
LoggerFactory.getLogger(BouncyCastleCertificateGenerator.class);
+
+ private static final boolean IS_CA = false;
+ private static final boolean CRITICAL = true;
+
+ /**
+ * Uses the Bouncy Castle code the generator needs without performing any
cryptographic operation.
+ *
+ * @throws LinkageError if a Bouncy Castle library is missing from the
classpath or incompatible
+ */
+ static void checkLibraries()
+ {
+ new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
+ new GeneralNames(new GeneralName[] { new
GeneralName(GeneralName.dNSName, "localhost"),
+ new
GeneralName(GeneralName.iPAddress, new DEROctetString(new byte[4])) });
+ new BasicConstraints(false);
+ new JcaContentSignerBuilder("SHA256withRSA");
+ new JcaX509CertificateConverter();
+ // loads the builder class without building a certificate
+ LOGGER.debug("Bouncy Castle certificate builder {} is available",
JcaX509v3CertificateBuilder.class.getName());
+ }
+
+ @Override
+ public GeneratedCertificate generate(final CertificateRequest request)
throws GeneralSecurityException
Review Comment:
With the tested BC-FIPS 2.1.0 setup in approved-only mode, requesting a
1024-bit RSA key throws `FipsUnapprovedOperationError`. It escapes the plugin's
catches and the keystore's checked exception handler, so that handler cannot
add the keystore name and requested algorithms. A later RSA-2048 request in the
same JVM succeeds.
Please turn the expected policy rejection into `GeneralSecurityException`
with its cause, or reject the unsupported setting with a checked error before
calling the provider. Keep the handling limited to understood policy
rejections; a blanket catch of `Throwable` / `Error` would also hide fatal
failures.
##########
broker-core/src/main/java/org/apache/qpid/server/transport/network/security/ssl/SSLUtil.java:
##########
@@ -869,9 +848,24 @@ else if (trustStores.size() == 1)
public static boolean canGenerateCerts()
{
- return true;
- }
-
+ return CertificateGenerators.isAvailable();
+ }
+
+ /**
+ * Generates a self-signed certificate with the certificate generator
selected by {@link CertificateGenerators}.
+ *
+ * @param keyAlgorithm JCA name of the key algorithm, for example RSA
+ * @param signatureAlgorithm name of the signature algorithm, for example
SHA256withRSA
+ * @param keyLength key length in bits
+ * @param startTime start of the validity period, in milliseconds since
the epoch
+ * @param endTime end of the validity period, in milliseconds since the
epoch
+ * @param x500Name subject and issuer distinguished name
+ * @param dnsNames DNS names for the subject alternative name extension,
or null for none
+ * @param addresses IP addresses for the subject alternative name
extension, or null for none
+ * @return private key and self-signed certificate
+ * @throws NoSuchAlgorithmException if no certificate generator is
available, or an algorithm is not supported
+ * @throws GeneralSecurityException if the parameters are invalid or the
certificate cannot be generated
+ */
public static KeyCertPair generateSelfSignedCertificate(final String
keyAlgorithm,
Review Comment:
Could the keystore use CertificateRequest and GeneratedCertificate directly?
The keystore appears to be its only production caller in the repository. This
would also make passing a broker-owned generator easier.
> Decouple self-signed certificate generation from Bouncy Castle to support
> FIPS 140 deployments
> ----------------------------------------------------------------------------------------------
>
> Key: QPID-8773
> URL: https://issues.apache.org/jira/browse/QPID-8773
> Project: Qpid
> Issue Type: Improvement
> Components: Broker-J
> Reporter: Partha Sarathy Maripini
> Priority: Major
> Labels: FIPS, Security
>
> *Motivation:*
> Deploying Apache Qpid Broker-J in enterprise and regulated environments (such
> as govcloud) requires FIPS 140 compliance. Broker-J's only direct use of
> Bouncy Castle in the broker runtime is building the self-signed certificate.
> Because that code is in broker-core:
> 1. Every deployment carries the standard Bouncy Castle libraries
> (bcprov-jdk18on / bcpkix-jdk18on), which are not FIPS 140 certified;
> 2. The static BouncyCastleProvider in SSLUtil conflicts with a runtime that
> supplies its own Bouncy Castle libraries on the platform class loader.
> *Proposed Solution:*
> 1. Move self-signed certificate generation behind a small SPI in broker-core
> (CertificateGeneratorFactory / CertificateGenerator, discovered with
> QpidServiceLoader). broker-core then has no Bouncy Castle dependency, and an
> enforcer rule keeps it that way.
> 2. Move the existing Bouncy Castle code into a new plugin,
> qpid-broker-plugins-certificate-generator-bouncycastle, which the standard
> distribution includes. The plugin does not create or register a security
> provider: keys, signatures and certificate parsing use default JCA provider
> selection, so a FIPS provider preferred by the platform is used automatically.
> 3. Select the generator when the Broker starts. If one generator is installed
> it is used; if several are installed, the system property
> qpid.security.certificateGenerator selects one. An unknown type, or a
> generator that cannot be created, makes startup fail.
> 4. Deployments that must not use Bouncy Castle can leave the plugin out
> (keystores whose certificate is already stored still load) or install a
> different generator through the same SPI.
> *Impact:*
> No change for the standard distribution. Applications that embed
> qpid-broker-core directly must add the plugin and the Bouncy Castle libraries
> (bcprov, bcpkix, bcutil) to keep creating AutoGeneratedSelfSigned keystores.
> *Out of scope:*
> Other FIPS-related areas, such as BCFKS / PKCS12-PBMAC1 keystores or TLS
> through BCJSSE, can follow as separate issues if needed.
> *Note:* I am actively working on this change and will submit a Pull Request
> shortly.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]