MockServer uses port unification to simplify the configuration so all protocols (i.e. HTTP, HTTPS / SSL, SOCKS, etc) are supported on the same port. This means when a request is sent over TLS (i.e. an HTTPS request) MockServer dynamically detects that the request is encrypted.

MockServer has support for TLS (i.e. HTTPS) in three areas:

  • TLS for inbound connections to support HTTPS for mocking, proxying and control-plane interactions (creating expectations, retrieving logs, etc)
  • mTLS for inbound connections (also called client authentication or two-way TLS) to authenticate any client sending HTTPS requests
  • TLS for outbound connections (also called forward proxy TLS) to authenticate any client sending HTTPS requests

MockServer HTTPS & TLS

The majority of HTTP clients perform the following steps when making an HTTPS request:

  1. establish TCP connection to remote server
  2. perform TLS handshake with remote server and verify trust chain by receiving remote server X.509 Certificate and verifying it is signed by a known Certificate Authority
  3. perform hostname validation by comparing hostname (or IP address) of remote server with Subject Alternative Name (SAN) or Common Name (CN) on X.509

MockServer is able to mock the behaviour of multiple hostnames (i.e. servers) and present a valid X.509 Certificates for them. MockServer achieves this by dynamically generating its X.509 Certificate using an in-memory list of hostnames and ip addresses, this is described in more detail below.

It is important to ensure that any client calling MockServer over TLS trust MockServer as a Certificate Authority (CA) (i.e. trust the MockServer CA X.509) the different approaches to establishing this trust is described below.

MockServer provides multiple ways its TLS can be configured. The following things can be configured:

 

TLS Termination (No Passthrough)

Note: when proxying HTTPS traffic, MockServer performs man-in-the-middle (MITM) TLS termination. It decrypts incoming TLS connections, inspects the HTTP request content for expectation matching, and then re-encrypts traffic when forwarding to the upstream server. MockServer does not support TLS passthrough (where encrypted traffic is forwarded without decryption). This is by design — MockServer needs to inspect request content to match expectations, record requests for verification, and apply response actions.

 

Ensure MockServer Certificates Are Trusted

The MockServer CA X.509 must be considered a valid trust root to ensure MockServer's dynamically generate X.509 certificates are trusted by an HTTP Client. This means the CA X.509 needs to be added into the JVM, HTTP Client or operating system as appropriate.

The MockServer CA X.509 can be found (in PEM format) in the MockServer github repo or can be loaded from the classpath location /org/mockserver/socket/CertificateAuthorityCertificate.pem

Operating System

It is possible to add the MockServer CA X.509 as a trusted root CA to your operating system, this will make most clients applications running on your OS (such as browsers) trust dynamically generated certificates from MockServer.

This is only an acceptable risk if it is done for a short period and the configuration setting dynamicallyCreateCertificateAuthorityCertificate is enabled to generate a local unique CA X.509 and Private Key that is saved to your local disk in the folder configured using directoryToSaveDynamicSSLCertificate.

If the configuration setting dynamicallyCreateCertificateAuthorityCertificate is not enabled, and your OS trusts the MockServer CA X.509, then this would leave your machine open to man-in-the-middle attacks because the corresponding Private Key is in the MockServer github repository. This would allow hackers to compromise all sensitive communicates such as to your bank or other sensitive sites.

Web Browsers

Browsers (such as Chrome, Firefox or IE) may not always trust dynamically generated certificates from MockServer because of Certificate Transparency and Public Key Pinning both of which make it hard to dynamically generate certificates that are trusted.

Some sites will work but others (such as google sites) won't work due to certificate pinning.

Browser that rely on Certificate Transparency will likely not trust dynamically generated certificates from MockServer

Java via Classpath

The following code shows how to load a file from the classpath or a relative filesystem location:

public void doSomething() {
    String mockServerCA = loadFileFromLocation("/org/mockserver/socket/CertificateAuthorityCertificate.pem");
}

public String loadFileFromLocation(String location) {
    location = location.trim().replaceAll("\\\\", "/");

    Path path;
    if (location.toLowerCase().startsWith("file:")) {
        path = Paths.get(URI.create(location));
    } else {
        path = Paths.get(location);
    }

    if (Files.exists(path)) {
        // org.apache.commons.io.FileUtils
        return FileUtils.readFileToString(path.toFile(), "UTF-8");
    } else {
        return loadFileFromClasspath(location);
    }
}

