Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 38 additions & 26 deletions xmppserver/src/main/java/org/jivesoftware/util/S2STestService.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
import org.xmpp.packet.JID;
import org.xmpp.packet.Packet;

import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.security.cert.Certificate;
Expand Down Expand Up @@ -193,37 +193,49 @@ private void logSessionStatus() {

/**
* @return A String representation of the certificate chain for the connection to the domain under test.
* @throws IOException when a certificate cannot be encoded.
*/
private String getCertificates() {
private String getCertificates() throws IOException {
final DomainPair pair = new DomainPair(XMPPServer.getInstance().getServerInfo().getXMPPDomain(), domain.getDomain());
Session session = XMPPServer.getInstance().getSessionManager().getOutgoingServerSession(pair);
if (session == null) {
return "";
}
Log.info("Successfully negotiated TLS connection.");
return formatCertificates(session.getPeerCertificates());
}

/**
* Describes each certificate (subject, alternative names, validity) followed by the certificate itself in PEM
* format, so that it can be copied into other tools.
*
* @param certificates the certificate chain presented by the remote server.
* @return the description, never null.
* @throws IOException when a certificate cannot be encoded.
*/
static String formatCertificates(final Certificate[] certificates) throws IOException {
StringBuilder certs = new StringBuilder();
if (session != null) {
Log.info("Successfully negotiated TLS connection.");
Certificate[] certificates = session.getPeerCertificates();
for (Certificate certificate : certificates) {
X509Certificate x509cert = (X509Certificate) certificate;
certs.append("--\nSubject: ");
certs.append(x509cert.getSubjectDN());

List<String> subjectAltNames = new SANCertificateIdentityMapping().mapIdentity(x509cert);
if (!subjectAltNames.isEmpty()) {
certs.append("\nSubject Alternative Names: ");
for (String subjectAltName : subjectAltNames) {
certs.append("\n ");
certs.append(subjectAltName);
}
for (Certificate certificate : certificates) {
X509Certificate x509cert = (X509Certificate) certificate;
certs.append("--\nSubject: ");
certs.append(x509cert.getSubjectDN());

List<String> subjectAltNames = new SANCertificateIdentityMapping().mapIdentity(x509cert);
if (!subjectAltNames.isEmpty()) {
certs.append("\nSubject Alternative Names: ");
for (String subjectAltName : subjectAltNames) {
certs.append("\n ");
certs.append(subjectAltName);
}

certs.append("\nNot Before: ");
certs.append(x509cert.getNotBefore());
certs.append("\nNot After: ");
certs.append(x509cert.getNotAfter());
certs.append("\n\n-----BEGIN CERTIFICATE-----\n");
certs.append(DatatypeConverter.printBase64Binary(
certificate.getPublicKey().getEncoded()).replaceAll("(.{64})", "$1\n"));
certs.append("\n-----END CERTIFICATE-----\n\n");
}

certs.append("\nNot Before: ");
certs.append(x509cert.getNotBefore());
certs.append("\nNot After: ");
certs.append(x509cert.getNotAfter());
certs.append("\n\n");
certs.append(CertificateManager.toPemRepresentation(x509cert));
certs.append("\n");
}
return certs.toString();
}
Expand Down
108 changes: 108 additions & 0 deletions xmppserver/src/test/java/org/jivesoftware/util/S2STestServiceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/*
* Copyright (C) 2026 Ignite Realtime Foundation. All rights reserved.
*
* Licensed 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.jivesoftware.util;

import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.jivesoftware.openfire.keystore.KeystoreTestUtils;
import org.junit.jupiter.api.Test;

import java.io.ByteArrayInputStream;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
* Unit tests that verify the functionality of {@link S2STestService}.
*/
public class S2STestServiceTest
{
@Test
public void testCertificateOutputIsTheCertificateInPem() throws Exception
{
// Setup test fixture.
final X509Certificate certificate = KeystoreTestUtils.generateValidCertificateChain("remote.example.org").getCertificateChain()[0];

// Execute system under test.
final String output = S2STestService.formatCertificates(new Certificate[] { certificate });

// Verify results.
final int begin = output.indexOf("-----BEGIN CERTIFICATE-----");
final int end = output.indexOf("-----END CERTIFICATE-----") + "-----END CERTIFICATE-----".length();
assertTrue(begin >= 0 && end > begin, "the output must contain a PEM block");
final Certificate parsed = CertificateFactory.getInstance("X.509")
.generateCertificate(new ByteArrayInputStream(output.substring(begin, end).getBytes(StandardCharsets.US_ASCII)));
assertEquals(certificate, parsed, "the PEM block must hold the certificate itself, not only its public key");
assertTrue(output.contains("remote.example.org"), "the output must still show the subject for reading at a glance");
}

/**
* Verifies that the PEM block has no empty line, whatever the length of the certificate. OpenSSL refuses a block
* with an empty line before the END marker, which a naive wrap at 64 characters produces when the base64 text is
* an exact multiple of 64 characters long. Java's CertificateFactory accepts such a block, so parsing it back, as
* the other test does, cannot catch this.
*
* The certificates are signed with Ed25519, whose signature always has the same length, so each extra character
* in the subject name adds one byte to the encoding (a few more where a length field grows), and 96 consecutive
* name lengths cover every length of the encoding modulo 48 (48 bytes being 64 base64 characters).
*/
@Test
public void testCertificateOutputHasNoEmptyLineInThePemBlockForAnyLength() throws Exception
{
// Setup test fixture.
final KeyPair keyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair();
final Set<Integer> remaindersCovered = new HashSet<>();
for (int nameLength = 1; nameLength <= 96; nameLength++) {
final X509Certificate certificate = selfSignedCertificate(keyPair, "a".repeat(nameLength));
remaindersCovered.add(certificate.getEncoded().length % 48);

// Execute system under test.
final String output = S2STestService.formatCertificates(new Certificate[] { certificate });

// Verify results.
final int begin = output.indexOf("-----BEGIN CERTIFICATE-----");
final int end = output.indexOf("-----END CERTIFICATE-----");
assertTrue(begin >= 0 && end > begin, "the output must contain a PEM block");
// PemWriter ends its lines with the platform's line separator, so treat CRLF as one line break.
final String block = output.substring(begin, end).replace("\r\n", "\n");
assertFalse(block.contains("\n\n"), "no line in the PEM block may be empty (encoded length " + certificate.getEncoded().length + ")");
}
assertEquals(48, remaindersCovered.size(), "the certificates must cover every encoded length modulo 48");
}

private static X509Certificate selfSignedCertificate(final KeyPair keyPair, final String commonName) throws Exception
{
final X500Name name = new X500Name("CN=" + commonName);
final Date notBefore = new Date(0);
final Date notAfter = new Date(86_400_000L);
return new JcaX509CertificateConverter().getCertificate(
new JcaX509v3CertificateBuilder(name, BigInteger.ONE, notBefore, notAfter, name, keyPair.getPublic())
.build(new JcaContentSignerBuilder("Ed25519").build(keyPair.getPrivate())));
}
}
Loading