001/*
002    Licensed to the Apache Software Foundation (ASF) under one
003    or more contributor license agreements.  See the NOTICE file
004    distributed with this work for additional information
005    regarding copyright ownership.  The ASF licenses this file
006    to you under the Apache License, Version 2.0 (the
007    "License"); you may not use this file except in compliance
008    with the License.  You may obtain a copy of the License at
009
010       http://www.apache.org/licenses/LICENSE-2.0
011
012    Unless required by applicable law or agreed to in writing,
013    software distributed under the License is distributed on an
014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015    KIND, either express or implied.  See the License for the
016    specific language governing permissions and limitations
017    under the License.
018 */
019package org.apache.wiki.http.filter;
020
021import org.apache.logging.log4j.LogManager;
022import org.apache.logging.log4j.Logger;
023import org.apache.wiki.api.core.Engine;
024import org.apache.wiki.api.core.Session;
025import org.apache.wiki.api.spi.Wiki;
026
027import jakarta.servlet.Filter;
028import jakarta.servlet.FilterChain;
029import jakarta.servlet.FilterConfig;
030import jakarta.servlet.ServletException;
031import jakarta.servlet.ServletRequest;
032import jakarta.servlet.ServletResponse;
033import jakarta.servlet.http.HttpServletRequest;
034import jakarta.servlet.http.HttpServletResponse;
035import java.io.IOException;
036import java.util.Locale;
037
038
039/**
040 * CSRF protection Filter which uses the synchronizer token pattern – an anti-CSRF token is created and stored in the
041 * user session and in a hidden field on subsequent form submits. At every submit the server checks the token from the
042 * session matches the one submitted from the form.
043 */
044public class CsrfProtectionFilter implements Filter {
045
046    private static final Logger LOG = LogManager.getLogger( CsrfProtectionFilter.class );
047
048    public static final String ANTICSRF_PARAM = "X-XSRF-TOKEN";
049
050    /** {@inheritDoc} */
051    @Override
052    public void init( final FilterConfig filterConfig ) {
053    }
054
055    /** {@inheritDoc} */
056    @Override
057    public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain ) throws IOException, ServletException {
058        if( isPost( ( HttpServletRequest ) request ) && !isMultipartAttachmentUpload( ( HttpServletRequest ) request ) ) {
059            final Engine engine = Wiki.engine().find( request.getServletContext(), null );
060            final Session session = Wiki.session().find( engine, ( HttpServletRequest ) request );
061            if( !requestContainsValidCsrfToken( request, session ) ) {
062                LOG.error( "Incorrect {} param with value '{}' received for {}",
063                           ANTICSRF_PARAM, request.getParameter( ANTICSRF_PARAM ), ( ( HttpServletRequest ) request ).getPathInfo() );
064                ( ( HttpServletResponse ) response ).sendRedirect( "/error/Forbidden.html" );
065                return;
066            }
067        }
068        chain.doFilter( request, response );
069    }
070
071    public static boolean isCsrfProtectedPost( final HttpServletRequest request ) {
072        if( isPost( request ) ) {
073            final Engine engine = Wiki.engine().find( request.getServletContext(), null );
074            final Session session = Wiki.session().find( engine, request );
075            return requestContainsValidCsrfToken( request, session );
076        }
077        return false;
078    }
079
080    private static boolean requestContainsValidCsrfToken( final ServletRequest request, final Session session ) {
081        return session.antiCsrfToken().equals( request.getParameter( ANTICSRF_PARAM ) );
082    }
083
084    static boolean isPost( final HttpServletRequest request ) {
085        return "POST".equalsIgnoreCase( request.getMethod() );
086    }
087
088    /**
089     * Multipart uploads carry their anti-CSRF token in the request body, which {@code getParameter()} cannot read
090     * without consuming the stream. Requiring the token as a request parameter would force it into the URL query
091     * string, where it leaks into access logs, proxies and browser history. For the attachment servlet - the only
092     * multipart consumer, which parses the body itself and performs the same token check before acting on the
093     * request - the check is therefore delegated instead of applied here. Multipart POSTs to any other path keep
094     * being validated by this filter, so the body trick cannot be used to smuggle query-string parameters past it.
095     *
096     * @param request the inbound request
097     * @return true if this is a multipart POST for the attachment servlet
098     */
099    private static boolean isMultipartAttachmentUpload( final HttpServletRequest request ) {
100        final String contentType = request.getContentType();
101        return "/attach".equals( request.getServletPath() )
102                && contentType != null
103                && contentType.toLowerCase( Locale.ENGLISH ).startsWith( "multipart/" );
104    }
105
106    /** {@inheritDoc} */
107    @Override
108    public void destroy() {
109    }
110
111}