private String loadFileFromClasspath(String location) {
    try {
        InputStream inputStream = this.getClass().getResourceAsStream(location);
        try {
            if (inputStream == null) {
                inputStream = this.getClass().getClassLoader().getResourceAsStream(location);
            }

            if (inputStream == null) {
                inputStream = ClassLoader.getSystemResourceAsStream(location);
            }

            if (inputStream != null) {
                try {
                    // org.apache.commons.io.IOUtils
                    return IOUtils.toString(inputStream, Charsets.UTF_8);
                } catch (IOException e) {
                    throw new RuntimeException("Could not read " + location + " from the classpath", e);
                }
            }

            throw new RuntimeException("Could not find " + location + " on the classpath");
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    } catch (IOException ioe) {
        throw new RuntimeException("Exception closing input stream for " + location, ioe);
    }
}

Java DefaultSSLSocketFactory

Another mechanism to ensure the MockServer X.509 is trusted is to configure the DefaultSSLSocketFactory in the JVM using the following line:

HttpsURLConnection.setDefaultSSLSocketFactory(new KeyStoreFactory(new MockServerLogger()).sslContext().getSocketFactory());

This can be used in a test case, as follows:

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.logging.MockServerLogger;
import org.mockserver.socket.PortFactory;
import org.mockserver.socket.tls.KeyStoreFactory;

import javax.net.ssl.HttpsURLConnection;

public class ExampleTestClass {

    private static ClientAndServer mockServer;

    @BeforeClass
    public static void startMockServer() {
        // ensure all connection using HTTPS will use the SSL context defined by
        // MockServer to allow dynamically generated certificates to be accepted
        HttpsURLConnection.setDefaultSSLSocketFactory(new KeyStoreFactory(new MockServerLogger()).sslContext().getSocketFactory());
        mockServer = ClientAndServer.startClientAndServer(PortFactory.findFreePort());
    }

    @AfterClass
    public static void stopMockServer() {
        mockServer.stop();
    }

    @Test
    public void shouldDoSomething() {
        // test system
    }
}

Java Custom TrustStore (Programmatic)

If you cannot modify the JVM's default SSLSocketFactory, you can programmatically create a custom TrustStore that trusts MockServer's dynamically generated certificates and use it with a specific HTTP client:

import org.mockserver.logging.MockServerLogger;
import org.mockserver.socket.tls.KeyStoreFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;

KeyStoreFactory keyStoreFactory = new KeyStoreFactory(new MockServerLogger());
KeyStore trustStore = keyStoreFactory.loadOrCreateKeyStore();

TrustManagerFactory trustManagerFactory =
    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);

HttpsURLConnection connection =
    (HttpsURLConnection) new URL("https://localhost:1080/some/path").openConnection();
connection.setSSLSocketFactory(sslContext.getSocketFactory());

This approach is useful when you need to trust MockServer's certificates for a specific connection without affecting other HTTPS connections in the JVM.

Java Keytool

The Java keytool command can also be used to add the MockServer CA X.509 certificate to the list of trust CA Certificates for a JVM, as follows:

keytool -import -v -keystore /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts -alias mockserver-ca -file CertificateAuthorityCertificate.pem -storepass changeit -trustcacerts -noprompt

An example bash script showing how this can be done can be found in the MockServer github repo

 

Hostname Validation

MockServer is able to mock the behaviour of multiple hostnames (i.e. servers) and present a valid X.509 Certificates for them. MockServer achieves this by dynamically generating its X.509 Certificate using an in-memory list of hostnames and ip addresses. When the list of hostnames or ips addresses changes a new certificate is generated. The list of hostnames is updated, when:

  • configuration for SAN hostnames or SAN IP addresses is specified
  • an expectation is added containing a Host header with a hostname not seen before
  • a request is received containing a Host header with a hostname not seen before
  • a TLS handshake using Server Name Indication (SNI) with a hostname not seen before

Note: if a request is received with a Host header for a hostname not seen before the first request will fail validation because the TLS connection has already been established before the Host header can be read, any subsequent requests with that hostname will pass hostname validation.

 

mTLS Examples

The following examples show how to configure MockServer with mutual TLS (mTLS / client authentication) using self-generated certificates. A complete Docker Compose example is available in the MockServer repository.

 

Step 1: Generate Certificates

This example uses one CA to sign both server and client certificates. In production, server and client certificates may be issued by separate trusted CAs. The three certificate sets are:

  • CA certificate and key — the root of trust; both MockServer and clients must trust this CA
  • Server certificate and key — used by MockServer to identify itself to clients
  • Client certificate and key — used by clients (curl, HTTP libraries) to authenticate to MockServer

MockServer accepts private keys in both PKCS#8 (-----BEGIN PRIVATE KEY-----) and PKCS#1 RSA (-----BEGIN RSA PRIVATE KEY-----) PEM format. The examples below use PKCS#8 for consistency. To convert a PKCS#1 key to PKCS#8:

openssl pkcs8 -topk8 -inform PEM -in private_key_PKCS_1.pem -out private_key_PKCS_8.pem -nocrypt

Using OpenSSL (Recommended)

#!/usr/bin/env bash
set -euo pipefail

DAYS=3650
KEY_SIZE=2048

# 1. Generate Certificate Authority (CA)
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:${KEY_SIZE} -out ca-key.pem
openssl req -new -x509 -key ca-key.pem -out ca.pem -days ${DAYS} \
    -subj "/C=UK/ST=England/L=London/O=MockServer/CN=MockServer CA"

# 2. Generate server certificate signed by CA
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:${KEY_SIZE} -out server-key-pkcs8.pem
openssl req -new -key server-key-pkcs8.pem -out server.csr \
    -subj "/C=UK/ST=England/L=London/O=MockServer/CN=localhost"

cat > server-ext.cnf <<EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage=digitalSignature,keyEncipherment
extendedKeyUsage=serverAuth
subjectAltName=DNS:localhost,DNS:mockserver,DNS:host.docker.internal,IP:127.0.0.1,IP:0.0.0.0
EOF

openssl x509 -req -in server.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial \
    -out server-cert.pem -days ${DAYS} -extfile server-ext.cnf

