Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

4.x: Initial support for proxy protocol V1 and V2 #7829

Merged
merged 8 commits into from
Nov 20, 2023
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,22 @@ public void request(String method, String path, String protocol, String host, It
}
}

/**
* Write raw proxy protocol header before a request.
*
* @param header header to write
*/
public void writeProxyHeader(byte[] header) {
try {
if (socket == null) {
connect();
}
socket.getOutputStream().write(header);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}

/**
* Disconnect from server socket.
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Copyright (c) 2023 Oracle and/or its affiliates.
*
* 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 io.helidon.common.testing.junit5;

/**
* Utility class to decode hex strings.
*/
public final class HexStringDecoder {

private HexStringDecoder() {
}

/**
* Utility method to decode hex strings. For example, "\0x0D\0x0A\0x0D\0x0A" is decoded
* as a 4-byte array with hex values 0D 0A 0D 0A.
*
* @param s string to decode
* @return decoded string as byte array
*/
public static byte[] decodeHexString(String s) {
spericas marked this conversation as resolved.
Show resolved Hide resolved
if (s.isEmpty() || s.length() % 4 != 0) {
throw new IllegalArgumentException("Invalid hex string");
}
byte[] bytes = new byte[s.length() / 4];
for (int i = 0, j = 0; i < s.length(); i += 4) {
char c1 = s.charAt(i + 2);
byte b1 = (byte) (Character.isDigit(c1) ? c1 - '0' : c1 - 'A' + 10);
char c2 = s.charAt(i + 3);
byte b2 = (byte) (Character.isDigit(c2) ? c2 - '0' : c2 - 'A' + 10);
bytes[j++] = (byte) (((b1 << 4) & 0xF0) | (b2 & 0x0F));
}
return bytes;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@
import io.helidon.webserver.http2.spi.Http2SubProtocolSelector;
import io.helidon.webserver.spi.ServerConnection;

import static io.helidon.http.HeaderNames.X_FORWARDED_FOR;
import static io.helidon.http.HeaderNames.X_FORWARDED_PORT;
import static io.helidon.http.HeaderNames.X_HELIDON_CN;
import static io.helidon.http.http2.Http2Util.PREFACE_LENGTH;
import static java.lang.System.Logger.Level.DEBUG;
Expand Down Expand Up @@ -614,6 +616,19 @@ private void doHeaders(Semaphore requestSemaphore) {
ctx.remotePeer().tlsCertificates()
.flatMap(TlsUtils::parseCn)
.ifPresent(cn -> connectionHeaders.add(X_HELIDON_CN, cn));

// proxy protocol related headers X-Forwarded-For and X-Forwarded-Port
ctx.proxyProtocolData().ifPresent(proxyProtocolData -> {
String sourceAddress = proxyProtocolData.sourceAddress();
if (!sourceAddress.isEmpty()) {
connectionHeaders.add(X_FORWARDED_FOR, sourceAddress);
}
int sourcePort = proxyProtocolData.sourcePort();
if (sourcePort != -1) {
connectionHeaders.set(X_FORWARDED_PORT, sourcePort);
}
});

initConnectionHeaders = false;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import java.io.InputStream;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;

Expand All @@ -38,6 +39,7 @@
import io.helidon.http.media.ReadableEntity;
import io.helidon.webserver.ConnectionContext;
import io.helidon.webserver.ListenerContext;
import io.helidon.webserver.ProxyProtocolData;
import io.helidon.webserver.http.HttpSecurity;
import io.helidon.webserver.http.RoutingRequest;

Expand Down Expand Up @@ -220,6 +222,11 @@ public void streamFilter(UnaryOperator<InputStream> filterFunction) {
this.streamFilter = it -> filterFunction.apply(current.apply(it));
}

@Override
public Optional<ProxyProtocolData> proxyProtocolData() {
return ctx.proxyProtocolData();
}

private UriInfo createUriInfo() {
return ctx.listenerContext().config().requestedUriDiscoveryContext().uriInfo(remotePeer().address().toString(),
localPeer().address().toString(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/*
* Copyright (c) 2023 Oracle and/or its affiliates.
*
* 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 io.helidon.webserver.tests;

import io.helidon.common.testing.http.junit5.SocketHttpClient;
import io.helidon.http.HeaderNames;
import io.helidon.http.Method;
import io.helidon.http.Status;
import io.helidon.webserver.ProxyProtocolData;
import io.helidon.webserver.WebServerConfig;
import io.helidon.webserver.http.HttpRules;
import io.helidon.webserver.testing.junit5.ServerTest;
import io.helidon.webserver.testing.junit5.SetUpRoute;
import io.helidon.webserver.testing.junit5.SetUpServer;
import org.junit.jupiter.api.Test;

import static java.nio.charset.StandardCharsets.US_ASCII;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.MatcherAssert.assertThat;
import static io.helidon.common.testing.junit5.HexStringDecoder.decodeHexString;

@ServerTest
class ProxyProtocolTest {

static final String V2_PREFIX = "\0x0D\0x0A\0x0D\0x0A\0x00\0x0D\0x0A\0x51\0x55\0x49\0x54\0x0A";

private final SocketHttpClient socketHttpClient;

ProxyProtocolTest(SocketHttpClient socketHttpClient) {
this.socketHttpClient = socketHttpClient;
}

@SetUpServer
static void setupServer(WebServerConfig.Builder builder) {
builder.enableProxyProtocol(true);
}

@SetUpRoute
static void routing(HttpRules routing) {
routing.get("/", (req, res) -> {
ProxyProtocolData data = req.proxyProtocolData().orElse(null);
if (data != null
&& data.family() == ProxyProtocolData.Family.IPv4
&& data.protocol() == ProxyProtocolData.Protocol.TCP
&& data.sourceAddress().equals("192.168.0.1")
&& data.destAddress().equals("192.168.0.11")
&& data.sourcePort() == 56324
&& data.destPort() == 443
&& "192.168.0.1".equals(req.headers().first(HeaderNames.X_FORWARDED_FOR).orElse(null))
&& "56324".equals(req.headers().first(HeaderNames.X_FORWARDED_PORT).orElse(null))) {
res.status(Status.OK_200).send();
return;
}
res.status(Status.INTERNAL_SERVER_ERROR_500).send();
});
}

/**
* V1 encoding in this test was manually verified with Wireshark.
*/
@Test
void testProxyProtocolV1IPv4() {
socketHttpClient.writeProxyHeader("PROXY TCP4 192.168.0.1 192.168.0.11 56324 443\r\n".getBytes(US_ASCII));
String s = socketHttpClient.sendAndReceive(Method.GET, "");
assertThat(s, startsWith("HTTP/1.1 200 OK"));
}

/**
* V2 encoding in this test was manually verified with Wireshark.
*/
@Test
void testProxyProtocolV2IPv4() {
String header = V2_PREFIX
+ "\0x20\0x11\0x00\0x0C" // version, family/protocol, length
+ "\0xC0\0xA8\0x00\0x01" // 192.168.0.1
+ "\0xC0\0xA8\0x00\0x0B" // 192.168.0.11
+ "\0xDC\0x04" // 56324
+ "\0x01\0xBB"; // 443
socketHttpClient.writeProxyHeader(decodeHexString(header));
String s = socketHttpClient.sendAndReceive(Method.GET, "");
assertThat(s, startsWith("HTTP/1.1 200 OK"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package io.helidon.webserver;

import java.util.Optional;
import java.util.concurrent.ExecutorService;

import io.helidon.common.buffers.DataReader;
Expand Down Expand Up @@ -60,4 +61,14 @@ public interface ConnectionContext extends SocketContext {
* @return rouer
*/
Router router();

/**
* Proxy protocol header data.
*
* @return protocol header data if proxy protocol is enabled on socket
* @see ListenerConfig#enableProxyProtocol()
*/
default Optional<ProxyProtocolData> proxyProtocolData() {
return Optional.empty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Semaphore;

Expand Down Expand Up @@ -64,11 +65,13 @@ class ConnectionHandler implements InterruptableTask<Void>, ConnectionContext {
private final String serverChannelId;
private final Router router;
private final Tls tls;
private final ListenerConfig listenerConfig;

private ServerConnection connection;
private HelidonSocket helidonSocket;
private DataReader reader;
private SocketWriter writer;
private ProxyProtocolData proxyProtocolData;

ConnectionHandler(ListenerContext listenerContext,
Semaphore connectionSemaphore,
Expand All @@ -78,7 +81,8 @@ class ConnectionHandler implements InterruptableTask<Void>, ConnectionContext {
Socket socket,
String serverChannelId,
Router router,
Tls tls) {
Tls tls,
ListenerConfig listenerConfig) {
this.listenerContext = listenerContext;
this.connectionSemaphore = connectionSemaphore;
this.requestSemaphore = requestSemaphore;
Expand All @@ -89,6 +93,7 @@ class ConnectionHandler implements InterruptableTask<Void>, ConnectionContext {
this.serverChannelId = serverChannelId;
this.router = router;
this.tls = tls;
this.listenerConfig = listenerConfig;
}

@Override
Expand All @@ -100,6 +105,12 @@ public boolean canInterrupt() {
public final void run() {
String channelId = "0x" + HexFormat.of().toHexDigits(System.identityHashCode(socket));

// proxy protocol before SSL handshake
if (listenerConfig.enableProxyProtocol()) {
ProxyProtocolHandler handler = new ProxyProtocolHandler(socket, channelId);
proxyProtocolData = handler.get();
}

// handle SSL and init helidonSocket, reader and writer
try {
if (tls.enabled()) {
Expand Down Expand Up @@ -226,6 +237,11 @@ public Router router() {
return router;
}

@Override
public Optional<ProxyProtocolData> proxyProtocolData() {
return Optional.ofNullable(proxyProtocolData);
}

private ServerConnection identifyConnection() {
try {
reader.ensureAvailable();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,15 @@ interface ListenerConfigBlueprint {
*/
Optional<Context> listenerContext();

/**
* Enable support for proxy protocol for this socket.
spericas marked this conversation as resolved.
Show resolved Hide resolved
* Default is {@code false}.
*
* @return proxy support status
*/
@Option.Default("false")
boolean enableProxyProtocol();

/**
* Requested URI discovery context.
*
Expand Down
Loading