Skip to content
javahacks.dev
Struts

How to Upload Files in Struts 2 Safely and Limit the Risk

Accept file uploads in Struts 2 with size and type limits, safe file names and storage outside the web root, and know which settings and releases matter.

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

File upload is the feature that turns a read-only application into one that accepts arbitrary data from the internet. In Struts 2 it is a few lines of configuration, and the safe version is a few more. This post shows both. The security background is in hardening Struts 2, and the equivalent general rules in preventing path traversal.

The action

src/main/java/dev/javahacks/web/UploadAction.javajava
public class UploadAction extends ActionSupport {

    private File upload;
    private String uploadFileName;
    private String uploadContentType;

    @Override
    public String execute() throws IOException {
        Path target = Paths.get("/var/app/uploads", UUID.randomUUID() + ".dat");
        Files.copy(upload.toPath(), target);
        return SUCCESS;
    }

    public void setUpload(File upload) { this.upload = upload; }
    public void setUploadFileName(String name) { this.uploadFileName = name; }
    public void setUploadContentType(String type) { this.uploadContentType = type; }
}

The interceptor sets upload (a temporary file), uploadFileName and uploadContentType by naming convention, using the form field name as the prefix. The action saves the file under a name it generated, not the one the client sent.

The mapping, with limits

XML
<action name="upload" class="dev.javahacks.web.UploadAction">
    <interceptor-ref name="defaultStack">
        <param name="fileUpload.maximumSize">2097152</param>
        <param name="fileUpload.allowedTypes">image/png,image/jpeg</param>
        <param name="fileUpload.allowedExtensions">.png,.jpg,.jpeg</param>
    </interceptor-ref>
    <result name="success">/uploaded.jsp</result>
    <result name="input">/upload.jsp</result>
</action>

maximumSize is in bytes (2 MB here). Files over the limit add a field error, and the workflow interceptor returns input. The form needs enctype="multipart/form-data", which <s:form enctype="multipart/form-data"> writes. Also set the multipart limits globally with struts.multipart.maxSize, so a request cannot exhaust memory before the interceptor runs.

The client lies, so check

Client-supplied valueWhy you cannot trust it
uploadFileNameMay contain ../, a path, a double extension or null bytes
uploadContentTypeSet by the browser; an attacker sets anything
The extension.jpg on a file that is an HTML page

Never use the name to build a path. Generate your own, and keep the original only as display data after escaping. Verify the type by content for anything you will serve or process, by reading the first bytes (the magic number) or by decoding the image with a library and rejecting failures. Re-encoding images drops embedded payloads.

Store outside the web root

java
Path dir = Paths.get("/var/app/uploads");     // not inside webapp/

A file saved under the web root can be requested by URL and executed if it is a JSP. Serve downloads through an action that checks permissions and streams the file with the result type stream, setting Content-Disposition: attachment and a fixed Content-Type. Do not serve user uploads from the same origin as the application if they can contain HTML or SVG.

Resource limits

Large files fill the disk, and many parallel uploads fill the temp directory. Set the maximum request size, run uploads under a quota and clean the temporary directory. Scan files with an antivirus component if users share them with each other.

Releases that matter

Upload handling was affected by a path traversal issue through parameter names, fixed in Struts 2.5.33 and 6.3.0.2 (CVE-2023-50164). Struts 6.4 and later added a new upload mechanism with different interceptors. Check the Struts file upload documentation for the interceptor in your release, because the parameter names and classes differ.

Check the content, not the declared type

The browser sends a content type and a file name, and an attacker controls both. The interceptor's allowedTypes check compares against that header, so it stops an honest mistake and nothing else. To confirm a file is an image, read its first bytes:

java
static boolean looksLikePng(Path file) throws IOException {
    byte[] header = new byte[8];
    try (InputStream in = Files.newInputStream(file)) {
        if (in.readNBytes(header, 0, 8) < 8) {
            return false;
        }
    }
    return Arrays.equals(header, new byte[] {(byte) 0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A});
}

Do the same for each accepted format, using its documented signature. For stricter validation, decode the image with ImageIO.read and re-encode it, which strips metadata and rejects files that only pretend to be images. Apache Tika detects types more broadly, at the cost of a dependency.

Never use the supplied file name

The name can contain ../, a drive letter, a null byte or a very long string. Generate the stored name yourself and keep the original only as a display value in the database:

java
String stored = UUID.randomUUID() + ".png";
Path target = uploadDir.resolve(stored).normalize();
if (!target.startsWith(uploadDir)) {
    throw new SecurityException("Path escapes the upload directory");
}
Files.copy(file.toPath(), target);

The startsWith check after normalize is the guard against path traversal. With a generated name it can never fail, and it is worth keeping as a second line of defence for the day someone changes the name logic.

Make an upload test part of the build

An upload endpoint needs negative tests more than positive ones. Cases to cover:

CaseExpected result
A file at the size limit plus one byteRejected with a message, nothing written
A .png extension on a text fileRejected by the content check
A name such as ../../etc/cron.d/xStored under a generated name inside the directory
An executable extension, .jsp or .warRejected, never stored where it can be served
An empty fileRejected with a message
Two parts with the same field nameHandled predictably, usually only the first is kept

Each row corresponds to a real attack or a real support ticket. Write them as tests once, and they hold across the framework upgrades that this project will face.

Serve uploads safely

Storing outside the web root is half of it. The other half is how files are served back. Send them through an action that sets Content-Type from your own record, adds X-Content-Type-Options: nosniff and, for anything that is not an image or PDF, Content-Disposition: attachment. A user-supplied HTML or SVG file served inline from your domain runs script with your origin's privileges, which is stored cross-site scripting. Serving user content from a separate domain, with no cookies, removes the risk entirely and is the choice for any site where uploads are public.

Limits at every layer

The framework limit, the container's limit and the reverse proxy's limit all apply, and the smallest wins. A 10 MB maximumSize in Struts is useless when nginx has the default client_max_body_size of 1 MB, and the user sees a 413 error page and not your message. Set the three to matching values, and test through the proxy, since a direct test to the application server skips the layer most likely to reject the file.

Logging uploads for later investigation

When an upload goes wrong, the log is the only witness. Record the user, the time, the original file name, the stored name, the declared type, the detected type, the size and the outcome, whether accepted or rejected, and the reason for a rejection. Keep the log apart from the application log, with access limited to the security team, since file names can hold personal data.

A pattern of rejected uploads from one account is often the first sign of probing, so an alert on the rate of rejections costs little and gives an early warning.

Where this does not apply

If the files are large media for streaming, use direct-to-storage uploads with signed URLs and keep them off the application server. The Struts security bulletins list advisories by version, and the general class of upload flaws is covered in OWASP Top Ten for Java developers.

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.