# Create certificate chain (leaf + CA)
cat server-cert.pem ca.pem > server-cert-chain.pem

# 3. Generate client certificate signed by CA
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:${KEY_SIZE} -out client-key-pkcs8.pem
openssl req -new -key client-key-pkcs8.pem -out client.csr \
    -subj "/C=UK/ST=England/L=London/O=MockServer/CN=MockServer Client"

cat > client-ext.cnf <<EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage=digitalSignature,keyEncipherment
extendedKeyUsage=clientAuth
EOF

openssl x509 -req -in client.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial \
    -out client-cert.pem -days ${DAYS} -extfile client-ext.cnf

cat client-cert.pem ca.pem > client-cert-chain.pem

# Clean up CSR and temp files
rm -f server.csr server-ext.cnf client.csr client-ext.cnf ca.srl

Using CFSSL (Alternative)

CFSSL is CloudFlare's PKI toolkit. Install with brew install cfssl.

#!/usr/bin/env bash
set -euo pipefail

# 1. Generate CA
cat > ca-csr.json <<EOF
{
  "key": { "algo": "rsa", "size": 2048 },
  "names": [{ "C": "UK", "L": "London", "O": "MockServer", "CN": "MockServer CA" }]
}
EOF
cfssl genkey -initca ca-csr.json | cfssljson -bare ca
rm -f ca.csr

# 2. Create signing config with explicit profiles and expiry
cat > cfssl-config.json <<EOF
{
  "signing": {
    "default": { "expiry": "87600h" },
    "profiles": {
      "server": {
        "expiry": "87600h",
        "usages": ["signing", "key encipherment", "server auth"]
      },
      "client": {
        "expiry": "87600h",
        "usages": ["signing", "key encipherment", "client auth"]
      }
    }
  }
}
EOF

# 3. Generate server certificate
cat > server-csr.json <<EOF
{
  "CN": "localhost",
  "hosts": ["localhost", "mockserver", "host.docker.internal", "127.0.0.1", "0.0.0.0"],
  "key": { "algo": "rsa", "size": 2048 },
  "names": [{ "C": "UK", "L": "London", "O": "MockServer" }]
}
EOF
cfssl gencert -ca ca.pem -ca-key ca-key.pem -config cfssl-config.json -profile server \
    server-csr.json | cfssljson -bare server
rm -f server.csr
openssl pkcs8 -topk8 -inform PEM -in server-key.pem -out server-key-pkcs8.pem -nocrypt
mv server.pem server-cert.pem
cat server-cert.pem ca.pem > server-cert-chain.pem

# 4. Generate client certificate
cat > client-csr.json <<EOF
{
  "CN": "MockServer Client",
  "key": { "algo": "rsa", "size": 2048 },
  "names": [{ "C": "UK", "L": "London", "O": "MockServer" }]
}
EOF
cfssl gencert -ca ca.pem -ca-key ca-key.pem -config cfssl-config.json -profile client \
    client-csr.json | cfssljson -bare client
rm -f client.csr
openssl pkcs8 -topk8 -inform PEM -in client-key.pem -out client-key-pkcs8.pem -nocrypt
mv client.pem client-cert.pem
cat client-cert.pem ca.pem > client-cert-chain.pem

# Clean up
rm -f ca-csr.json cfssl-config.json server-csr.json client-csr.json server-key.pem client-key.pem

Both approaches produce the same output files:

FilePurpose
ca-key.pem, ca.pemCA private key and certificate (root of trust)
server-key-pkcs8.pem, server-cert.pemServer private key (PKCS#8) and certificate
server-cert-chain.pemServer certificate chain (leaf + CA)
client-key-pkcs8.pem, client-cert.pemClient private key (PKCS#8) and certificate
client-cert-chain.pemClient certificate chain (leaf + CA)
 

Step 2: Data-Plane mTLS (Client Authentication for All Requests)

Data-plane mTLS requires every HTTPS client to present a valid certificate. Non-TLS (HTTP) requests receive a 426 Upgrade Required response. This is the most common mTLS setup.

Docker Compose Configuration

version: "2.4"
services:
  mockserver:
    image: mockserver/mockserver:latest
    ports:
      - "1080:1080"
    environment:
      MOCKSERVER_LOG_LEVEL: INFO
      MOCKSERVER_SERVER_PORT: 1080
      # Enable mTLS — require client certificates for all TLS connections
      MOCKSERVER_TLS_MUTUAL_AUTHENTICATION_REQUIRED: "true"
      # CA certificate used to verify client certificates
      MOCKSERVER_TLS_MUTUAL_AUTHENTICATION_CERTIFICATE_CHAIN: /certs/ca.pem
      # Custom CA for signing MockServer's own server certificate
      MOCKSERVER_CERTIFICATE_AUTHORITY_PRIVATE_KEY: /certs/ca-key.pem
      MOCKSERVER_CERTIFICATE_AUTHORITY_X509_CERTIFICATE: /certs/ca.pem
      # Custom server certificate and key (signed by the CA above)
      MOCKSERVER_TLS_PRIVATE_KEY_PATH: /certs/server-key-pkcs8.pem
      MOCKSERVER_TLS_X509_CERTIFICATE_PATH: /certs/server-cert-chain.pem
      # Validate TLS configuration at startup
      MOCKSERVER_PROACTIVELY_INITIALISE_TLS: "true"
      # Load expectations from file
      MOCKSERVER_INITIALIZATION_JSON_PATH: /config/expectationInitialiser.json
    volumes:
      - ./certs:/certs:ro
      - ./config:/config:ro

Testing with curl

Successful mTLS request (client presents certificate):

curl --cacert certs/ca.pem \
     --cert certs/client-cert.pem \
     --key certs/client-key-pkcs8.pem \
     https://localhost:1080/hello

Failed request without client certificate (TLS handshake fails):

curl --cacert certs/ca.pem https://localhost:1080/hello
# Error varies by TLS backend, e.g.: alert bad certificate / certificate required / handshake failure

Failed request over HTTP (returns 426 Upgrade Required):

curl http://localhost:1080/hello
# 426 Upgrade Required

Creating Expectations with curl over mTLS

When data-plane mTLS is enabled, creating expectations via the MockServer API also requires mTLS:

curl --cacert certs/ca.pem \
     --cert certs/client-cert.pem \
     --key certs/client-key-pkcs8.pem \
     -X PUT https://localhost:1080/mockserver/expectation \
     -H "Content-Type: application/json" \
     -d '[{
       "httpRequest": { "method": "GET", "path": "/api/users" },
       "httpResponse": {
         "statusCode": 200,
         "headers": { "Content-Type": ["application/json"] },
         "body": "[{\"id\": 1, \"name\": \"Alice\"}]"
       }
     }]'
 

