Skip to content

Commit

Permalink
WW-5504 Allows to use request instead of session attribute to store n…
Browse files Browse the repository at this point in the history
…once
  • Loading branch information
lukaszlenart committed Jan 5, 2025
1 parent c7a6daf commit 471e4e7
Show file tree
Hide file tree
Showing 32 changed files with 379 additions and 40 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@
import ognl.PropertyAccessor;
import org.apache.struts2.dispatcher.HttpParameters;
import org.apache.struts2.dispatcher.Parameter;
import org.apache.struts2.interceptor.csp.CspNonceReader;
import org.apache.struts2.interceptor.csp.StrutsCspNonceReader;
import org.apache.struts2.interceptor.exec.ExecutorProvider;
import org.apache.struts2.interceptor.exec.StrutsExecutorProvider;
import org.apache.struts2.url.QueryStringBuilder;
Expand Down Expand Up @@ -159,7 +161,9 @@ public void register(ContainerBuilder builder, LocatableProperties props) throws
.factory(UrlEncoder.class, StrutsUrlEncoder.class, Scope.SINGLETON)
.factory(UrlDecoder.class, StrutsUrlDecoder.class, Scope.SINGLETON)

.factory(ExecutorProvider.class, StrutsExecutorProvider.class, Scope.SINGLETON);
.factory(ExecutorProvider.class, StrutsExecutorProvider.class, Scope.SINGLETON)

.factory(CspNonceReader.class, StrutsCspNonceReader.class, Scope.SINGLETON);

