001/*
002 * Copyright 2026 The Apache Software Foundation.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.apache.wiki.http.filter;
017
018import jakarta.servlet.Filter;
019import jakarta.servlet.FilterChain;
020import jakarta.servlet.FilterConfig;
021import jakarta.servlet.ServletException;
022import jakarta.servlet.ServletRequest;
023import jakarta.servlet.ServletResponse;
024import jakarta.servlet.http.HttpServletRequest;
025import java.io.IOException;
026import java.util.ArrayList;
027import java.util.HashSet;
028import java.util.List;
029import java.util.Set;
030import org.apache.commons.lang3.StringUtils;
031import org.apache.commons.net.util.SubnetUtils;
032import org.slf4j.Logger;
033import org.slf4j.LoggerFactory;
034
035/**
036 * see JSPWIKI-1289 and JSPWIKI-1294
037 *
038 * This can be configured either via web.xml using the init parameters
039 * (trustedProxies, allowedHosts) or in jspwiki-custom.properties
040 * (forwarded.trustedProxies and forwarded.allowedHosts).
041 *
042 * Used for providing security filtering for when jspwiki is behind a reverse
043 * proxy and providing some security checks on inbound http headers.
044 *
045 * Trust Proxies can either be ip addresses, ip address range via CIDR notation,
046 * or hostnames. This would be the ip address/hostnames of your reverse proxy
047 * (httpd/nginx/etc)
048 *
049 * Allowed Hosts is the public facing URL/hostname. i.e. wiki.apache.org or
050 * whatever.
051 *
052 * If both checks do not pass, inbound http headers related to forwarded by are
053 * dropped from further processing.
054 * 
055 * If neither is defined, it will default to a secure default setting, meaning
056 * all x forwarded by headers are dropped/ignored
057 *
058 * @since 3.0.1, 2.12.6
059 */
060public class ForwardedHeaderFilter implements Filter {
061
062    private static final Logger LOG = LoggerFactory.getLogger(ForwardedHeaderFilter.class);
063    /**
064     * Peers whose X-Forwarded-* we believe. Empty => trust nobody, strip
065     * everything.
066     */
067    private List<String> trustedProxies = new ArrayList<>();
068    /**
069     * Acceptable host[:port] values. Empty => only the container's own server
070     * name.
071     */
072    private Set<String> allowedHosts = new HashSet<>();
073
074    @Override
075    public void init(final FilterConfig filterConfig) {
076        final String proxies = FilterOperations.initValue(filterConfig, "trustedProxies", "forwarded.trustedProxies");
077        final String hosts = FilterOperations.initValue(filterConfig, "allowedHosts", "forwarded.allowedHosts");
078        // parse comma-separated; proxies as regex on remoteAddr, hosts lowercased literal
079        if (proxies != null) {
080            for (String s : proxies.split("\\,")) {
081                s = s.trim();
082                if (s.length() > 0) {
083                    trustedProxies.add((s));
084                }
085            }
086        }
087        if (hosts != null) {
088            for (String s : hosts.split("\\,")) {
089                s = s.trim();
090                if (s.length() > 0) {
091                    allowedHosts.add(s);
092                }
093            }
094        }
095    }
096
097    /**
098     * Returns whether the given address matches an entry of the
099     * {@value #PROP_TRUSTED_PROXIES} system property.
100     *
101     * @param addr address to check.
102     * @return {@code true} if the address is a trusted proxy, {@code false}
103     * otherwise.
104     */
105    boolean isTrustedProxy(final String addr, final String originalHostHeader) {
106        LOG.trace("isTrustedProxy " + addr + "," + originalHostHeader);
107        if (trustedProxies.isEmpty() || allowedHosts.isEmpty()) {
108            LOG.info("web.xml configuration has no trustedProxies or allowedHosts set, meaning we are not behind a reverse proxy. all requests will not honor x-forwarded-by headers");
109            return false;
110        }
111        if (StringUtils.isEmpty(addr)) {
112            LOG.info("Request does not contain a Remote Address header that is a trust proxy, denying access to X-Forwarded-By headers");
113            return false;
114        }
115        boolean proxyCheck = false;
116        for (final String entry : trustedProxies) {
117            if (entry.indexOf('/') >= 0) {
118                try {
119                    if (new SubnetUtils(entry).getInfo().isInRange(addr)) {
120                        LOG.info("Request has Remote Address header that is a trust proxy via CIDR notation, allowing access to X-Forwarded-By headers");
121                        proxyCheck = true;
122                        break;
123                    }
124                } catch (final IllegalArgumentException e) {
125                    LOG.warn("ignoring invalid {} entry: {}", "trustedProxies", entry);
126                }
127            } else if (entry.equalsIgnoreCase(addr)) {
128                LOG.info("Request has Remote Address header that is a trust proxy via hostname match, allowing access to X-Forwarded-By headers");
129                proxyCheck = true;
130                break;
131            }
132        }
133        boolean hostCheck = false;
134        for (String host : allowedHosts) {
135            if (host.equalsIgnoreCase(originalHostHeader)) {
136                LOG.info("Request has an allowed X-Forwarded-Host via hostname match, allowing access to X-Forwarded-By headers");
137                hostCheck = true;
138            }
139        }
140        if (!hostCheck) {
141            LOG.warn("Request does not have an allowed X-Forwarded-Host via hostname match, denying access to X-Forwarded-By headers");
142        }
143        if (!proxyCheck) {
144            LOG.warn("Request does not have a Remote Address header that is a trust proxy, denying access to X-Forwarded-By headers");
145        }
146        return hostCheck && proxyCheck;
147    }
148
149    @Override
150    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
151            throws IOException, ServletException {
152
153        if (request instanceof HttpServletRequest req) {
154            String remoteAddr = req.getRemoteAddr();
155            String forwardedHost = req.getHeader("X-Forwarded-Host");
156            chain.doFilter(new ForwardedRequest(req, isTrustedProxy(
157                    remoteAddr,
158                    forwardedHost)), response);
159        } else {
160            LOG.warn("filter request does not extend from HttpServletRequest and thus all forwarded by headers will process unchecked!" + request.getClass().getCanonicalName());
161            chain.doFilter(request, response);
162        }
163    }
164
165}