Control-Plane mTLS (Securing the Management API Only)

Control-plane mTLS secures only the MockServer management API (expectations, verification, reset, etc.) while leaving the data plane accessible without client certificates. This is useful when you want to protect who can configure MockServer without requiring mTLS for all test traffic.

Docker Compose Configuration

version: "2.4"
services:
  mockserver:
    image: mockserver/mockserver:latest
    ports:
      - "1080:1080"
    environment:
      MOCKSERVER_LOG_LEVEL: INFO
      MOCKSERVER_SERVER_PORT: 1080
      # Control-plane mTLS — only management API requires client certificates
      MOCKSERVER_CONTROL_PLANE_TLS_MUTUAL_AUTHENTICATION_REQUIRED: "true"
      MOCKSERVER_CONTROL_PLANE_TLS_MUTUAL_AUTHENTICATION_CERTIFICATE_CHAIN: /certs/ca.pem
      # Custom CA for signing MockServer's server certificate
      MOCKSERVER_CERTIFICATE_AUTHORITY_PRIVATE_KEY: /certs/ca-key.pem
      MOCKSERVER_CERTIFICATE_AUTHORITY_X509_CERTIFICATE: /certs/ca.pem
      # Custom server certificate and key
      MOCKSERVER_TLS_PRIVATE_KEY_PATH: /certs/server-key-pkcs8.pem
      MOCKSERVER_TLS_X509_CERTIFICATE_PATH: /certs/server-cert-chain.pem
      MOCKSERVER_PROACTIVELY_INITIALISE_TLS: "true"
      MOCKSERVER_INITIALIZATION_JSON_PATH: /config/expectationInitialiser.json
    volumes:
      - ./certs:/certs:ro
      - ./config:/config:ro

Testing with curl

Data-plane requests work without client certificates:

# This works — data plane does not require mTLS
curl --cacert certs/ca.pem https://localhost:1080/hello

Management API requires client certificates:

# This fails — control plane requires mTLS
curl --cacert certs/ca.pem \
     -X PUT https://localhost:1080/mockserver/expectation \
     -H "Content-Type: application/json" \
     -d '[{"httpRequest": {"path": "/test"}, "httpResponse": {"body": "ok"}}]'
# 401 Unauthorized

# This works — client certificate provided
curl --cacert certs/ca.pem \
     --cert certs/client-cert.pem \
     --key certs/client-key-pkcs8.pem \
     -X PUT https://localhost:1080/mockserver/expectation \
     -H "Content-Type: application/json" \
     -d '[{"httpRequest": {"path": "/test"}, "httpResponse": {"body": "ok"}}]'
 

Java Client with mTLS

When using MockServerClient with control-plane mTLS, configure the client certificate paths:

import org.mockserver.client.MockServerClient;
import org.mockserver.configuration.ConfigurationProperties;

// Enable control-plane mTLS on the client side
ConfigurationProperties.controlPlaneTLSMutualAuthenticationRequired(true);

// Client certificate and key for authenticating to MockServer
ConfigurationProperties.controlPlanePrivateKeyPath("/path/to/client-key-pkcs8.pem");
ConfigurationProperties.controlPlaneX509CertificatePath("/path/to/client-cert-chain.pem");

// CA certificate to verify MockServer's server certificate
ConfigurationProperties.controlPlaneTLSMutualAuthenticationCAChain("/path/to/ca.pem");

// Connect over HTTPS
MockServerClient client = new MockServerClient("localhost", 1080)
    .withSecure(true);
 

BouncyCastle FIPS Support

MockServer supports BouncyCastle FIPS (bc-fips) as a drop-in alternative to the standard BouncyCastle provider (bcprov-jdk18on). This is useful in environments that require FIPS 140-2 compliant cryptographic modules.