for (Map.Entry<String, Object> entry : DefaultConfiguration.BOOTSTRAP_CONSTANTS.entrySet()) {
props.setProperty(entry.getKey(), String.valueOf(entry.getValue()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -419,8 +419,12 @@ Object construct(InternalContext context, Class<? super T> expectedType) {
// First time through...
constructionContext.startConstruction();
try {
final Object[] parameters = getParameters(constructor, context, parameterInjectors);
t = constructor.newInstance(parameters);
if (constructor.getParameterCount() > 0 && parameterInjectors == null) {
t = constructor.newInstance(new Object[constructor.getParameterCount()]);
} else {
final Object[] parameters = getParameters(constructor, context, parameterInjectors);
t = constructor.newInstance(parameters);
}
constructionContext.setProxyDelegates(t);
} finally {
constructionContext.finishConstruction();
Expand Down
7 changes: 7 additions & 0 deletions core/src/main/java/org/apache/struts2/StrutsConstants.java
Original file line number Diff line number Diff line change
Expand Up @@ -509,4 +509,11 @@ public final class StrutsConstants {

/** See {@link org.apache.struts2.interceptor.exec.ExecutorProvider} */
public static final String STRUTS_EXECUTOR_PROVIDER = "struts.executor.provider";

/**
* See {@link org.apache.struts2.interceptor.csp.CspNonceReader}
* @since 6.8.0
*/
public static final String STRUTS_CSP_NONCE_READER = "struts.csp.nonce.reader";
public static final String STRUTS_CSP_NONCE_SOURCE = "struts.csp.nonce.source";
}
18 changes: 12 additions & 6 deletions core/src/main/java/org/apache/struts2/components/UIBean.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@
import org.apache.struts2.components.template.TemplateEngineManager;
import org.apache.struts2.components.template.TemplateRenderingContext;
import org.apache.struts2.dispatcher.StaticContentLoader;
import org.apache.struts2.interceptor.csp.CspNonceReader;
import org.apache.struts2.util.ComponentUtils;
import org.apache.struts2.util.TextProviderHelper;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import org.apache.struts2.views.util.ContextUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.Writer;
import java.util.HashMap;
import java.util.LinkedHashMap;
Expand Down Expand Up @@ -521,6 +521,8 @@ public UIBean(ValueStack stack, HttpServletRequest request, HttpServletResponse

protected TemplateEngineManager templateEngineManager;

protected CspNonceReader cspNonceReader;

@Inject(StrutsConstants.STRUTS_UI_TEMPLATEDIR)
public void setDefaultTemplateDir(String dir) {
this.defaultTemplateDir = dir;
Expand All @@ -546,6 +548,11 @@ public void setTemplateEngineManager(TemplateEngineManager mgr) {
this.templateEngineManager = mgr;
}

@Inject
public void setCspNonceReader(CspNonceReader cspNonceReader) {
this.cspNonceReader = cspNonceReader;
}

@Override
public boolean end(Writer writer, String body) {
evaluateParams();
Expand Down Expand Up @@ -864,13 +871,12 @@ public void evaluateParams() {
}

// to be used with the CSP interceptor - adds the nonce value as a parameter to be accessed from ftl files
HttpSession session = stack.getActionContext().getServletRequest().getSession(false);
Object nonceValue = session != null ? session.getAttribute("nonce") : null;
CspNonceReader.NonceValue nonceValue = cspNonceReader.readNonceValue(stack);

if (nonceValue != null) {
addParameter("nonce", nonceValue.toString());
if (nonceValue.isNonceValueSet()) {
addParameter("nonce", nonceValue.getNonceValue());
} else {
LOG.debug("Session is not active, cannot obtain nonce value");
LOG.debug("Nonce not defined in: {}", nonceValue.getSource());
}

evaluateExtraParams();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
import org.apache.struts2.dispatcher.StaticContentLoader;
import org.apache.struts2.dispatcher.mapper.ActionMapper;
import org.apache.struts2.dispatcher.multipart.MultiPartRequest;
import org.apache.struts2.interceptor.csp.CspNonceReader;
import org.apache.struts2.interceptor.exec.ExecutorProvider;
import org.apache.struts2.ognl.OgnlGuard;
import org.apache.struts2.url.QueryStringBuilder;
Expand Down Expand Up @@ -450,6 +451,8 @@ public void register(ContainerBuilder builder, LocatableProperties props) {

alias(ExecutorProvider.class, StrutsConstants.STRUTS_EXECUTOR_PROVIDER, builder, props, Scope.SINGLETON);

alias(CspNonceReader.class, StrutsConstants.STRUTS_CSP_NONCE_READER, builder, props, Scope.SINGLETON);

switchDevMode(props);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.interceptor.csp;

import org.apache.struts2.util.ValueStack;

/**
* Reads the nonce value using the ValueStack, {@link StrutsCspNonceReader} is the default implementation
* @since 6.8.0
*/
public interface CspNonceReader {

NonceValue readNonceValue(ValueStack stack);

class NonceValue {
private final String nonceValue;
private final CspNonceSource source;

private NonceValue(String nonceValue, CspNonceSource source) {
this.nonceValue = nonceValue;
this.source = source;
}

public static NonceValue ofSession(String nonceValue) {
return new NonceValue(nonceValue, CspNonceSource.SESSION);
}

public static NonceValue ofRequest(String nonceValue) {
return new NonceValue(nonceValue, CspNonceSource.REQUEST);
}

public static NonceValue ofNullSession() {
return new NonceValue(null, CspNonceSource.REQUEST);
}

public static NonceValue ofNullRequest() {
return new NonceValue(null, CspNonceSource.REQUEST);
}

public boolean isNonceValueSet() {
return nonceValue != null;
}

public String getNonceValue() {
return nonceValue;
}

public CspNonceSource getSource() {
return source;
}

@Override
public String toString() {
return "NonceValue{" +
String.format("nonceValue='%s**********'", nonceValue.substring(0, 4)) +
", source=" + source +
'}';
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.interceptor.csp;

/**
* Source of the nonce value
*/
public enum CspNonceSource {
REQUEST,
SESSION
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,11 @@
*/
package org.apache.struts2.interceptor.csp;

import com.opensymphony.xwork2.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.action.CspSettingsAware;

import javax.servlet.http.HttpServletRequest;
Expand All @@ -43,56 +46,82 @@
*/
public class DefaultCspSettings implements CspSettings {

private final static Logger LOG = LogManager.getLogger(DefaultCspSettings.class);
private static final Logger LOG = LogManager.getLogger(DefaultCspSettings.class);
private static final String NONCE_KEY = "nonce";

private final SecureRandom sRand = new SecureRandom();

private CspNonceSource nonceSource = CspNonceSource.SESSION;

protected String reportUri;
protected String reportTo;
// default to reporting mode
protected String cspHeader = CSP_REPORT_HEADER;

@Inject(value = StrutsConstants.STRUTS_CSP_NONCE_SOURCE, required = false)
public void setNonceSource(String nonceSource) {
if (StringUtils.isBlank(nonceSource)) {
this.nonceSource = CspNonceSource.SESSION;
} else {
this.nonceSource = CspNonceSource.valueOf(nonceSource.toUpperCase());
}
}

@Override
public void addCspHeaders(HttpServletResponse response) {
throw new UnsupportedOperationException("Unsupported implementation, use #addCspHeaders(HttpServletRequest request, HttpServletResponse response)");
}

@Override
public void addCspHeaders(HttpServletRequest request, HttpServletResponse response) {
if (this.nonceSource == CspNonceSource.SESSION) {
addCspHeadersWithSession(request, response);
} else if (this.nonceSource == CspNonceSource.REQUEST) {
addCspHeadersWithRequest(request, response);
} else {
LOG.warn("Unknown nonce source: {}, ignoring CSP settings", nonceSource);
}
}

private void addCspHeadersWithSession(HttpServletRequest request, HttpServletResponse response) {
if (isSessionActive(request)) {
LOG.trace("Session is active, applying CSP settings");
associateNonceWithSession(request);
request.getSession().setAttribute(NONCE_KEY, generateNonceValue());
response.setHeader(cspHeader, createPolicyFormat(request));
} else {
LOG.trace("Session is not active, ignoring CSP settings");
LOG.debug("Session is not active, ignoring CSP settings");
}
}

private void addCspHeadersWithRequest(HttpServletRequest request, HttpServletResponse response) {
request.setAttribute(NONCE_KEY, generateNonceValue());
response.setHeader(cspHeader, createPolicyFormat(request));
}

private boolean isSessionActive(HttpServletRequest request) {
return request.getSession(false) != null;
}

private void associateNonceWithSession(HttpServletRequest request) {
String nonceValue = Base64.getUrlEncoder().encodeToString(getRandomBytes());
request.getSession().setAttribute("nonce", nonceValue);
private String generateNonceValue() {
return Base64.getUrlEncoder().encodeToString(getRandomBytes());
}

protected String createPolicyFormat(HttpServletRequest request) {
StringBuilder policyFormatBuilder = new StringBuilder()
.append(OBJECT_SRC)
.append(format(" '%s'; ", NONE))
.append(SCRIPT_SRC)
.append(" 'nonce-%s' ") // nonce placeholder
.append(format("'%s' ", STRICT_DYNAMIC))
.append(format("%s %s; ", HTTP, HTTPS))
.append(BASE_URI)
.append(format(" '%s'; ", NONE));
.append(OBJECT_SRC)
.append(format(" '%s'; ", NONE))
.append(SCRIPT_SRC)
.append(" 'nonce-%s' ") // nonce placeholder
.append(format("'%s' ", STRICT_DYNAMIC))
.append(format("%s %s; ", HTTP, HTTPS))
.append(BASE_URI)
.append(format(" '%s'; ", NONE));

if (reportUri != null) {
policyFormatBuilder
.append(REPORT_URI)
.append(format(" %s; ", reportUri));
if(reportTo != null) {
.append(REPORT_URI)
.append(format(" %s; ", reportUri));
if (reportTo != null) {
policyFormatBuilder
.append(REPORT_TO)
.append(format(" %s; ", reportTo));
Expand All @@ -103,7 +132,7 @@ protected String createPolicyFormat(HttpServletRequest request) {
}

protected String getNonceString(HttpServletRequest request) {
Object nonce = request.getSession().getAttribute("nonce");
Object nonce = request.getSession().getAttribute(NONCE_KEY);
return Objects.toString(nonce);
}

Expand Down Expand Up @@ -133,10 +162,10 @@ public void setReportTo(String reportTo) {
@Override
public String toString() {
return "DefaultCspSettings{" +
"reportUri='" + reportUri + '\'' +
", reportTo='" + reportTo + '\'' +
", cspHeader='" + cspHeader + '\'' +
'}';
"reportUri='" + reportUri + '\'' +
", reportTo='" + reportTo + '\'' +
", cspHeader='" + cspHeader + '\'' +
'}';
}

}
Loading

0 comments on commit 471e4e7

Please sign in to comment.