Skip to content
javahacks.dev
Struts

How to Use OGNL in Struts 2 Safely Without Injection Risks

Learn where Struts 2 evaluates OGNL, why user input must never reach an expression, and which settings and habits keep the value stack safe.

5 min read
Summarize in AI
Flat illustration of a request passing through a servlet container, with the OpenJDK, NGINX, Apache Tomcat and Docker logos.

Most of the serious security advisories on Struts 2 have the same shape: a place where attacker-controlled text reached the OGNL evaluator. Understanding what OGNL does in a Struts page is the first defense, and this post is written for the defender: it describes the risk and the habits that avoid it, without exploit recipes. For the wider picture of the framework, see what Struts 2 is; for server hardening see hardening Struts 2 against remote code execution.

What OGNL does here

OGNL (Object-Graph Navigation Language) navigates object graphs and can call methods. Struts uses it in three places:

PlaceExample
Tag attributes<s:property value="user.name" />
Forced evaluation<s:textfield name="x" value="%{defaultName}" />
Parameter namesuser.address.city=Berlin in a request

In the last case, the framework turns the parameter name into an OGNL expression to set a property. Because names come from the client, the framework limits which names are acceptable.

The rule: user text is data

Safe use:

XML
<s:property value="username" />          <!-- evaluates the expression "username" -->

Unsafe use:

XML
<s:textfield name="field" value="%{#parameters.q[0]}" />      <!-- evaluates text taken from the request -->

The danger appears when the expression is built from request content, or when an attribute value is evaluated twice, once as the author intended and again on the result. Several past vulnerabilities came from double evaluation: a tag attribute holding %{userInput} where userInput itself contained an expression. Avoid %{...} around any value that can be influenced by a user, and avoid putting request data into attributes that Struts treats as expressions (id, name and value of some tags).

Escape output

<s:property> escapes HTML by default (escapeHtml="true"), which prevents script injection in the page. Keep it. Escaping output stops cross-site scripting and does not stop OGNL injection, which happens before output; the two need separate care. For the XSS side see preventing XSS in Java web applications.

Keep the strict defaults

Current Struts versions ship with restrictive OGNL settings:

XML
<constant name="struts.ognl.allowStaticFieldAccess" value="false" />
<constant name="struts.ognl.excludedClasses" value="java.lang.Runtime,java.lang.ProcessBuilder" />

The defaults are stricter than this sample, which only shows the setting names. Do not relax them to make a legacy page work. If a page needs static access, call the static method from the action and expose the result as a property.

Limit what parameters can set

The parameters interceptor can accept or reject names by pattern:

XML
<interceptor-ref name="params">
    <param name="excludeParams">dojo\..*,^struts\..*,^session\..*,^request\..*,^application\..*,^servlet(Request|Response)\..*</param>
</interceptor-ref>

The default patterns exclude framework internals. Review the version you run and keep the acceptedPatterns narrow, so that only names resembling your action's properties pass.

Stay patched

Most OGNL-related advisories were fixed by upgrading, and the exploits for old releases are widely available and automated. Subscribe to the Struts security bulletins and upgrade within days of a fix. The OGNL documentation describes the language, and OWASP's guidance on injection covers the general class of bug.

Find where user text could reach an expression

A review is a search with a list. These patterns in JSP and in Java deserve a second look, because each places a string where an expression evaluator reads it:

Shell
grep -rnE '%\{[^}]*\}' src/main/webapp | grep -v 'cssClass\|style'
grep -rnE 'escapeHtml="false"|escape="false"' src/main/webapp
grep -rnE 'TextParseUtil|ValueStack|findValue|translateVariables' src/main/java

The first pattern lists %{...} forced evaluation, which is legitimate for fixed strings and dangerous for anything derived from a request. The second lists output that is not escaped, a plain cross-site scripting risk as well. The third lists code that evaluates a string as an expression. For each hit, ask where the text comes from. If the answer includes a request parameter, a header or a database field a user can write, rewrite it so the text is passed as a value and never evaluated.

Know every Struts copy you run

Advisories are fixed by upgrading, and the hard part is finding all the places that need it. Application servers, shared library folders and old WAR files hide copies:

Shell
find / -name 'struts2-core*.jar' 2>/dev/null
find /opt /srv -name '*.war' -exec sh -c 'unzip -l "$1" | grep -q struts2-core && echo "$1"' _ {} \;

Record each version and owner in a list that someone maintains. An application that nobody remembers is the one that is breached. The OWASP Dependency-Check tool reports known vulnerabilities for the jars it finds, and running it in the build gives a failing result as soon as a new advisory covers a used version.

Defence in depth around the framework

Patching is the fix, and several layers reduce the damage while a patch is scheduled.

LayerWhat it doesWhat it does not do
Run as an unprivileged userA compromised process cannot write outside its directoriesDoes not stop access to the application's own data
Network egress rulesThe server cannot download a second stage from the internetDoes not stop the first request
A web application firewallBlocks known payload shapes quicklyCan be bypassed, it is not a substitute for the upgrade
Read-only file system for the containerPrevents writing new filesThe application still writes to its data directories
Alerting on process spawns from the JVMDetects a shell started by the serverDetects after the fact

A firewall rule is a stopgap for the hours between an advisory and the deployment, and a long-term plan that depends on it is a plan to be breached later.

Prove that parameters are limited

A test that sends a request with a parameter name that should be refused, and checks that nothing changed, documents the protection. Use a harmless property name that exists on the action, and assert that its value is still the default:

java
public class ProfileActionTest extends StrutsJUnit4TestCase<ProfileAction> {

    @Test
    public void unlistedParameterIsIgnored() throws Exception {
        request.setParameter("internalFlag", "true");
        executeAction("/profile.action");
        assertFalse(getAction().isInternalFlag());
    }
}

The name internalFlag stands for a field that should never be set from outside. A passing test shows that the parameter filter works for it, and the test fails when a change to the configuration removes the protection.

Treat the pages and the actions as the boundary

Every action that is reachable is an input surface. List them, mark those that need no login, and look first at the ones that take file uploads, redirects or free text that is echoed back in a page. The smaller the set of public actions, the smaller the review, and removing an action that no one uses is the cheapest fix there is.

Where this does not apply

Applications that moved off Struts do not have this surface, although a Spring Expression Language injection has the same shape (a @Value or ExpressionParser fed with request text). The principle is portable: do not evaluate user input as code.

Also inSecurity
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.