MockServer automatically detects which BouncyCastle provider is available at runtime — no configuration changes are needed. To use FIPS mode:

  1. Exclude the standard BouncyCastle dependency (bcprov-jdk18on) from your classpath
  2. Add the BouncyCastle FIPS dependency (bc-fips) instead
  3. Ensure the FIPS provider is registered with the JVM (e.g. via java.security configuration or programmatically)

Example Maven dependency replacement:

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bc-fips</artifactId>
    <version>1.0.2.5</version>
</dependency>

MockServer will use whichever provider it finds on the classpath. If both are present, the standard (non-FIPS) provider is used. If neither is available, MockServer falls back to the JVM's default cryptographic provider.

 

TLS Troubleshooting

The following are common TLS-related issues and their solutions:

SSL Context Initialization Failure

If you see an error like javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty, this means the JVM's trust store is empty or misconfigured. This is common in minimal Docker images or Linux systems where the CA certificates package is not installed.

Solution:

# Debian/Ubuntu
apt-get install -y ca-certificates-java
update-ca-certificates -f

# Alpine
apk add --no-cache ca-certificates java-cacerts

Certificate Not Trusted

If your HTTP client rejects MockServer's certificate, ensure the MockServer CA certificate is trusted. See Ensure MockServer Certificates Are Trusted above for multiple approaches (OS trust store, JVM keytool, programmatic SSLContext).

First Request Fails with New Hostname

When MockServer receives a request with a Host header for a hostname it has not seen before, the first request may fail TLS hostname validation. This is because the TLS handshake completes before MockServer can read the Host header and regenerate its certificate. Subsequent requests with that hostname will succeed. To avoid this, pre-configure the expected hostnames using the sslSubjectAlternativeNameDomains configuration property.

Connection Reset or Broken Pipe

If you see "Connection reset" or "Broken pipe" errors during TLS connections, common causes include:

  • Expired test certificates: MockServer's dynamically generated certificates have a limited validity period. If you are using custom CA certificates for testing, ensure they have not expired.
  • Protocol mismatch: Ensure the client and MockServer agree on a TLS protocol version. MockServer supports TLS 1.2 and TLS 1.3 by default. Use the tlsProtocols configuration property to adjust supported protocols.
  • Corporate TLS inspection proxies: If your network uses a TLS inspection proxy, you may need to add the proxy's CA certificate to the JVM trust store, or configure the JAVA_OPTS with -Djavax.net.ssl.trustStore pointing to a trust store that includes both the proxy CA and MockServer CA certificates.

Certificate Chain Is Not Valid (mTLS)

If you see java.security.KeyStoreException: Certificate chain is not valid, the server certificate is not signed by the configured Certificate Authority. This commonly happens when:

  • Server cert and CA don't match: The certificate in MOCKSERVER_TLS_X509_CERTIFICATE_PATH was not signed by the CA in MOCKSERVER_CERTIFICATE_AUTHORITY_X509_CERTIFICATE. Regenerate the server certificate using the same CA.
  • Missing certificate chain: The certificate file must contain the full chain (leaf certificate followed by CA certificate). Create it with: cat server-cert.pem ca.pem > server-cert-chain.pem
  • Wrong key format: The private key must be in PKCS#8 format (begins with -----BEGIN PRIVATE KEY-----). PKCS#1 keys (beginning with -----BEGIN RSA PRIVATE KEY-----) must be converted:
    openssl pkcs8 -topk8 -inform PEM -in key-pkcs1.pem -out key-pkcs8.pem -nocrypt

426 Upgrade Required (mTLS)

When tlsMutualAuthenticationRequired is enabled, MockServer requires all connections to use TLS. If a plain HTTP request is received, MockServer returns 426 Upgrade Required to indicate that the client must use HTTPS with a client certificate. Change your request URL from http:// to https:// and provide a client certificate.

Bad Certificate / Handshake Failure (mTLS)

If curl reports sslv3 alert bad certificate or SSL_ERROR_HANDSHAKE_FAILURE_ALERT, the client certificate was rejected by MockServer. Check that:

  • The client certificate was signed by the same CA configured in MOCKSERVER_TLS_MUTUAL_AUTHENTICATION_CERTIFICATE_CHAIN
  • The client certificate has not expired
  • You are passing both --cert and --key to curl
   

TLS Configuration:

The following diagram shows where TLS/mTLS configuration settings are used:

MockServer HTTPS & TLS

 

Inbound TLS (for Received Requests)

Dynamic Inbound Certificate Authority X.509 & Private Key

Enable dynamic creation of Certificate Authority X.509 Certificate and Private Key

Enable this property to increase the security of trusting the MockServer Certificate Authority X.509 by ensuring a local dynamic value is used instead of the public value in the MockServer git repo.

These PEM files will be created and saved in the directory specified with configuration property directoryToSaveDynamicSSLCertificate.

A Certificate Authority X.509 Certificate and Private Key will only be created if the files used to save them are not already present. Therefore, if MockServer is re-started multiple times with the same value for directoryToSaveDynamicSSLCertificate. the Certificate Authority X.509 Certificate and Private Key will only be created once.

Type: boolean Default: false

Java Code:

ConfigurationProperties.dynamicallyCreateCertificateAuthorityCertificate(boolean enable)

System Property:

-Dmockserver.dynamicallyCreateCertificateAuthorityCertificate=...

Environment Variable:

MOCKSERVER_DYNAMICALLY_CREATE_CERTIFICATE_AUTHORITY_CERTIFICATE=...

