struts2远程执行漏洞

来源:互联网 发布:回转企鹅罐 知乎 编辑:程序博客网 时间:2024/04/30 04:44

    原文:https://communities.coverity.com/blogs/security/2013/05/29/struts2-remote-code-execution-via-ognl-injection

 

Struts 2 Remote Code Execution via OGNL Double Evaluation

发表人 Jon Passki 位置 Security Research Laboratory 打开 2013-5-29 9:08:40                                            

                    

Advisory

 

Overview

(Note: this write-up uses the Maven sample application provided by Struts2. Refer to the Appendix section at the bottom to install the application. References to the blank-archetype application refer to this sample application.)

From the Struts 2 website

Apache Struts 2 is an elegant, extensible framework for creating enterprise-ready Java web applications. The framework is designed to streamline the full development cycle, from building, to deploying, to maintaining applications over time.

Struts 2 heavily utilizes OGNL as a templating / expression language. OGNL, similar to other expression languages, is vulnerable to a class of issues informally termed "double evaluation". That is, the value of an OGNL expression is mistakenly evaluated again as an OGNL expression. For a background on previous OGNL double evaluation issues, I recommend@meder's"Milking a horse or executing remote code in modern Java frameworks" presentation. (The exploit used below is based on @meder's exploit, just condensed.) For other examples of double evaluation in different expression languages, check out Aspect Security's "Remote Code with Expression Language".

 

Struts 2 calls its controllers Actions. Actions are mapped to URLs and views within anXML configuration file or via Java annotations. For a good background on Struts 2 andActions, refer to their "Getting Started" page.

 

Struts 2 allows a developer to configure wildcard mappings in its XML configuration files. The blank-archetype application has the following wildcard example in its XML configuration:

 

  1. <action name="*" class="tutorial2.example.ExampleSupport">  
  2.   <result>/example/{1}.jsp</result>  
  3. </action>  

 

This allows one to specify an arbitrary Action name. If the name doesn't match any of the other more specific mappings in the XML configuration (or possibly others annotated in the Java code), then this acts as a catch-all. The Action name provided is substituted as a component of the file name. Struts then dispatches to the selfsame JSP defined in theresult section.

 

Vulnerability and Exploit

There exists a vulnerability in this Action name to replacement mapping. If the Action name provided is in the form of${STUFF_HERE} or %{STUFF_HERE}, and the contents of the expression areOGNL, then Struts2 unsafely double evaluates the contents.

To view this exploit, start up the blank-archetype application using jetty:run. Thefollowing URL exploits a vulnerability within the replacement support in Struts 2. If the exploit is successful, something similar to the following should be displayed:

HTTP ERROR 404

Problem accessing /struts2-blank/example/0.jsp. Reason:

Not Found

Note the "0.jsp" part in the 404 page. When successfully executed, Process.waitFor returns a value of "0". This is then used as the JSP file name, "0.jsp". This implies thetouch aaa executed successfully. A patched version doesn't have a return value since the process never executed.

 

Root Cause Analysis

Using JavaSnoop, instrumenting the blank-archetype application application, and setting canaries for strings to match against the payload URL showed numerous potential traces. Scoping the trace toorg.apache.struts2 packages shows an interesting call to StrutsResultSupport.conditionalParse:

 

  1. /** 
  2. * Parses the parameter for OGNL expressions against the valuestack 
  3. * 
  4. * @param param The parameter value 
  5. * @param invocation The action invocation instance 
  6. * @return The resulting string 
  7. */  
  8. protected String conditionalParse(String param, ActionInvocation invocation) {  
  9.     if (parse && param != null && invocation != null) {  
  10.         return TextParseUtil.translateVariables(param, invocation.getStack(),  
  11.                 new TextParseUtil.ParsedValueEvaluator() {  
  12.                     public Object evaluate(String parsedValue) {  
  13.                         if (encode) {  
  14.                             if (parsedValue != null) {  
  15.                                 try {  
  16.                                     // use UTF-8 as this is the recommended encoding by W3C to  
  17.                                     // avoid incompatibilities.  
  18.                                     return URLEncoder.encode(parsedValue, "UTF-8");  
  19.                                 }  
  20.                                 catch(UnsupportedEncodingException e) {  
  21.                                     if (LOG.isWarnEnabled()) {  
  22.                                         LOG.warn("error while trying to encode ["+parsedValue+"]", e);  
  23.                                     }  
  24.                                 }  
  25.                             }  
  26.                         }  
  27.                         return parsedValue;  
  28.                     }  
  29.         });  
  30.     } else {  
  31.         return param;  
  32.     }  
  33. }  

 

