diff --git a/server/conf/mirth.properties b/server/conf/mirth.properties index 4c9894277..f37fb9d78 100644 --- a/server/conf/mirth.properties +++ b/server/conf/mirth.properties @@ -54,6 +54,12 @@ server.api.accesscontrolallowheaders = Content-Type server.api.accesscontrolexposeheaders = server.api.accesscontrolmaxage = +# Reverse proxies whose X-Forwarded-For, X-Forwarded-Proto and Forwarded headers are trusted. +# Comma separated addresses, CIDR blocks (10.0.0.0/8) or ranges. Leave blank to ignore these headers. +# The first X-Forwarded-For entry is used as the client address, so the proxy must replace that +# header rather than append to it (nginx: proxy_set_header X-Forwarded-For $remote_addr;). +server.api.trustedproxies = + # Password for the admin user, only applied when the database is first created. # If blank, a random password is generated and written to the log once on first startup. server.initialadminpassword = diff --git a/server/src/main/java/com/mirth/connect/server/MirthWebServer.java b/server/src/main/java/com/mirth/connect/server/MirthWebServer.java index b2cbf8d8f..f6eb5618c 100644 --- a/server/src/main/java/com/mirth/connect/server/MirthWebServer.java +++ b/server/src/main/java/com/mirth/connect/server/MirthWebServer.java @@ -15,6 +15,7 @@ import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; +import java.net.InetSocketAddress; import java.nio.file.Paths; import java.security.KeyStore; import java.sql.Connection; @@ -56,6 +57,7 @@ import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.server.Connector; +import org.eclipse.jetty.server.ForwardedRequestCustomizer; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.LowResourceMonitor; @@ -82,6 +84,7 @@ import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.util.InetAddressSet; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.webapp.Configuration; import org.eclipse.jetty.webapp.WebAppContext; @@ -153,6 +156,7 @@ public MirthWebServer(PropertiesConfiguration mirthProperties) throws Exception HttpConfiguration config = new HttpConfiguration(); config.setSendServerVersion(false); config.setSendXPoweredBy(false); + addTrustedProxyCustomizer(config, mirthProperties); connector = new ServerConnector(this, new HttpConnectionFactory(config)); connector.setName(CONNECTOR); connector.setHost(mirthProperties.getString("http.host", "0.0.0.0")); @@ -402,6 +406,7 @@ private ServerConnector createSSLConnector(String name, PropertiesConfiguration config.addCustomizer(new SecureRequestCustomizer()); config.setSendServerVersion(false); config.setSendXPoweredBy(false); + addTrustedProxyCustomizer(config, mirthProperties); ServerConnector sslConnector = new ServerConnector(this, new SslConnectionFactory(contextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(config)); @@ -439,6 +444,41 @@ private ServerConnector createSSLConnector(String name, PropertiesConfiguration return sslConnector; } + /** + * Applies X-Forwarded-* and Forwarded headers only to requests whose connection comes from an + * address listed in "server.api.trustedproxies" (addresses, CIDR blocks or ranges, comma + * separated). If the property is blank, nothing is added and the headers are ignored, as before. + */ + static void addTrustedProxyCustomizer(HttpConfiguration config, PropertiesConfiguration mirthProperties) { + String[] proxies = StringUtils.split(mirthProperties.getString("server.api.trustedproxies", ""), ','); + if (proxies.length > 0) { + config.addCustomizer(new TrustedProxyCustomizer(proxies)); + } + } + + static class TrustedProxyCustomizer implements HttpConfiguration.Customizer { + private final InetAddressSet trusted = new InetAddressSet(); + private final ForwardedRequestCustomizer forwarded = new ForwardedRequestCustomizer(); + + TrustedProxyCustomizer(String[] proxies) { + for (String proxy : proxies) { + try { + trusted.add(proxy.trim()); + } catch (IllegalArgumentException e) { + LogManager.getLogger(MirthWebServer.class).error("Invalid value \"" + proxy.trim() + "\" in server.api.trustedproxies, expected an IP address, CIDR block or range. It will be ignored."); + } + } + } + + @Override + public void customize(Connector connector, HttpConfiguration config, Request request) { + InetSocketAddress peer = request.getHttpChannel().getEndPoint().getRemoteAddress(); + if (peer != null && trusted.test(peer.getAddress())) { + forwarded.customize(connector, config, request); + } + } + } + private ServletContextHandler createApiServletContextHandler(String contextPath, String baseAPI, boolean apiAllowHTTP, Version version, PropertiesConfiguration mirthProperties) { String apiPath = ""; Version apiVersion = version; diff --git a/server/src/test/java/com/mirth/connect/server/MirthWebServerTrustedProxyTest.java b/server/src/test/java/com/mirth/connect/server/MirthWebServerTrustedProxyTest.java new file mode 100644 index 000000000..3f776730c --- /dev/null +++ b/server/src/test/java/com/mirth/connect/server/MirthWebServerTrustedProxyTest.java @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: Open Integration Engine + +package com.mirth.connect.server; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.configuration2.PropertiesConfiguration; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.eclipse.jetty.server.HttpConfiguration; +import org.eclipse.jetty.server.HttpConnectionFactory; +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.server.handler.AbstractHandler; +import org.junit.After; +import org.junit.Test; + +import com.mirth.connect.client.core.PropertiesConfigurationUtil; + +/** + * Sends forwarded headers from 127.0.0.1 to a real Jetty connector configured by + * MirthWebServer.addTrustedProxyCustomizer, and checks what the request reports. + */ +public class MirthWebServerTrustedProxyTest { + + private Server server; + + @After + public void tearDown() throws Exception { + if (server != null) { + server.stop(); + server = null; + } + } + + @Test + // assert that forwarded headers are ignored when no proxy is configured + public void testBlankIgnoresForwardedHeaders() throws Exception { + assertEquals("127.0.0.1 false", sendForwardedRequest(null)); + assertEquals("127.0.0.1 false", sendForwardedRequest("")); + } + + @Test + // assert that forwarded headers are applied when the connection comes from a listed proxy + public void testTrustedPeerAppliesForwardedHeaders() throws Exception { + assertEquals("10.0.0.5 true", sendForwardedRequest("127.0.0.1")); + assertEquals("10.0.0.5 true", sendForwardedRequest(" 192.168.1.5, 127.0.0.0/8 ")); + } + + @Test + // assert that forwarded headers are ignored when the connection comes from an unlisted address + public void testUntrustedPeerIgnoresForwardedHeaders() throws Exception { + assertEquals("127.0.0.1 false", sendForwardedRequest("10.0.0.0/8")); + } + + @Test + // assert that an invalid entry is skipped instead of stopping the connector from starting + public void testInvalidEntryIsSkipped() throws Exception { + assertEquals("127.0.0.1 false", sendForwardedRequest("172.30.0.10x")); + assertEquals("127.0.0.1 false", sendForwardedRequest("proxy.example.com")); + assertEquals("10.0.0.5 true", sendForwardedRequest("172.30.0.10x, 127.0.0.1")); + } + + private String sendForwardedRequest(String trustedProxies) throws Exception { + PropertiesConfiguration mirthProperties = PropertiesConfigurationUtil.create(); + if (trustedProxies != null) { + mirthProperties.setProperty("server.api.trustedproxies", trustedProxies); + } + int port = startServer(mirthProperties); + + try (CloseableHttpClient client = HttpClients.createDefault()) { + HttpGet get = new HttpGet("http://127.0.0.1:" + port + "/"); + get.addHeader("X-Forwarded-For", "10.0.0.5"); + get.addHeader("X-Forwarded-Proto", "https"); + + try (CloseableHttpResponse response = client.execute(get)) { + return EntityUtils.toString(response.getEntity()); + } + } finally { + server.stop(); + server = null; + } + } + + private int startServer(PropertiesConfiguration mirthProperties) throws Exception { + server = new Server(); + + HttpConfiguration config = new HttpConfiguration(); + MirthWebServer.addTrustedProxyCustomizer(config, mirthProperties); + ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(config)); + connector.setHost("127.0.0.1"); + connector.setPort(0); + server.addConnector(connector); + + server.setHandler(new AbstractHandler() { + @Override + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { + baseRequest.setHandled(true); + response.setStatus(HttpServletResponse.SC_OK); + response.getWriter().print(request.getRemoteAddr() + " " + request.isSecure()); + } + }); + + server.start(); + return connector.getLocalPort(); + } +}