Property File:

mockserver.dynamicallyCreateCertificateAuthorityCertificate=...

Example:

-Dmockserver.dynamicallyCreateCertificateAuthorityCertificate="true"

Directory used to save the dynamically generated Certificate Authority X.509 Certificate and Private Key.

This directory will only be used if MockServer is configured to create a dynamic Certificate Authority X.509 certificate and private key using dynamicallyCreateCertificateAuthorityCertificate.

Type: string Default: null

Java Code:

ConfigurationProperties.directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate)

System Property:

-Dmockserver.directoryToSaveDynamicSSLCertificate=...

Environment Variable:

MOCKSERVER_CERTIFICATE_DIRECTORY_TO_SAVE_DYNAMIC_SSL_CERTIFICATE=...

Property File:

mockserver.directoryToSaveDynamicSSLCertificate=...

Example:

-Dmockserver.directoryToSaveDynamicSSLCertificate="/some/existing/path"

Proactively initialise TLS during start to ensure that if dynamicallyCreateCertificateAuthorityCertificate is enabled the Certificate Authority X.509 Certificate and Private Key will be created during start up and not when the first TLS connection is received.

This setting will also ensure any configured private key and X.509 will be loaded during start up and not when the first TLS connection is received to give immediate feedback on any related TLS configuration errors.

Type: boolean Default: false

Java Code:

ConfigurationProperties.proactivelyInitialiseTLS(boolean enable)

System Property:

-Dmockserver.proactivelyInitialiseTLS=...

Environment Variable:

MOCKSERVER_PROACTIVELY_INITIALISE_TLS=...

Property File:

mockserver.proactivelyInitialiseTLS=...

Example:

-Dmockserver.proactivelyInitialiseTLS="true"

TLS Protocol Versions

Comma separated list of TLS protocol versions to enable for both inbound and outbound TLS connections.

The default value is TLSv1,TLSv1.1,TLSv1.2 which includes TLSv1 and TLSv1.1 for backward compatibility. These older protocols are deprecated and considered insecure by most security standards.

To enable TLS 1.3, add TLSv1.3 to the list. To use only modern protocols, set the value to TLSv1.2,TLSv1.3.

Note: TLS 1.3 requires Java 11 or later. MockServer's default includes TLSv1 and TLSv1.1 for backward compatibility but you should restrict protocols to TLSv1.2 and TLSv1.3 in production-like environments.

Type: string Default: TLSv1,TLSv1.1,TLSv1.2

Java Code:

ConfigurationProperties.tlsProtocols("TLSv1.2,TLSv1.3")

System Property:

-Dmockserver.tlsProtocols=...

Environment Variable:

MOCKSERVER_TLS_PROTOCOLS=...

Property File:

mockserver.tlsProtocols=...

Example (enable TLS 1.2 and 1.3 only):

-Dmockserver.tlsProtocols="TLSv1.2,TLSv1.3"

Example (Docker environment variable):

MOCKSERVER_TLS_PROTOCOLS="TLSv1.2,TLSv1.3"

Dynamic Inbound Private Key & X.509

MockServer dynamically updates the Subject Alternative Name (SAN) values for its TLS certificate to add domain names and IP addresses from request Host headers and Host headers in expectations, this configuration setting disables this automatic update and only uses SAN value provided in TLS Subject Alternative Name Domains and TLS Subject Alternative Name IPs configuration properties.

When this property is enabled the generated X.509 Certificate and Private Key pair are saved to the directoryToSaveDynamicSSLCertificate as Certificate.pem and PKCS8PrivateKey.pem

Type: boolean Default: false

Java Code:

ConfigurationProperties.preventCertificateDynamicUpdate(boolean prevent)

System Property:

-Dmockserver.preventCertificateDynamicUpdate=...

Environment Variable:

MOCKSERVER_PREVENT_CERTIFICATE_DYNAMIC_UPDATE=...

Property File:

mockserver.preventCertificateDynamicUpdate=...

Example:

-Dmockserver.preventCertificateDynamicUpdate="true"

The domain name for auto-generate TLS certificates

Type: string Default: localhost

Java Code:

ConfigurationProperties.sslCertificateDomainName(String domainName)

System Property:

-Dmockserver.sslCertificateDomainName=...

Environment Variable:

MOCKSERVER_SSL_CERTIFICATE_DOMAIN_NAME=...

Property File:

mockserver.sslCertificateDomainName=...

Example:

-Dmockserver.sslCertificateDomainName="localhost"

The Subject Alternative Name (SAN) domain names for auto-generate TLS certificates as a comma separated list

Type: string Default: localhost

Java Code:

ConfigurationProperties.addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains)
or
ConfigurationProperties.clearSslSubjectAlternativeNameDomains()

System Property:

-Dmockserver.sslSubjectAlternativeNameDomains=...

Environment Variable:

MOCKSERVER_SSL_SUBJECT_ALTERNATIVE_NAME_DOMAINS=...

Property File:

mockserver.sslSubjectAlternativeNameDomains=...

Example:

-Dmockserver.sslSubjectAlternativeNameDomains="localhost,www.foo.bar"

The Subject Alternative Name (SAN) IP addresses for auto-generate TLS certificates as a comma separated list

Type: string Default: 127.0.0.1,0.0.0.0

