|
| 1 | +/* |
| 2 | + * Copyright 2026 Google LLC |
| 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 | + * http://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 com.google.adk.web.config; |
| 18 | + |
| 19 | +import com.google.common.base.Ascii; |
| 20 | +import com.google.common.base.CharMatcher; |
| 21 | +import com.google.common.collect.ImmutableSet; |
| 22 | +import com.google.common.net.HostAndPort; |
| 23 | +import com.google.common.net.InetAddresses; |
| 24 | +import jakarta.servlet.FilterChain; |
| 25 | +import jakarta.servlet.ServletException; |
| 26 | +import jakarta.servlet.ServletRequest; |
| 27 | +import jakarta.servlet.ServletRequestWrapper; |
| 28 | +import jakarta.servlet.http.HttpServletRequest; |
| 29 | +import jakarta.servlet.http.HttpServletResponse; |
| 30 | +import java.io.IOException; |
| 31 | +import java.util.List; |
| 32 | +import org.jspecify.annotations.Nullable; |
| 33 | +import org.springframework.http.HttpHeaders; |
| 34 | +import org.springframework.web.filter.OncePerRequestFilter; |
| 35 | +import org.springframework.web.util.UriComponentsBuilder; |
| 36 | + |
| 37 | +/** |
| 38 | + * Rejects requests from a page that resolved its own domain to this machine (DNS rebinding): a |
| 39 | + * foreign {@code Host} on a server bound to loopback, and a foreign {@code Origin} on a request |
| 40 | + * that arrived over loopback. Listed origins and their hosts pass, and {@code *} turns both checks |
| 41 | + * off. |
| 42 | + */ |
| 43 | +final class OriginGuardFilter extends OncePerRequestFilter { |
| 44 | + |
| 45 | + private final boolean allowAll; |
| 46 | + private final ImmutableSet<String> origins; |
| 47 | + private final ImmutableSet<String> hosts; |
| 48 | + private final boolean boundToLoopback; |
| 49 | + |
| 50 | + OriginGuardFilter(List<String> allowedOrigins, String bindAddress) { |
| 51 | + this.allowAll = allowedOrigins.contains("*"); |
| 52 | + this.origins = |
| 53 | + allowedOrigins.stream() |
| 54 | + .map(OriginGuardFilter::normalizeOrigin) |
| 55 | + .collect(ImmutableSet.toImmutableSet()); |
| 56 | + this.hosts = |
| 57 | + origins.stream() |
| 58 | + .map(OriginGuardFilter::originHost) |
| 59 | + .filter(host -> !host.isEmpty()) |
| 60 | + .collect(ImmutableSet.toImmutableSet()); |
| 61 | + this.boundToLoopback = isLoopback(bindAddress); |
| 62 | + } |
| 63 | + |
| 64 | + @Override |
| 65 | + protected void doFilterInternal( |
| 66 | + HttpServletRequest request, HttpServletResponse response, FilterChain chain) |
| 67 | + throws ServletException, IOException { |
| 68 | + if (allowAll) { |
| 69 | + chain.doFilter(request, response); |
| 70 | + return; |
| 71 | + } |
| 72 | + // ForwardedHeaderFilter's wrapper takes the local address from headers a page can set. |
| 73 | + HttpServletRequest connection = unwrap(request); |
| 74 | + if (boundToLoopback && isForeignHost(connection)) { |
| 75 | + reject(response, "host not allowed"); |
| 76 | + return; |
| 77 | + } |
| 78 | + String origin = request.getHeader(HttpHeaders.ORIGIN); |
| 79 | + if (origin != null |
| 80 | + && !origins.contains(normalizeOrigin(origin)) |
| 81 | + && isLoopback(connection.getLocalAddr()) |
| 82 | + && !isLoopback(originHost(origin))) { |
| 83 | + // A rebound page's own domain fills Host and Origin alike, so same-origin checks pass it. |
| 84 | + reject(response, "origin not allowed"); |
| 85 | + return; |
| 86 | + } |
| 87 | + chain.doFilter(request, response); |
| 88 | + } |
| 89 | + |
| 90 | + /** Whether the real Host, which a page cannot set, names neither loopback nor a listed host. */ |
| 91 | + private boolean isForeignHost(HttpServletRequest connection) { |
| 92 | + // HTTP/2 sends the authority as the server name rather than a Host header. |
| 93 | + String host = connection.getHeader(HttpHeaders.HOST); |
| 94 | + if (host == null) { |
| 95 | + host = connection.getServerName(); |
| 96 | + } |
| 97 | + return !isLoopback(host) && !hosts.contains(bareHost(host)); |
| 98 | + } |
| 99 | + |
| 100 | + private static HttpServletRequest unwrap(HttpServletRequest request) { |
| 101 | + ServletRequest current = request; |
| 102 | + while (current instanceof ServletRequestWrapper wrapper) { |
| 103 | + current = wrapper.getRequest(); |
| 104 | + } |
| 105 | + return current instanceof HttpServletRequest connection ? connection : request; |
| 106 | + } |
| 107 | + |
| 108 | + private static void reject(HttpServletResponse response, String reason) throws IOException { |
| 109 | + response.setStatus(HttpServletResponse.SC_FORBIDDEN); |
| 110 | + response.setContentType("text/plain"); |
| 111 | + response.getWriter().write("Forbidden: " + reason); |
| 112 | + } |
| 113 | + |
| 114 | + /** Whether host, with or without a port, is localhost or a loopback IP; never queries DNS. */ |
| 115 | + private static boolean isLoopback(@Nullable String host) { |
| 116 | + String bare = bareHost(host); |
| 117 | + return bare.equals("localhost") |
| 118 | + || (InetAddresses.isInetAddress(bare) && InetAddresses.forString(bare).isLoopbackAddress()); |
| 119 | + } |
| 120 | + |
| 121 | + /** Lowercases host and strips its port, brackets and trailing dot; empty if unparsable. */ |
| 122 | + private static String bareHost(@Nullable String host) { |
| 123 | + if (host == null) { |
| 124 | + return ""; |
| 125 | + } |
| 126 | + try { |
| 127 | + String bare = HostAndPort.fromString(host.trim()).getHost(); |
| 128 | + return Ascii.toLowerCase(CharMatcher.is('.').trimTrailingFrom(bare)); |
| 129 | + } catch (IllegalArgumentException e) { |
| 130 | + return ""; |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + private static String originHost(String origin) { |
| 135 | + try { |
| 136 | + return bareHost(UriComponentsBuilder.fromUriString(origin.trim()).build().getHost()); |
| 137 | + } catch (IllegalArgumentException e) { |
| 138 | + return ""; |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + private static String normalizeOrigin(String origin) { |
| 143 | + return Ascii.toLowerCase(CharMatcher.is('/').trimTrailingFrom(origin.trim())); |
| 144 | + } |
| 145 | +} |
0 commit comments