CVE-2018-1000129 (published 2018-03-14T13:29Z)

An XSS vulnerability exists in the Jolokia agent version 1.3.7 in the HTTP servlet that allows an attacker to execute malicious javascript in the victim's browser.

Severity: MEDIUM
CVSS v2 base score: 4.3 (AV:N/AC:M/Au:N/C:N/I:P/A:N)
CVSS v3 base score: 6.1, MEDIUM (CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N)

Weakness information:
cwe_id: CWE-79
cwe_name: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
description: The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
extended_description: 
            Cross-site scripting (XSS) vulnerabilities occur when:
            
               Untrusted data enters a web application, typically from a web request.
               The web application dynamically generates a web page that contains this untrusted data.
               During page generation, the application does not prevent the data from containing content that is executable by a web browser, such as JavaScript, HTML tags, HTML attributes, mouse events, Flash, ActiveX, etc.
               A victim visits the generated web page through a web browser, which contains malicious script that was injected using the untrusted data.
               Since the script comes from a web page that was sent by the web server, the victim's web browser executes the malicious script in the context of the web server's domain.
               This effectively violates the intention of the web browser's same-origin policy, which states that scripts in one domain should not be able to access resources or run code in a different domain.
            
            There are three main kinds of XSS:
            
               
                  Type 1: Reflected XSS (or Non-Persistent) - 
         			The server reads data directly from the HTTP request and reflects it back in the HTTP response. Reflected XSS exploits occur when an attacker causes a victim to supply dangerous content to a vulnerable web application, which is then reflected back to the victim and executed by the web browser. The most common mechanism for delivering malicious content is to include it as a parameter in a URL that is posted publicly or e-mailed directly to the victim. URLs constructed in this manner constitute the core of many phishing schemes, whereby an attacker convinces a victim to visit a URL that refers to a vulnerable site. After the site reflects the attacker's content back to the victim, the content is executed by the victim's browser.
               
                  Type 2: Stored XSS (or Persistent) - 
               The application stores dangerous data in a database, message forum, visitor log, or other trusted data store. At a later time, the dangerous data is subsequently read back into the application and included in dynamic content. From an attacker's perspective, the optimal place to inject malicious content is in an area that is displayed to either many users or particularly interesting users. Interesting users typically have elevated privileges in the application or interact with sensitive data that is valuable to the attacker. If one of these users executes malicious content, the attacker may be able to perform privileged operations on behalf of the user or gain access to sensitive data belonging to the user. For example, the attacker might inject XSS into a log message, which might not be handled properly when an administrator views the logs.
            
               
                  Type 0: DOM-Based XSS - 
               In DOM-based XSS, the client performs the injection of XSS into the page; in the other types, the server performs the injection. DOM-based XSS generally involves server-controlled, trusted script that is sent to the client, such as Javascript that performs sanity checks on a form before the user submits it. If the server-supplied script processes user-supplied data and then injects it back into the web page (such as with dynamic HTML), then DOM-based XSS is possible.
            
            
            Once the malicious script is injected, the attacker can perform a variety of malicious activities. The attacker could transfer private information, such as cookies that may include session information, from the victim's machine to the attacker. The attacker could send malicious requests to a web site on behalf of the victim, which could be especially dangerous to the site if the victim has administrator privileges to manage that site. Phishing attacks could be used to emulate trusted web sites and trick the victim into entering a password, allowing the attacker to compromise the victim's account on that web site. Finally, the script could exploit a vulnerability in the web browser itself possibly taking over the victim's machine, sometimes referred to as "drive-by hacking."
            In many cases, the attack can be launched without the victim even being aware of it. Even with careful users, attackers frequently use a variety of methods to encode the malicious portion of the attack, such as URL encoding or Unicode, so the request looks less suspicious.
         
         

Fix information:
repo_url: https://github.com/rhuss/jolokia
commit_details: repo_url: https://github.com/rhuss/jolokia
author: Roland Huß
author_date: 2018-01-24 10:35:53+01:00
msg: fix: Verify a given 'mimeType' and/or 'callback' request parameter