Java Code:

ConfigurationProperties.addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps)
or
ConfigurationProperties.clearSslSubjectAlternativeNameIps()

System Property:

-Dmockserver.sslSubjectAlternativeNameIps=...

Environment Variable:

MOCKSERVER_SSL_SUBJECT_ALTERNATIVE_NAME_IPS=...

Property File:

mockserver.sslSubjectAlternativeNameIps=...

Example:

-Dmockserver.sslSubjectAlternativeNameIps="127.0.0.1,0.0.0.0"

Fixed (i.e. Custom) Inbound Certificate Authority X.509 & Private Key

Location of custom file for Certificate Authority for TLS, the private key must be a PKCS#8 or PKCS#1 PEM file and must match the TLS Certificate Authority X.509 Certificate.

To convert a PKCS#1 PEM file (i.e. default for Bouncy Castle) to a PKCS#8 PEM file the following command can be used: openssl pkcs8 -topk8 -inform PEM -in private_key_PKCS_1.pem -out private_key_PKCS_8.pem -nocrypt

Type: string Default: null

Java Code:

ConfigurationProperties.certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey)

System Property:

-Dmockserver.certificateAuthorityPrivateKey=...

Environment Variable:

MOCKSERVER_CERTIFICATE_AUTHORITY_PRIVATE_KEY=...

Property File:

mockserver.certificateAuthorityPrivateKey=...

Example:

-Dmockserver.certificateAuthorityPrivateKey="/some/existing/path"

Location of custom file for Certificate Authority for TLS, the certificate must be a X.509 PEM file and must match the TLS Certificate Authority Private Key.

Type: string Default: null

Java Code:

ConfigurationProperties.certificateAuthorityCertificate(String certificateAuthorityCertificate)

System Property:

-Dmockserver.certificateAuthorityCertificate=...

Environment Variable:

MOCKSERVER_CERTIFICATE_AUTHORITY_X509_CERTIFICATE=...

Property File:

mockserver.certificateAuthorityCertificate=...

Example:

-Dmockserver.certificateAuthorityCertificate="/some/existing/path"

Fixed (i.e. Custom) Inbound Private Key & X.509

File system path or classpath location of a fixed custom private key for TLS connections into MockServer.

The private key must be a PKCS#8 or PKCS#1 PEM file and must be the private key corresponding to the x509CertificatePath X.509 (public key) configuration.

The certificateAuthorityCertificate configuration must be the Certificate Authority for the corresponding X.509 certificate (i.e. able to valid its signature), see: x509CertificatePath.

To convert a PKCS#1 (i.e. default for Bouncy Castle) to a PKCS#8 the following command can be used: openssl pkcs8 -topk8 -inform PEM -in private_key_PKCS_1.pem -out private_key_PKCS_8.pem -nocrypt

This configuration will be ignored unless x509CertificatePath is also set.

Type: string Default: null

Java Code:

ConfigurationProperties.privateKeyPath(String privateKeyPath)

System Property:

-Dmockserver.privateKeyPath=...

Environment Variable:

MOCKSERVER_TLS_PRIVATE_KEY_PATH=...

Property File:

mockserver.privateKeyPath=...

Example:

-Dmockserver.privateKeyPath="/some/existing/path"

File system path or classpath location of a fixed custom X.509 Certificate for TLS connections into MockServer

The certificate must be a X.509 PEM file and must be the public key corresponding to the privateKeyPath private key configuration.

The certificateAuthorityCertificate configuration must be the Certificate Authority for this certificate (i.e. able to valid its signature).

This configuration will be ignored unless privateKeyPath is also set.

Type: string Default: null

Java Code:

ConfigurationProperties.x509CertificatePath(String x509CertificatePath)

System Property:

-Dmockserver.x509CertificatePath=...

Environment Variable:

MOCKSERVER_TLS_X509_CERTIFICATE_PATH=...

Property File:

mockserver.x509CertificatePath=...

Example:

-Dmockserver.x509CertificatePath="/some/existing/path"

Inbound mTLS Client Authentication (for Received Requests)

Require mTLS (also called client authentication and two-way TLS) for all TLS connections / HTTPS requests to MockServer

Type: boolean Default: false

Java Code:

ConfigurationProperties.tlsMutualAuthenticationRequired(boolean enable)

System Property:

-Dmockserver.tlsMutualAuthenticationRequired=...

Environment Variable:

MOCKSERVER_TLS_MUTUAL_AUTHENTICATION_REQUIRED=...

Property File:

mockserver.tlsMutualAuthenticationRequired=...

Example:

-Dmockserver.tlsMutualAuthenticationRequired="true"

File system path or classpath location of custom mTLS (TLS client authentication) X.509 Certificate Chain for Trusting (i.e. signature verification of) Client X.509 Certificates, the certificate chain must be a X.509 PEM file.

This certificate chain will be used if MockServer performs mTLS (client authentication) for inbound TLS connections because tlsMutualAuthenticationRequired is enabled

This configuration property is also used for MockServerClient to trust outbound TLS X.509 certificates i.e. TLS connections to MockServer

Type: string Default: null

Java Code:

ConfigurationProperties.tlsMutualAuthenticationCertificateChain(String certificateChain)

System Property:

-Dmockserver.tlsMutualAuthenticationCertificateChain=...

Environment Variable:

MOCKSERVER_TLS_MUTUAL_AUTHENTICATION_CERTIFICATE_CHAIN=...

Property File:

mockserver.tlsMutualAuthenticationCertificateChain=...

Example:

-Dmockserver.tlsMutualAuthenticationCertificateChain="/some/existing/path"


 

Outbound Client TLS/mTLS (for Forwarded or Proxied Requests)

Configure trusted set of certificates for forwarded or proxied requests (i.e. TLS connections out of MockServer).

MockServer will only be able to establish a TLS connection to endpoints that have a trusted X.509 certificate according to the trust manager type, as follows:

  • ANY - Insecure will trust all X.509 certificates and not perform host name verification.
  • JVM - Will trust all X.509 certificates trust by the JVM.
  • CUSTOM - Will trust all X.509 certificates specified in forwardProxyTLSCustomTrustX509Certificates configuration value.

Type: string Default: ANY

Java Code:

ConfigurationProperties.forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType)

System Property:

-Dmockserver.forwardProxyTLSX509CertificatesTrustManagerType=...

Environment Variable:

MOCKSERVER_FORWARD_PROXY_TLS_X509_CERTIFICATES_TRUST_MANAGER_TYPE=...

Property File:

mockserver.forwardProxyTLSX509CertificatesTrustManagerType=...

Example:

-Dmockserver.forwardProxyTLSX509CertificatesTrustManagerType="CUSTOM"

Fixed (i.e. Custom) Outbound CA X.509, Private Key & X.509

File system path or classpath location of custom file for trusted X.509 Certificate Authority roots for forwarded or proxied requests (i.e. TLS connections out of MockServer), the certificate chain must be a X.509 PEM file.

MockServer will only be able to establish a TLS connection to endpoints that have an X.509 certificate chain that is signed by one of the provided custom certificates, i.e. where a path can be established from the endpoints X.509 certificate to one or more of the custom X.509 certificates provided.

This configuration only take effect if forwardProxyTLSX509CertificatesTrustManagerType is configured as CUSTOM otherwise this value is ignored.

Type: string Default: null

Java Code:

ConfigurationProperties.forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates)

System Property:

-Dmockserver.forwardProxyTLSCustomTrustX509Certificates=...

Environment Variable:

MOCKSERVER_FORWARD_PROXY_TLS_CUSTOM_TRUST_X509_CERTIFICATES=...

Property File:

mockserver.forwardProxyTLSCustomTrustX509Certificates=...

Example:

-Dmockserver.forwardProxyTLSCustomTrustX509Certificates="/some/existing/path"

File system path or classpath location of custom Private Key for forwarded or proxied requests (i.e. TLS connections out of MockServer), the private key must be a PKCS#8 or PKCS#1 PEM file

To convert a PKCS#1 (i.e. default for Bouncy Castle) to a PKCS#8 the following command can be used: openssl pkcs8 -topk8 -inform PEM -in private_key_PKCS_1.pem -out private_key_PKCS_8.pem -nocrypt

This private key will be used if MockServer needs to perform mTLS (client authentication) for outbound TLS connections.

Type: string Default: null

Java Code:

ConfigurationProperties.forwardProxyPrivateKey(String privateKey)

System Property:

-Dmockserver.forwardProxyPrivateKey=...

Environment Variable:

MOCKSERVER_FORWARD_PROXY_TLS_PRIVATE_KEY=...

Property File:

mockserver.forwardProxyPrivateKey=...

Example:

-Dmockserver.forwardProxyPrivateKey="/some/existing/path"

File system path or classpath location of custom X.509 Certificate Chain for forwarded or proxied requests (i.e. TLS connections out of MockServer), the certificates must be a X.509 PEM file

This certificate chain will be used if MockServer needs to perform mTLS (client authentication) for outbound TLS connections.

Type: string Default: null

Java Code:

ConfigurationProperties.forwardProxyCertificateChain(String certificateChain)

System Property:

-Dmockserver.forwardProxyCertificateChain=...

Environment Variable:

MOCKSERVER_FORWARD_PROXY_TLS_X509_CERTIFICATE_CHAIN=...

Property File:

mockserver.forwardProxyCertificateChain=...

Example:

-Dmockserver.forwardProxyCertificateChain="/some/existing/path"
 

MockServer Client

File system path or classpath location of custom mTLS (TLS client authentication) X.509 Certificate Chain for Trusting (i.e. signature verification of) MockServer X.509 Certificates, the certificate chain must be a X.509 PEM file. This certificate chain will only be used if MockServerClient performs TLS to calls to MockServer.

This settings is particularly used when connecting to MockServer via a load-balancer or other TLS terminating network infrastructure with its own X.509 Certificate.

This configuration property is also used for MockServer to trust inbound mTLS client authentication X.509 certificates

Type: string Default: null

Java Code:

ConfigurationProperties.tlsMutualAuthenticationCertificateChain(String certificateChain)

System Property:

-Dmockserver.tlsMutualAuthenticationCertificateChain=...

Environment Variable:

MOCKSERVER_TLS_MUTUAL_AUTHENTICATION_CERTIFICATE_CHAIN=...

Property File:

mockserver.tlsMutualAuthenticationCertificateChain=...

Example:

-Dmockserver.tlsMutualAuthenticationCertificateChain="/some/existing/path"