Skip to content

Java: Add XSS Sanitizer for HttpServletResponse.setContentType with safe values #18607

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions java/ql/lib/semmle/code/java/frameworks/Servlets.qll
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,16 @@ class ResponseSetHeaderMethod extends Method {
}
}

/**
* The method `setContentType` declared in `javax.servlet.http.HttpServletResponse`.
*/
class ResponseSetContentTypeMethod extends Method {
ResponseSetContentTypeMethod() {
this.getDeclaringType() instanceof ServletResponse and
this.hasName("setContentType")
}
}

/**
* A class that has `javax.servlet.Servlet` as an ancestor.
*/
Expand Down
27 changes: 24 additions & 3 deletions java/ql/lib/semmle/code/java/security/XSS.qll
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,25 @@ private class WritingMethod extends Method {
/** An output stream or writer that writes to a servlet, JSP or JSF response. */
class XssVulnerableWriterSource extends MethodCall {
XssVulnerableWriterSource() {
this.getMethod() instanceof ServletResponseGetWriterMethod
or
this.getMethod() instanceof ServletResponseGetOutputStreamMethod
(
this.getMethod() instanceof ServletResponseGetWriterMethod
or
this.getMethod() instanceof ServletResponseGetOutputStreamMethod
) and
not exists(MethodCall mc, Expr contentType |
mc.getMethod() instanceof ResponseSetContentTypeMethod and
contentType = mc.getArgument(0)
or
(
mc.getMethod() instanceof ResponseAddHeaderMethod or
mc.getMethod() instanceof ResponseSetHeaderMethod
) and
mc.getArgument(0).(CompileTimeConstantExpr).getStringValue().toLowerCase() = "content-type" and
contentType = mc.getArgument(1)
|
isXssSafeContentTypeString(contentType.(CompileTimeConstantExpr).getStringValue()) and
DataFlow::localExprFlow(mc.getQualifier(), this.getQualifier())
)
or
exists(Method m | m = this.getMethod() |
m.hasQualifiedName("javax.servlet.jsp", "JspContext", "getOut")
Expand All @@ -106,6 +122,11 @@ class XssVulnerableWriterSource extends MethodCall {
}
}

pragma[nomagic]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why nomagic? Inlining this would seem like a good way to make the somewhat-expensive regex test against just those string constants passed to a relevant method, rather than every string constant in the database, which could well get into the millions for big projects?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was copying how it is done in other places, as recently updated in #18552

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@aschackmull can you comment since you're the author there? Wouldn't it be better to actually encourage restricting the strings we're considering (here, to arguments to a particular method) and then regex-match them, rather than match against every string constant value?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inlining this would seem like a good way to make the somewhat-expensive regex test against just those string constants passed to a relevant method, rather than every string constant in the database, which could well get into the millions for big projects?

True. At least in theory. IIRC the trouble was that as long as at least one of the use-cases fails to provide a properly restrictive context then inlining/magic'ing becomes actively bad as that just increases the number of regex operations. And the optimiser is too unreliable for ensuring that every use-case has a good restrictive context that's also applied before the regex. That's why I went with the somewhat blunt solution of just evaluating the regex on all the values of all string literals (notice that the string literal column is projected away, which is crucial, as that reduces things a lot). In the cases I looked at this was a considerable performance improvement over the previous situation.

We can of course refactor things to do the minimal number of regex operations, but we shouldn't trust the optimiser too much.

private predicate isXssSafeContentTypeString(string s) {
s = any(CompileTimeConstantExpr cte).getStringValue() and isXssSafeContentType(s)
}

/**
* A xss vulnerable writer source node.
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
category: majorAnalysis
---
* Fixed false positive alerts in the java query "Cross-site scripting" (`java/xss`) when `javax.servlet.http.HttpServletResponse` is used with a content type which is not exploitable.
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,18 @@ public static Response specificContentType(boolean safeContentType, boolean chai
if(!safeContentType) {
if(chainDirectly) {
if(contentTypeFirst)
return builder.type(MediaType.TEXT_HTML).entity(userControlled).build(); // $xss
return builder.type(MediaType.TEXT_HTML).entity(userControlled).build(); // $ xss
else
return builder.entity(userControlled).type(MediaType.TEXT_HTML).build(); // $xss
return builder.entity(userControlled).type(MediaType.TEXT_HTML).build(); // $ xss
}
else {
if(contentTypeFirst) {
Response.ResponseBuilder builder2 = builder.type(MediaType.TEXT_HTML);
return builder2.entity(userControlled).build(); // $xss
return builder2.entity(userControlled).build(); // $ xss
}
else {
Response.ResponseBuilder builder2 = builder.entity(userControlled);
return builder2.type(MediaType.TEXT_HTML).build(); // $xss
return builder2.type(MediaType.TEXT_HTML).build(); // $ xss
}
}
}
Expand Down Expand Up @@ -105,39 +105,39 @@ else if(route == 8) {
else {
if(route == 0) {
// via ok, as a string literal:
return Response.ok("text/html").entity(userControlled).build(); // $xss
return Response.ok("text/html").entity(userControlled).build(); // $ xss
}
else if(route == 1) {
// via ok, as a string constant:
return Response.ok(MediaType.TEXT_HTML).entity(userControlled).build(); // $xss
return Response.ok(MediaType.TEXT_HTML).entity(userControlled).build(); // $ xss
}
else if(route == 2) {
// via ok, as a MediaType constant:
return Response.ok(MediaType.TEXT_HTML_TYPE).entity(userControlled).build(); // $xss
return Response.ok(MediaType.TEXT_HTML_TYPE).entity(userControlled).build(); // $ xss
}
else if(route == 3) {
// via ok, as a Variant, via constructor:
return Response.ok(new Variant(MediaType.TEXT_HTML_TYPE, "language", "encoding")).entity(userControlled).build(); // $xss
return Response.ok(new Variant(MediaType.TEXT_HTML_TYPE, "language", "encoding")).entity(userControlled).build(); // $ xss
}
else if(route == 4) {
// via ok, as a Variant, via static method:
return Response.ok(Variant.mediaTypes(MediaType.TEXT_HTML_TYPE).build()).entity(userControlled).build(); // $xss
return Response.ok(Variant.mediaTypes(MediaType.TEXT_HTML_TYPE).build()).entity(userControlled).build(); // $ xss
}
else if(route == 5) {
// via ok, as a Variant, via instance method:
return Response.ok(Variant.languages(Locale.UK).mediaTypes(MediaType.TEXT_HTML_TYPE).build()).entity(userControlled).build(); // $xss
return Response.ok(Variant.languages(Locale.UK).mediaTypes(MediaType.TEXT_HTML_TYPE).build()).entity(userControlled).build(); // $ xss
}
else if(route == 6) {
// via builder variant, before entity:
return Response.ok().variant(new Variant(MediaType.TEXT_HTML_TYPE, "language", "encoding")).entity(userControlled).build(); // $xss
return Response.ok().variant(new Variant(MediaType.TEXT_HTML_TYPE, "language", "encoding")).entity(userControlled).build(); // $ xss
}
else if(route == 7) {
// via builder variant, after entity:
return Response.ok().entity(userControlled).variant(new Variant(MediaType.TEXT_HTML_TYPE, "language", "encoding")).build(); // $xss
return Response.ok().entity(userControlled).variant(new Variant(MediaType.TEXT_HTML_TYPE, "language", "encoding")).build(); // $ xss
}
else if(route == 8) {
// provide entity via ok, then content-type via builder:
return Response.ok(userControlled).type(MediaType.TEXT_HTML_TYPE).build(); // $xss
return Response.ok(userControlled).type(MediaType.TEXT_HTML_TYPE).build(); // $ xss
}
}

Expand All @@ -162,27 +162,27 @@ public static Response methodContentTypeSafeStringLiteral(String userControlled)

@GET @Produces(MediaType.TEXT_HTML)
public static Response methodContentTypeUnsafe(String userControlled) {
return Response.ok(userControlled).build(); // $xss
return Response.ok(userControlled).build(); // $ xss
}

@POST @Produces(MediaType.TEXT_HTML)
public static Response methodContentTypeUnsafePost(String userControlled) {
return Response.ok(userControlled).build(); // $xss
return Response.ok(userControlled).build(); // $ xss
}

@GET @Produces("text/html")
public static Response methodContentTypeUnsafeStringLiteral(String userControlled) {
return Response.ok(userControlled).build(); // $xss
return Response.ok(userControlled).build(); // $ xss
}

@GET @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
public static Response methodContentTypeMaybeSafe(String userControlled) {
return Response.ok(userControlled).build(); // $xss
return Response.ok(userControlled).build(); // $ xss
}

@GET @Produces(MediaType.APPLICATION_JSON)
public static Response methodContentTypeSafeOverriddenWithUnsafe(String userControlled) {
return Response.ok().type(MediaType.TEXT_HTML).entity(userControlled).build(); // $xss
return Response.ok().type(MediaType.TEXT_HTML).entity(userControlled).build(); // $ xss
}

@GET @Produces(MediaType.TEXT_HTML)
Expand All @@ -205,12 +205,12 @@ public String testDirectReturn(String userControlled) {

@GET @Produces({"text/html"})
public Response overridesWithUnsafe(String userControlled) {
return Response.ok(userControlled).build(); // $xss
return Response.ok(userControlled).build(); // $ xss
}

@GET
public Response overridesWithUnsafe2(String userControlled) {
return Response.ok().type(MediaType.TEXT_HTML).entity(userControlled).build(); // $xss
return Response.ok().type(MediaType.TEXT_HTML).entity(userControlled).build(); // $ xss
}
}

Expand All @@ -219,12 +219,12 @@ public Response overridesWithUnsafe2(String userControlled) {
public static class ClassContentTypeUnsafe {
@GET
public Response test(String userControlled) {
return Response.ok(userControlled).build(); // $xss
return Response.ok(userControlled).build(); // $ xss
}

@GET
public String testDirectReturn(String userControlled) {
return userControlled; // $xss
return userControlled; // $ xss
}

@GET @Produces({"application/json"})
Expand All @@ -240,12 +240,12 @@ public Response overridesWithSafe2(String userControlled) {

@GET
public static Response entityWithNoMediaType(String userControlled) {
return Response.ok(userControlled).build(); // $xss
return Response.ok(userControlled).build(); // $ xss
}

@GET
public static String stringWithNoMediaType(String userControlled) {
return userControlled; // $xss
return userControlled; // $ xss
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public void encodeBegin(FacesContext facesContext, UIComponent component) throws
writer.write("(function(){");
writer.write("dswh.init('" + windowId + "','"
+ "......" + "',"
+ -1 + ",{"); // $xss
+ -1 + ",{"); // $ xss
writer.write("});");
writer.write("})();");
writer.write("</script>");
Expand Down Expand Up @@ -57,13 +57,13 @@ public void testAllSources(FacesContext facesContext) throws IOException
{
ExternalContext ec = facesContext.getExternalContext();
ResponseWriter writer = facesContext.getResponseWriter();
writer.write(ec.getRequestParameterMap().keySet().iterator().next()); // $xss
writer.write(ec.getRequestParameterNames().next()); // $xss
writer.write(ec.getRequestParameterValuesMap().get("someKey")[0]); // $xss
writer.write(ec.getRequestParameterValuesMap().keySet().iterator().next()); // $xss
writer.write(ec.getRequestPathInfo()); // $xss
writer.write(((Cookie)ec.getRequestCookieMap().get("someKey")).getName()); // $xss
writer.write(ec.getRequestHeaderMap().get("someKey")); // $xss
writer.write(ec.getRequestHeaderValuesMap().get("someKey")[0]); // $xss
writer.write(ec.getRequestParameterMap().keySet().iterator().next()); // $ xss
writer.write(ec.getRequestParameterNames().next()); // $ xss
writer.write(ec.getRequestParameterValuesMap().get("someKey")[0]); // $ xss
writer.write(ec.getRequestParameterValuesMap().keySet().iterator().next()); // $ xss
writer.write(ec.getRequestPathInfo()); // $ xss
writer.write(((Cookie)ec.getRequestCookieMap().get("someKey")).getName()); // $ xss
writer.write(ec.getRequestHeaderMap().get("someKey")); // $ xss
writer.write(ec.getRequestHeaderValuesMap().get("someKey")[0]); // $ xss
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
public class SetJavascriptEnabled {
public static void configureWebViewUnsafe(WebView view) {
WebSettings settings = view.getSettings();
settings.setJavaScriptEnabled(true); // $javascriptEnabled
settings.setJavaScriptEnabled(true); // $ javascriptEnabled
}

public static void configureWebViewSafe(WebView view) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@ public static ResponseEntity<String> specificContentType(boolean safeContentType

ResponseEntity.BodyBuilder builder = ResponseEntity.ok();

if(safeContentType) {
if(!safeContentType) {
if(chainDirectly) {
return builder.contentType(MediaType.TEXT_HTML).body(userControlled); // $xss
return builder.contentType(MediaType.TEXT_HTML).body(userControlled); // $ xss
}
else {
ResponseEntity.BodyBuilder builder2 = builder.contentType(MediaType.TEXT_HTML);
return builder2.body(userControlled); // $xss
return builder2.body(userControlled); // $ xss
}
}
else {
Expand Down Expand Up @@ -60,22 +60,22 @@ public static ResponseEntity<String> methodContentTypeSafeStringLiteral(String u

@GetMapping(value = "/xyz", produces = MediaType.TEXT_HTML_VALUE)
public static ResponseEntity<String> methodContentTypeUnsafe(String userControlled) {
return ResponseEntity.ok(userControlled); // $xss
return ResponseEntity.ok(userControlled); // $ xss
}

@GetMapping(value = "/xyz", produces = "text/html")
public static ResponseEntity<String> methodContentTypeUnsafeStringLiteral(String userControlled) {
return ResponseEntity.ok(userControlled); // $xss
return ResponseEntity.ok(userControlled); // $ xss
}

@GetMapping(value = "/xyz", produces = {MediaType.TEXT_HTML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public static ResponseEntity<String> methodContentTypeMaybeSafe(String userControlled) {
return ResponseEntity.ok(userControlled); // $xss
return ResponseEntity.ok(userControlled); // $ xss
}

@GetMapping(value = "/xyz", produces = MediaType.APPLICATION_JSON_VALUE)
public static ResponseEntity<String> methodContentTypeSafeOverriddenWithUnsafe(String userControlled) {
return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(userControlled); // $xss
return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(userControlled); // $ xss
}

@GetMapping(value = "/xyz", produces = MediaType.TEXT_HTML_VALUE)
Expand All @@ -88,13 +88,13 @@ public static ResponseEntity<String> methodContentTypeMaybeSafeStringLiterals(St
// Also try out some alternative constructors for the ResponseEntity:
switch(constructionMethod) {
case 0:
return ResponseEntity.ok(userControlled); // $xss
return ResponseEntity.ok(userControlled); // $ xss
case 1:
return ResponseEntity.of(Optional.of(userControlled)); // $xss
return ResponseEntity.of(Optional.of(userControlled)); // $ xss
case 2:
return ResponseEntity.ok().body(userControlled); // $xss
return ResponseEntity.ok().body(userControlled); // $ xss
case 3:
return new ResponseEntity<String>(userControlled, HttpStatus.OK); // $xss
return new ResponseEntity<String>(userControlled, HttpStatus.OK); // $ xss
default:
return null;
}
Expand All @@ -115,12 +115,12 @@ public String testDirectReturn(String userControlled) {

@GetMapping(value = "/xyz", produces = {"text/html"})
public ResponseEntity<String> overridesWithUnsafe(String userControlled) {
return ResponseEntity.ok(userControlled); // $xss
return ResponseEntity.ok(userControlled); // $ xss
}

@GetMapping(value = "/abc")
public ResponseEntity<String> overridesWithUnsafe2(String userControlled) {
return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(userControlled); // $xss
return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(userControlled); // $ xss
}
}

Expand All @@ -129,12 +129,12 @@ public ResponseEntity<String> overridesWithUnsafe2(String userControlled) {
private static class ClassContentTypeUnsafe {
@GetMapping(value = "/abc")
public ResponseEntity<String> test(String userControlled) {
return ResponseEntity.ok(userControlled); // $xss
return ResponseEntity.ok(userControlled); // $ xss
}

@GetMapping(value = "/abc")
public String testDirectReturn(String userControlled) {
return userControlled; // $xss
return userControlled; // $ xss
}

@GetMapping(value = "/xyz", produces = {"application/json"})
Expand All @@ -150,12 +150,12 @@ public ResponseEntity<String> overridesWithSafe2(String userControlled) {

@GetMapping(value = "/abc")
public static ResponseEntity<String> entityWithNoMediaType(String userControlled) {
return ResponseEntity.ok(userControlled); // $xss
return ResponseEntity.ok(userControlled); // $ xss
}

@GetMapping(value = "/abc")
public static String stringWithNoMediaType(String userControlled) {
return userControlled; // $xss
return userControlled; // $ xss
}

@GetMapping(value = "/abc")
Expand Down
Loading