So that only fixed values are possible, in order to avoid XSS attack
vectors.
repository: repo_url: https://github.com/rhuss/jolokia
repo_name: jolokia/jolokia
description: JMX on Capsaicin
repo_language: Java
owner: rhuss
file_changes: filename: AgentServlet.java
change_type: ModificationType.MODIFY
diff: @@ -264,20 +264,28 @@ public class AgentServlet extends HttpServlet {
     @SuppressWarnings({ "PMD.AvoidCatchingThrowable", "PMD.AvoidInstanceofChecksInCatchClause" })
     private void handle(ServletRequestHandler pReqHandler,HttpServletRequest pReq, HttpServletResponse pResp) throws IOException {
         JSONAware json = null;
+
         try {
             // Check access policy
             requestHandler.checkAccess(allowDnsReverseLookup ? pReq.getRemoteHost() : null,
                                        pReq.getRemoteAddr(),
                                        getOriginOrReferer(pReq));
 
+            // If a callback is given, check this is a valid javascript function name
+            validateCallbackIfGiven(pReq);
+
             // Remember the agent URL upon the first request. Needed for discovery
             updateAgentDetailsIfNeeded(pReq);
 
             // Dispatch for the proper HTTP request method
             json = handleSecurely(pReqHandler, pReq, pResp);
         } catch (Throwable exp) {
-            json = requestHandler.handleThrowable(
+            try {
+                json = requestHandler.handleThrowable(
                     exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp);
+            } catch (Throwable exp2) {
+                exp2.printStackTrace();
+            }
         } finally {
             setCorsHeader(pReq, pResp);
 
@@ -289,6 +297,7 @@ public class AgentServlet extends HttpServlet {
         }
     }
 
+
     private JSONAware handleSecurely(final ServletRequestHandler pReqHandler, final HttpServletRequest pReq, final HttpServletResponse pResp) throws IOException, PrivilegedActionException {
         Subject subject = (Subject) pReq.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE);
         if (subject != null) {
@@ -380,15 +389,6 @@ public class AgentServlet extends HttpServlet {
         }
     }
 
-    // Extract mime type for response (if not JSONP)
-    private String getMimeType(HttpServletRequest pReq) {
-        String requestMimeType = pReq.getParameter(ConfigKey.MIME_TYPE.getKeyValue());
-        if (requestMimeType != null) {
-            return requestMimeType;
-        }
-        return configMimeType;
-    }
-
     private boolean isStreamingEnabled(HttpServletRequest pReq) {
         String streamingFromReq = pReq.getParameter(ConfigKey.STREAMING.getKeyValue());
         if (streamingFromReq != null) {
@@ -470,8 +470,12 @@ public class AgentServlet extends HttpServlet {
 
     private void sendResponse(HttpServletResponse pResp, HttpServletRequest pReq, JSONAware pJson) throws IOException {
         String callback = pReq.getParameter(ConfigKey.CALLBACK.getKeyValue());
-        setContentType(pResp, callback != null ? "text/javascript" : getMimeType(pReq));
 
+        setContentType(pResp,
+                       MimeTypeUtil.getResponseMimeType(
+                           pReq.getParameter(ConfigKey.MIME_TYPE.getKeyValue()),
+                           configMimeType, callback
+                                                       ));
         pResp.setStatus(HttpServletResponse.SC_OK);
         setNoCacheHeaders(pResp);
         if (pJson == null) {
@@ -487,6 +491,12 @@ public class AgentServlet extends HttpServlet {
         }
     }
 
+    private void validateCallbackIfGiven(HttpServletRequest pReq) {
+        String callback = pReq.getParameter(ConfigKey.CALLBACK.getKeyValue());
+        if (callback != null && !MimeTypeUtil.isValidCallback(callback)) {
+            throw new IllegalArgumentException("Invalid callback name given, which must be a valid javascript function name");
+        }
+    }
     private void sendStreamingResponse(HttpServletResponse pResp, String pCallback, JSONStreamAware pJson) throws IOException {
         Writer writer = new OutputStreamWriter(pResp.getOutputStream(), "UTF-8");
         IoUtil.streamResponseAndClose(writer, pJson, pCallback);

programming_language: Java
filename: MimeTypeUtil.java
change_type: ModificationType.ADD
diff: @@ -0,0 +1,74 @@
+package org.jolokia.util;
+
+import java.util.regex.Pattern;
+
+/**
+ * Helper class for handling proper response mime types
+ *
+ * @author roland
+ * @since 24.01.18
+ */
+public class MimeTypeUtil {
+
+
+    /**
+     * Extract the response mime type. This value is calculated for different situations:
+     * <p>
+     * <ul>
+     * <li>If a callback is given and its valid, the mime type is "text/javascript"</li>
+     * <li>Otherwise:
+     * <ul>
+     * <li>If a valid mimeType is given in the request ("text/plain", "application/json"), then this
+     * mimet type is returned</li>
+     * <li>If another mimeType is given, then "text/plain" is used</li>
+     * <li>If no mimeType is given then a given default mime type is used, but also sanitized
+     * as described above</li>
+     * </ul>
+     * </li>
+     * </ul>
+     *
+     * @param pRequestMimeType the mimetype given in the request
+     * @param defaultMimeType  the default mime type to use if none is given in the request
+     * @param pCallback        a callback given (can be null)
+     */
+    public static String getResponseMimeType(String pRequestMimeType, String defaultMimeType, String pCallback) {
+
+        // For a valid given callback, return "text/javascript" for proper inclusion
+        if (pCallback != null && isValidCallback(pCallback)) {
+            return "text/javascript";
+        }
+
+        // Pick up mime time from request, but sanitize
+        if (pRequestMimeType != null) {
+            return sanitize(pRequestMimeType);
+        }
+
+        // Use the given default mime type (possibly picked up from a configuration)
+        return sanitize(defaultMimeType);
+    }
+
+    private static String sanitize(String mimeType) {
+        for (String accepted : new String[]{
+            "application/json",
+            "text/plain"
+        }) {
+            if (accepted.equalsIgnoreCase(mimeType)) {
+                return accepted;
+            }
+        }
+        return "text/plain";
+    }
+
+    /**
+     * Check that a callback matches a javascript function name. The argument must be not null
+     *
+     * @param pCallback callback to verify
+     * @return true if valud, false otherwise
+     */
+    public static boolean isValidCallback(String pCallback) {
+        Pattern validJavaScriptFunctionNamePattern =
+            Pattern.compile("^[$A-Z_][0-9A-Z_$]*$", Pattern.CASE_INSENSITIVE);
+        return validJavaScriptFunctionNamePattern.matcher(pCallback).matches();
+    }
+
+}
\ No newline at end of file

programming_language: Java
filename: AgentServletTest.java
change_type: ModificationType.MODIFY
diff: @@ -113,7 +113,7 @@ public class AgentServletTest {
     }
 
     @Test
-    public void initWithcustomAccessRestrictor() throws ServletException {
+    public void initWithCustomAccessRestrictor() throws ServletException {
         prepareStandardInitialisation();
         servlet.destroy();
     }
@@ -251,6 +251,44 @@ public class AgentServletTest {
         servlet.destroy();
     }
 
+    @Test
+    public void simpleGetWithWrongMimeType() throws ServletException, IOException {
+        checkMimeTypes("text/html", "text/plain");
+    }
+
+    @Test
+    public void simpleGetWithTextPlainMimeType() throws ServletException, IOException {
+        checkMimeTypes("text/plain", "text/plain");
+    }
+
+    @Test
+    public void simpleGetWithApplicationJsonMimeType() throws ServletException, IOException {
+        checkMimeTypes("application/json", "application/json");
+    }
+
+    private void checkMimeTypes(String given, final String expected) throws ServletException, IOException {
+        prepareStandardInitialisation();
+
+        initRequestResponseMocks(
+            getStandardRequestSetup(),
+            new Runnable() {
+                public void run() {
+                    response.setCharacterEncoding("utf-8");
+                    // The default content type
+                    response.setContentType(expected);
+                    response.setStatus(200);
+                }
+            });
+        expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
+        expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(given);
+        replay(request, response);
+
+        servlet.doGet(request, response);
+
+        verifyMocks();
+        servlet.destroy();
+    }
+
     @Test
     public void simpleGetWithNoReverseDnsLookupFalse() throws ServletException, IOException {
         checkNoReverseDns(false,"127.0.0.1");
@@ -484,6 +522,7 @@ public class AgentServletTest {
                 });
         expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
         expect(request.getAttribute("subject")).andReturn(null);
+        expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);
 
         replay(request, response);
 
@@ -493,6 +532,30 @@ public class AgentServletTest {
         servlet.destroy();
     }
 
+    @Test
+    public void withInvalidCallback() throws IOException, ServletException {
+        servlet = new AgentServlet(new AllowAllRestrictor());
+        initConfigMocks(null, null,"Error 400", IllegalArgumentException.class);
+        replay(config, context);
+        servlet.init(config);
+        ByteArrayOutputStream sw = initRequestResponseMocks(
+            "doSomethingEvil(); myCallback",
+            getStandardRequestSetup(),
+            getStandardResponseSetup());
+        expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
+        expect(request.getAttribute("subject")).andReturn(null);
+        expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);
+
+        replay(request, response);
+
+        servlet.doGet(request, response);
+        String resp = sw.toString();
+        assertTrue(resp.contains("error_type"));
+        assertTrue(resp.contains("IllegalArgumentException"));
+        assertTrue(resp.matches(".*status.*400.*"));
+        servlet.destroy();
+    }
+
     @Test
     public void withException() throws ServletException, IOException {
         servlet = new AgentServlet(new AllowAllRestrictor());
@@ -606,7 +669,7 @@ public class AgentServletTest {
         response = createMock(HttpServletResponse.class);
         setNoCacheHeaders(response);
 
-        expect(request.getParameter(ConfigKey.CALLBACK.getKeyValue())).andReturn(callback);
+        expect(request.getParameter(ConfigKey.CALLBACK.getKeyValue())).andReturn(callback).anyTimes();
         requestSetup.run();
         responseSetup.run();
 
@@ -648,6 +711,7 @@ public class AgentServletTest {
         return new Runnable() {
             public void run() {
                 response.setCharacterEncoding("utf-8");
+                // The default content type
                 response.setContentType("text/plain");
                 response.setStatus(200);
             }
@@ -690,7 +754,7 @@ public class AgentServletTest {
                 expect(request.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE)).andReturn(null);
 
                 expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
-                expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
+                expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain").anyTimes();
                 StringBuffer buf = new StringBuffer();
                 buf.append(url).append(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
                 expect(request.getRequestURL()).andReturn(buf);

programming_language: Java
filename: JolokiaHttpHandler.java
change_type: ModificationType.MODIFY
diff: @@ -224,6 +224,9 @@ public class JolokiaHttpHandler implements HttpHandler {
                                        extractOriginOrReferer(pExchange));
             String method = pExchange.getRequestMethod();
 
+            // If a callback is given, check this is a valid javascript function name
+            validateCallbackIfGiven(parsedUri);
+
             // Dispatch for the proper HTTP request method
             if ("GET".equalsIgnoreCase(method)) {
                 setHeaders(pExchange);
@@ -244,6 +247,14 @@ public class JolokiaHttpHandler implements HttpHandler {
         }
     }
 
+
+    private void validateCallbackIfGiven(ParsedUri pUri) {
+        String callback = pUri.getParameter(ConfigKey.CALLBACK.getKeyValue());
+        if (callback != null && !MimeTypeUtil.isValidCallback(callback)) {
+            throw new IllegalArgumentException("Invalid callback name given, which must be a valid javascript function name");
+        }
+    }
+
     // ========================================================================
 
     // Used for checking origin or referer is an origin policy is enabled
@@ -342,10 +353,11 @@ public class JolokiaHttpHandler implements HttpHandler {
         Headers headers = pExchange.getResponseHeaders();
         if (pJson != null) {
             headers.set("Content-Type", getMimeType(pParsedUri) + "; charset=utf-8");
-            String callback = pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue());
             pExchange.sendResponseHeaders(200, 0);
             Writer writer = new OutputStreamWriter(pExchange.getResponseBody(), "UTF-8");
-            IoUtil.streamResponseAndClose(writer, pJson, callback);
+
+            String callback = pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue());
+            IoUtil.streamResponseAndClose(writer, pJson, callback != null && MimeTypeUtil.isValidCallback(callback) ? callback : null);
         } else {
             headers.set("Content-Type", "text/plain");
             pExchange.sendResponseHeaders(200,-1);
@@ -360,7 +372,7 @@ public class JolokiaHttpHandler implements HttpHandler {
                 headers.set("Content-Type", getMimeType(pParsedUri) + "; charset=utf-8");
                 String json = pJson.toJSONString();
                 String callback = pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue());
-                String content = callback == null ? json : callback + "(" + json + ");";
+                String content = callback != null && MimeTypeUtil.isValidCallback(callback) ? callback + "(" + json + ");" : json;
                 byte[] response = content.getBytes("UTF8");
                 pExchange.sendResponseHeaders(200,response.length);
                 out = pExchange.getResponseBody();
@@ -380,16 +392,10 @@ public class JolokiaHttpHandler implements HttpHandler {
 
     // Get the proper mime type according to configuration
     private String getMimeType(ParsedUri pParsedUri) {
-        if (pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue()) != null) {
-            return "text/javascript";
-        } else {
-            String mimeType = pParsedUri.getParameter(ConfigKey.MIME_TYPE.getKeyValue());
-            if (mimeType != null) {
-                return mimeType;
-            }
-            mimeType = configuration.get(ConfigKey.MIME_TYPE);
-            return mimeType != null ? mimeType : ConfigKey.MIME_TYPE.getDefaultValue();
-        }
+        return MimeTypeUtil.getResponseMimeType(
+            pParsedUri.getParameter(ConfigKey.MIME_TYPE.getKeyValue()),
+            configuration.get(ConfigKey.MIME_TYPE),
+            pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue()));
     }
 
     // Creat a log handler from either the given class or by creating a default log handler printing

programming_language: Java
filename: JolokiaHttpHandlerTest.java
change_type: ModificationType.MODIFY
diff: @@ -74,6 +74,67 @@ public class JolokiaHttpHandlerTest {
         assertTrue(result.startsWith("data({"));
     }
 
+
+    @Test
+    public void testInvalidMimeType() throws IOException, URISyntaxException {
+        checkMimeType("text/html", "text/plain");
+    }
+
+    @Test
+    public void testMimeTypeApplicationJson() throws IOException, URISyntaxException {
+        checkMimeType("application/json", "application/json");
+    }
+
+    private void checkMimeType(String given, String expected) throws IOException, URISyntaxException {
+        HttpExchange exchange = prepareExchange("http://localhost:8080/jolokia/read/java.lang:type=Memory/HeapMemoryUsage?mimeType=" + given);
+
+        // Simple GET method
+        expect(exchange.getRequestMethod()).andReturn("GET");
+
+        Headers header = new Headers();
+        ByteArrayOutputStream out = prepareResponse(handler, exchange, header);
+
+        handler.doHandle(exchange);
+
+        assertEquals(header.getFirst("content-type"),expected + "; charset=utf-8");
+    }
+
+    @Test
+    public void testInvalidCallbackGetStreaming() throws IOException, URISyntaxException, ParseException {
+        checkInvalidCallback(true);
+    }
+
+    @Test
+    public void testInvalidCallbackGetNonStreaming() throws IOException, URISyntaxException, ParseException {
+        checkInvalidCallback(false);
+    }
+
+    private void checkInvalidCallback(boolean streaming) throws URISyntaxException, IOException, ParseException {
+        JolokiaHttpHandler handler = new JolokiaHttpHandler(getConfig(ConfigKey.SERIALIZE_EXCEPTION, Boolean.toString(streaming)));
+        handler.start(false);
+
+        HttpExchange exchange = prepareExchange("http://localhost:8080/jolokia/read/java.lang:type=Memory/HeapMemoryUsage?callback=evilCallback();data");
+
+        // Simple GET method
+        expect(exchange.getRequestMethod()).andReturn("GET");
+
+        Headers header = new Headers();
+        ByteArrayOutputStream out = prepareResponse(handler, exchange, header);
+
+        handler.doHandle(exchange);
+
+        assertEquals(header.getFirst("content-type"),"text/plain; charset=utf-8");
+        String result = out.toString("utf-8");
+        JSONObject resp = (JSONObject) new JSONParser().parse(result);
+        assertTrue(resp.containsKey("error"));
+        assertEquals(resp.get("error_type"), IllegalArgumentException.class.getName());
+        assertTrue(((String) resp.get("error")).contains("callback"));
+        assertFalse(((String) resp.get("error")).contains("evilCallback"));
+
+        handler.stop();
+    }
+
+
     @Test
     public void testCallbackPost() throws URISyntaxException, IOException, java.text.ParseException {
         HttpExchange exchange = prepareExchange("http://localhost:8080/jolokia?callback=data",
@@ -81,7 +142,6 @@ public class JolokiaHttpHandlerTest {
                                                 "Origin",null
                                                );
 
-        // Simple GET method
         prepareMemoryPostReadRequest(exchange);
         Headers header = new Headers();
         ByteArrayOutputStream out = prepareResponse(handler, exchange, header);

programming_language: Java