The method above is called from the StrutsResultSupport.execute(ActionInvocation). It then callsTextParseUtil.translateVariables:

 

  1. /** 
  2.  * Function similarly as {@link #translateVariables(char, String, ValueStack)} 
  3.  * except for the introduction of an additional <code>evaluator</code> that allows 
  4.  * the parsed value to be evaluated by the <code>evaluator</code>. The <code>evaluator</code> 
  5.  * could be null, if it is it will just be skipped as if it is just calling 
  6.  * {@link #translateVariables(char, String, ValueStack)}. 
  7.  * 
  8.  * <p/> 
  9.  * 
  10.  * A typical use-case would be when we need to URL Encode the parsed value. To do so 
  11.  * we could just supply a URLEncodingEvaluator for example. 
  12.  * 
  13.  * @param expression 
  14.  * @param stack 
  15.  * @param evaluator The parsed Value evaluator (could be null). 
  16.  * @return the parsed (and possibly evaluated) variable String. 
  17.  */  
  18. public static String translateVariables(String expression, ValueStack stack, ParsedValueEvaluator evaluator) {  
  19.   return translateVariables(new char[]{'$''%'}, expression, stack, String.class, evaluator).toString();  
  20. }  

 

This method evaluates expressions surrounded with ${} or %{}. The subsequent call totranslateVariables method evaluates the expression via theparser.evaluate call:

 

  1. /** 
  2.  * Converted object from variable translation. 
  3.  * 
  4.  * @param open 
  5.  * @param expression 
  6.  * @param stack 
  7.  * @param asType 
  8.  * @param evaluator 
  9.  * @return Converted object from variable translation. 
  10.  */  
  11. public static Object translateVariables(char[] openChars, String expression, final ValueStack stack, final Class asType, final ParsedValueEvaluator evaluator, int maxLoopCount) {  
  12.     ParsedValueEvaluator ognlEval = new ParsedValueEvaluator() {  
  13.         public Object evaluate(String parsedValue) {  
  14.             Object o = stack.findValue(parsedValue, asType);  
  15.             if (evaluator != null && o != null) {  
  16.                 o = evaluator.evaluate(o.toString());  
  17.             }  
  18.             return o;  
  19.         }  
  20.     };  
  21.     TextParser parser = ((Container)stack.getContext().get(ActionContext.CONTAINER)).getInstance(TextParser.class);  
  22.     XWorkConverter conv = ((Container)stack.getContext().get(ActionContext.CONTAINER)).getInstance(XWorkConverter.class);  
  23.     Object result = parser.evaluate(openChars, expression, ognlEval, maxLoopCount);  
  24.     return conv.convertValue(stack.getContext(), result, asType);  
  25. }  

 

That passes the expression to an instance of OgnlTextParser.evaluate. And then it's game over.

 

Other Vectors

Suspicious calls to TextParseUtil.translateVariables were also examined for exploitability.

 

org.apache.struts2.dispatcher.HttpHeaderResult.execute (Tested)

HttpHeaderResult.execute has the following call to TextParseUtil.translateVariables:

 

  1. if (headers != null) {  
  2.     for (Map.Entry<String, String> entry : headers.entrySet()) {  
  3.         String value = entry.getValue();  
  4.         String finalValue = parse ? TextParseUtil.translateVariables(value, stack) : value;  
  5.         response.addHeader(entry.getKey(), finalValue);  
  6.     }  
  7. }  

 

The blank-archetype application's HelloWorld XML example was modified below to test out the call. This is probably a very unlikely scenario and also can be mitigated by the<param name="parse">false</param> setting. (By default, this value is true.) In this case, the${message} value is user-controllable within the HelloWorld class. This tainted value is then supplied as a header. While it's an obvious header injection, it's also a RCE vector.

 

  1. <action name="HelloWorld" class="com.coverity.internal.examples.example.HelloWorld">  
  2.   <result name="success">/example/HelloWorld.jsp</result>  
  3.   <result name="foobar" type="httpheader">  
  4.     <param name="headers.foobar">${message}</param>  
  5.   </result>  
  6. </action>  

 

