|
| 1 | +/* |
| 2 | + * Copyright 2002-2023 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.springframework.web.util; |
| 18 | + |
| 19 | +import java.net.InetSocketAddress; |
| 20 | +import java.net.URI; |
| 21 | +import java.util.regex.Matcher; |
| 22 | +import java.util.regex.Pattern; |
| 23 | + |
| 24 | +import org.springframework.http.HttpHeaders; |
| 25 | +import org.springframework.lang.Nullable; |
| 26 | +import org.springframework.util.StringUtils; |
| 27 | + |
| 28 | + |
| 29 | +/** |
| 30 | + * Utility class to assist with processing "Forwarded" and "X-Forwarded-*" headers. |
| 31 | + * |
| 32 | + * <p><strong>Note:</strong>There are security considerations surrounding the use |
| 33 | + * of forwarded headers. Those should not be used unless the application is |
| 34 | + * behind a trusted proxy that inserts them and also explicitly removes any such |
| 35 | + * headers coming from an external source. |
| 36 | + * |
| 37 | + * <p>In most cases, should not use this class directly but rely on |
| 38 | + * {@link org.springframework.web.filter.ForwardedHeaderFilter} for Spring MVC, or |
| 39 | + * {@link org.springframework.web.server.adapter.ForwardedHeaderTransformer} in |
| 40 | + * order to extract the information from them as early as possible, and discard |
| 41 | + * such headers. Underlying servers such as Tomcat, Jetty, Reactor Netty, also |
| 42 | + * provides options to handle forwarded headers even earlier. |
| 43 | + * |
| 44 | + * @author Rossen Stoyanchev |
| 45 | + * @since 6.1 |
| 46 | + */ |
| 47 | +public abstract class ForwardedHeaderUtils { |
| 48 | + |
| 49 | + private static final String FORWARDED_VALUE = "\"?([^;,\"]+)\"?"; |
| 50 | + |
| 51 | + private static final Pattern FORWARDED_HOST_PATTERN = Pattern.compile("(?i:host)=" + FORWARDED_VALUE); |
| 52 | + |
| 53 | + private static final Pattern FORWARDED_PROTO_PATTERN = Pattern.compile("(?i:proto)=" + FORWARDED_VALUE); |
| 54 | + |
| 55 | + private static final Pattern FORWARDED_FOR_PATTERN = Pattern.compile("(?i:for)=" + FORWARDED_VALUE); |
| 56 | + |
| 57 | + |
| 58 | + /** |
| 59 | + * Adapt the scheme+host+port of the given {@link URI} from the "Forwarded" header, |
| 60 | + * see <a href="https://tools.ietf.org/html/rfc7239">RFC 7239</a>, or |
| 61 | + * "X-Forwarded-Host", "X-Forwarded-Port", and "X-Forwarded-Proto" if "Forwarded" |
| 62 | + * is not present. |
| 63 | + * @param headers the HTTP headers to consider |
| 64 | + * @return a {@link UriComponentsBuilder} that reflects the request URI and |
| 65 | + * additional updates from forwarded headers |
| 66 | + */ |
| 67 | + public static UriComponentsBuilder adaptFromForwardedHeaders(URI uri, HttpHeaders headers) { |
| 68 | + UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUri(uri); |
| 69 | + try { |
| 70 | + String forwardedHeader = headers.getFirst("Forwarded"); |
| 71 | + if (StringUtils.hasText(forwardedHeader)) { |
| 72 | + Matcher matcher = FORWARDED_PROTO_PATTERN.matcher(forwardedHeader); |
| 73 | + if (matcher.find()) { |
| 74 | + uriComponentsBuilder.scheme(matcher.group(1).trim()); |
| 75 | + uriComponentsBuilder.port(null); |
| 76 | + } |
| 77 | + else if (isForwardedSslOn(headers)) { |
| 78 | + uriComponentsBuilder.scheme("https"); |
| 79 | + uriComponentsBuilder.port(null); |
| 80 | + } |
| 81 | + matcher = FORWARDED_HOST_PATTERN.matcher(forwardedHeader); |
| 82 | + if (matcher.find()) { |
| 83 | + adaptForwardedHost(uriComponentsBuilder, matcher.group(1).trim()); |
| 84 | + } |
| 85 | + } |
| 86 | + else { |
| 87 | + String protocolHeader = headers.getFirst("X-Forwarded-Proto"); |
| 88 | + if (StringUtils.hasText(protocolHeader)) { |
| 89 | + uriComponentsBuilder.scheme(StringUtils.tokenizeToStringArray(protocolHeader, ",")[0]); |
| 90 | + uriComponentsBuilder.port(null); |
| 91 | + } |
| 92 | + else if (isForwardedSslOn(headers)) { |
| 93 | + uriComponentsBuilder.scheme("https"); |
| 94 | + uriComponentsBuilder.port(null); |
| 95 | + } |
| 96 | + String hostHeader = headers.getFirst("X-Forwarded-Host"); |
| 97 | + if (StringUtils.hasText(hostHeader)) { |
| 98 | + adaptForwardedHost(uriComponentsBuilder, StringUtils.tokenizeToStringArray(hostHeader, ",")[0]); |
| 99 | + } |
| 100 | + String portHeader = headers.getFirst("X-Forwarded-Port"); |
| 101 | + if (StringUtils.hasText(portHeader)) { |
| 102 | + uriComponentsBuilder.port(Integer.parseInt(StringUtils.tokenizeToStringArray(portHeader, ",")[0])); |
| 103 | + } |
| 104 | + } |
| 105 | + } |
| 106 | + catch (NumberFormatException ex) { |
| 107 | + throw new IllegalArgumentException("Failed to parse a port from \"forwarded\"-type headers. " + |
| 108 | + "If not behind a trusted proxy, consider using ForwardedHeaderFilter " + |
| 109 | + "with the removeOnly=true. Request headers: " + headers); |
| 110 | + } |
| 111 | + |
| 112 | + uriComponentsBuilder.resetPortIfDefaultForScheme(); |
| 113 | + |
| 114 | + return uriComponentsBuilder; |
| 115 | + } |
| 116 | + |
| 117 | + private static boolean isForwardedSslOn(HttpHeaders headers) { |
| 118 | + String forwardedSsl = headers.getFirst("X-Forwarded-Ssl"); |
| 119 | + return StringUtils.hasText(forwardedSsl) && forwardedSsl.equalsIgnoreCase("on"); |
| 120 | + } |
| 121 | + |
| 122 | + private static void adaptForwardedHost(UriComponentsBuilder uriComponentsBuilder, String rawValue) { |
| 123 | + int portSeparatorIdx = rawValue.lastIndexOf(':'); |
| 124 | + int squareBracketIdx = rawValue.lastIndexOf(']'); |
| 125 | + if (portSeparatorIdx > squareBracketIdx) { |
| 126 | + if (squareBracketIdx == -1 && rawValue.indexOf(':') != portSeparatorIdx) { |
| 127 | + throw new IllegalArgumentException("Invalid IPv4 address: " + rawValue); |
| 128 | + } |
| 129 | + uriComponentsBuilder.host(rawValue.substring(0, portSeparatorIdx)); |
| 130 | + uriComponentsBuilder.port(Integer.parseInt(rawValue, portSeparatorIdx + 1, rawValue.length(), 10)); |
| 131 | + } |
| 132 | + else { |
| 133 | + uriComponentsBuilder.host(rawValue); |
| 134 | + uriComponentsBuilder.port(null); |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + /** |
| 139 | + * Parse the first "Forwarded: for=..." or "X-Forwarded-For" header value to |
| 140 | + * an {@code InetSocketAddress} representing the address of the client. |
| 141 | + * @param uri the request URI |
| 142 | + * @param headers the request headers that may contain forwarded headers |
| 143 | + * @param remoteAddress the current remoteAddress |
| 144 | + * @return an {@code InetSocketAddress} with the extracted host and port, or |
| 145 | + * {@code null} if the headers are not present. |
| 146 | + * @see <a href="https://tools.ietf.org/html/rfc7239#section-5.2">RFC 7239, Section 5.2</a> |
| 147 | + */ |
| 148 | + @Nullable |
| 149 | + public static InetSocketAddress parseForwardedFor( |
| 150 | + URI uri, HttpHeaders headers, @Nullable InetSocketAddress remoteAddress) { |
| 151 | + |
| 152 | + int port = (remoteAddress != null ? |
| 153 | + remoteAddress.getPort() : "https".equals(uri.getScheme()) ? 443 : 80); |
| 154 | + |
| 155 | + String forwardedHeader = headers.getFirst("Forwarded"); |
| 156 | + if (StringUtils.hasText(forwardedHeader)) { |
| 157 | + String forwardedToUse = StringUtils.tokenizeToStringArray(forwardedHeader, ",")[0]; |
| 158 | + Matcher matcher = FORWARDED_FOR_PATTERN.matcher(forwardedToUse); |
| 159 | + if (matcher.find()) { |
| 160 | + String value = matcher.group(1).trim(); |
| 161 | + String host = value; |
| 162 | + int portSeparatorIdx = value.lastIndexOf(':'); |
| 163 | + int squareBracketIdx = value.lastIndexOf(']'); |
| 164 | + if (portSeparatorIdx > squareBracketIdx) { |
| 165 | + if (squareBracketIdx == -1 && value.indexOf(':') != portSeparatorIdx) { |
| 166 | + throw new IllegalArgumentException("Invalid IPv4 address: " + value); |
| 167 | + } |
| 168 | + host = value.substring(0, portSeparatorIdx); |
| 169 | + try { |
| 170 | + port = Integer.parseInt(value, portSeparatorIdx + 1, value.length(), 10); |
| 171 | + } |
| 172 | + catch (NumberFormatException ex) { |
| 173 | + throw new IllegalArgumentException( |
| 174 | + "Failed to parse a port from \"forwarded\"-type header value: " + value); |
| 175 | + } |
| 176 | + } |
| 177 | + return InetSocketAddress.createUnresolved(host, port); |
| 178 | + } |
| 179 | + } |
| 180 | + |
| 181 | + String forHeader = headers.getFirst("X-Forwarded-For"); |
| 182 | + if (StringUtils.hasText(forHeader)) { |
| 183 | + String host = StringUtils.tokenizeToStringArray(forHeader, ",")[0]; |
| 184 | + return InetSocketAddress.createUnresolved(host, port); |
| 185 | + } |
| 186 | + |
| 187 | + return null; |
| 188 | + } |
| 189 | + |
| 190 | +} |
0 commit comments