001/* 002 * Copyright 2025 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 org.apache.wiki.util.HttpUtil; 025 026import java.io.IOException; 027 028 029/** 030 * Content-Security-Policy (CSP): Mitigates XSS and other injection attacks by 031 * defining approved sources of content that the browser can load. 032 */ 033public class CSPFilter implements Filter { 034 035 private String mode = "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self'; img-src 'self';"; 036 037 /** {@inheritDoc} */ 038 @Override 039 public void init( final FilterConfig filterConfig ) { 040 final String configMode = FilterOperations.initValue( filterConfig, "CSPValue", "csp.value" ); 041 if( configMode != null ) { 042 mode = configMode; 043 } 044 } 045 046 /** {@inheritDoc} */ 047 @Override 048 public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain ) throws IOException, ServletException { 049 HttpUtil.addHeader( response,"Content-Security-Policy", mode ); 050 chain.doFilter( request, response ); 051 } 052 053}