org.apache.struts2.views.util.DefaultUrlHelper.* (Tested)

Pretty much every method in the DefaultUrlHelper class allows for RCE if one of the parameters is tainted. This is because of theDefaultUrlHelper.translateVariable method is called by most methods in the class. This class is also heavily utilized throughout Struts2 as the default UrlHelper class viastruts-default.xml.

 

Here is an instance of the defect, mocked up from the blank-archetype application HelloWorld.jsp:

 

  1. <s:url id="url" action="HelloWorld">  
  2.     <s:param name="request_locale"><s:property value="message"/></s:param>  
  3. </s:url>  

 

Assume the s:property 'message' is tainted via ?message=${OGNL_HERE}. Since thes:url / URL component uses the DefaultUrlHandler.urlRenderer (viaServletUrlRenderer), the parameter is double evaluated as OGNL.

 

org.apache.struts2.util.URLBean.getURL (Untested)

URLBean seems to mainly be used in Velocity via a macro. If URLBean is called w/o a setPage() method and either the addParameter() method contains tainted data or noaddParameter() method calls occur, then URLBean seems susceptible to RCE via the DefaultUrlHelper issue above.

 

Non-Vectors

Some potential vectors that seemed to double evaluate OGNL were tested but found not to be exploitable using this technique.

When the action name is used as a replacement value within the method attribute of the Action, the replacement value is not double evaluated. Rather, the unevaluated value is passed as a method name via reflection. The blank-archetype application has this example, which is not exploitable:

 

  1. <action name="Login_*" method="{1}" class="tutorial.example.Login">  
  2.   <result name="input">/example/Login.jsp</result>  
  3.   <result type="redirectAction">Menu</result>  
  4. </action>  

 

Another non-vector tested in the blank-archetype application is to enable Dynamic Method Invocation. Then modify HelloWorld Action mapping in the blank-archetype application as follows:

 

  1. <action name="HelloWorld" class="tutorial.example.HelloWorld">  
  2.   <result>/example/${message}.jsp</result>  
  3. </action>  

 

Finally, call the getMessage function on the HelloWorld Action (HelloWorld!getMessage?message=${PAYLOAD}). Test stack traces didn't show the OGNL expression being evaluated twice.

 

Untested

Struts2 annotations may be susceptible but have not been tested.

 

Testing

Outside of testing for vulnerable versions of Struts 2, testers can use a blind-ish dynamic technique:

  • Identify Actions (usually via a .action suffix) and fingerprint responses to the Actions. For this example URLhttp://www.example.com/app/Bar.action, the Action name isBar.
  • For each Action, substitute the Action name  with ACTION_NAME in the following expression:$%7B%23foo='ACTION_NAME',%23foo%7D. For example: $%7B%23foo='Bar',%23foo%7D.
  • Replace the Action name in the URL with the substituted expression. For example:http://www.example.com/app/$%7B%23foo='Bar',%23foo%7D.action.
  • If the Action is susceptible to this double evaluation vector, the application ought to return the same page as before. If it's not vulnerable, a 404 or other page will probably be returned.

To test out the Welcome.action blank-archetype above via jetty:run, usethis URL.

 

Remedy

Struts developers recommend upgrading to 2.3.14.2. Refer to S2-013 and S2-014 for details. The Struts developers mitigate the effects of double evaluation. While double evaluation still occurs within the sample application, remote code execution is not possible using @meder's vector.

 

Maven Appendix

First, get Maven. Then create an application based on theblank-archetype.

 

  1. mvn archetype:generate -B -DgroupId=tutorial -DartifactId=tutorial -DarchetypeGroupId=org.apache.struts -DarchetypeArtifactId=struts2-archetype-blank  
  2. cd tutorial  # ensure the struts2 entry in the pom.xml points to 2.3.14  
  3. mvn package jetty:run  

 

To test out the application, try accessing the Welcome Action by navigating tofollowing URL.