Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze all kinds of RCE loopholes in Spring family bucket

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)05/31 Report--

How to analyze all kinds of RCE loopholes in Spring family bucket? I believe that many inexperienced people are at a loss about this. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Brief introduction of Spring Family Bucket

With the development of Spring, the content of the whole family bucket is very huge. This paper mainly introduces five key parts, namely spring framework, springboot, spring cloud, spring security and spring mvc. Spring framework is often mentioned as spring, which is the most basic underlying architecture of all spring content, including spring mvc, springboot, spring core, IOC, AOP and so on. Spring mvc is a MVC framework in spring, which is mainly used to develop web applications and network interfaces, but it needs to configure a large number of xml files before use, which is more tedious, so there is springboot, which has built-in tomcat and built-in default XML configuration information, which facilitates the use of users. The following picture shows the relationship between them visually.

Spring security is mainly used for authentication to ensure security. Based on Spring Boot, Spring Cloud simplifies the development of distributed system and integrates various service management capabilities such as service discovery, configuration management, message bus, load balancing, circuit breaker, data monitoring and so on.

The whole spring family has four important basic concepts, namely, IOC, Context, Bean and AOP. Among them, IOC refers to control inversion, which is reflected in spring is to reclaim the creation rights of object attributes, and then configure them uniformly to achieve decoupling to facilitate code maintenance. Instead of specifying a class directly, you can use autowired annotations to declare the real type of the object in the bean in the XML file. Specific examples are as follows:

Public class WelcomeController {@ Autowired private WelcomeService service; @ RequestMapping ("/ welcome") public String welcome () {return service.retrieveWelcomeMessage ();}}

Spring refers to all created or managed objects as bean and manages them in a unified context context. As for AOP, it unifies the connection layer of each MVC architecture, which enhances the robustness of the code. The following picture vividly describes the above basic concepts.

Introduction of each sub-component

Since the development of Spring, the whole system continues to grow, and the sub-classification is very large. Here we only briefly introduce some of the components involved.

The first is the Spring Websocket,Spring built-in simple message broker. This agent processes subscription requests from clients, stores them in memory, and broadcasts messages to connected clients with matching targets. Spring Data is an open source framework for simplifying database access and supporting cloud services. Its main goal is to make database access easy and fast. Spring Data Commons is the basic framework shared by all sub-projects under Spring Data, and all implementations in the Spring Data family are based on Spring Data Commons. To put it simply, Spring Data REST automates a large number of REST template interfaces that we need to write, and conforms to the HAL specification. Spring Web Flow is an extension of Spring MVC that supports the development of process-based applications that separate the definition of a process from the classes and views that implement the behavior of the process.

Usage and distribution

According to the statistics of the whole network, more than 800000 websites use Spring, most of which are concentrated in the United States, and China ranks second in terms of usage. Among them, Hong Kong, Beijing, Shanghai and Guangdong have the highest usage. Through the data statistics and bar chart of the cyberspace search engine, as shown in the following figure.

Vulnerability background introduction (SpEL usage) what is 0x10 SpEL

SpEL is an expression language based on spring, similar to struts's OGNL, which can dynamically execute some operations or even instructions at run time, similar to the reflection function of Java. In terms of usage, it is divided into three categories, namely, directly used in annotations, used in XML files, and directly used in code blocks.

What can 0x20 SpEL do?

● basic expression

It includes logic operation, trinomial operation and regular expression and so on.

● class operation expression

Object method calls, object property references, custom functions and class instantiation, and so on.

● set (platform does not allow jihe) combined operation expression

Dictionary access, projection and modification, and so on.

● other expressions

Template expression

0x30 SpEL demo

0x31 annotation-based SpEL

It can be used in combination with the @ Value annotation of sping to initialize the attribute value of Bean directly.

@ RestControllerclass Sangfor {@ Value (value = "${'aaa'.toUpperCase ()}") private String test; public String getTest () {return test;} public void setTest (String value) {this.test = value;}}

In this case, the value of test can be initialized directly to AAA.

In addition, there are many other ways to use annotations that can be combined with the four usage patterns of the expressions mentioned above.

0x32 SpEL based on XML

You can use SpEL expressions directly in the XML file as follows:

Public class SpEL {public static void main (String [] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext ("test.xml"); String hello = ctx.getBean ("hello", String.class); System.out.println (hello);}}

The above code will output Hello wordings, and you can see that the value of world is found recursively and returned successfully.

0x33 string operation

Import org.springframework.expression.Expression;import org.springframework.expression.ExpressionParser;import org.springframework.expression.spel.standard.SpelExpressionParser;public class SpEL {public static void main (String [] args) {ExpressionParser parser = new SpelExpressionParser (); / / Expression exp = parser.parse_Expression ("'Hello'. Concat ('World')"); Expression exp = parser.parse_Expression ("' Hello'+ 'World'"); String message = (String) exp.getValue () System.out.println (message);}}

Note: similar string operations such as toUpperCase (), substr (), etc.

0x34 class related operations

Using T (class) to represent an instance of a class, except for java.lang 's package, the rest of the package needs to be specified. In addition, you can access the static methods and static fields of the class, and even instantiate the class.

Public class SpEL {public static void main (String [] args) {ExpressionParser parser = new SpelExpressionParser (); Expression exp = parser.parse_Expression ("T (Runtime). GetRuntime (). Exec ('calc.exe')"); Object message = exp.getValue (); System.out.println (message);}}

If you do the above, you can eventually execute the command and pop up the calculator. This is also the form of exploitation of SpEL RCE vulnerabilities later.

0x35 set (platform is not allowed to send jihe) with related operations

Public class SpEL {public static void main (String [] args) {ExpressionParser parser = new SpelExpressionParser (); Expression exp = parser.parse_Expression ("{'sangfor',' busyer', 'test'}"); List message = (List) exp.getValue (); System.out.println (message.get (1)); / / busyer}}

With the above operation, you can convert the string into an array, and finally output busyer.

SpEL principle

First of all, let's look at a few concepts:

● expression

Can be thought of as the contents of the passed-in string

● parser

Parse a string into the content of an expression

● context

The environment in which the expression object executes

● root object and active context object

The root object is the default active context object, and the active context object represents the object operated by the current expression

The specific process is as follows, which is actually lexical analysis and syntactic analysis in the compilation principle:

(1) first give the expression 1 to 2.

(2) then given the SpelExpressionParser parser, the parser implements the analysis in the figure above

(3) define the context object. This is optional. Default is StandardEvaluationContext.

(4) use expression objects to evaluate, such as getValue

The specific code is as follows:

ExpressionParser parser = new SpelExpressionParser (); Expression exp = parser.parse_Expression ("{'sangfor',' busyer', 'test'}"); / / StandardEvaluationContext context = new StandardEvaluationContext (); String message = (String) exp.getValue (context, String.class)

Root and this

In SpEL, # root always refers to the initial expression object, while # this always refers to the current expression object, with which you can directly manipulate the current context.

SimpleEvaluationContext and StandardEvaluationContext

SimpleEvaluationContext: does not include dangerous operations related to the class, so it is relatively safe

StandardEvaluationContext: contains all the features, there are risks

Introduction of high-risk vulnerabilities

Through the collection and collation of Spring vulnerabilities to filter out the high-risk vulnerabilities that have a great impact on remote code execution, the following list can be obtained:

As can be seen from the above table, these vulnerabilities are distributed among different subcategories of Spring, and most of them are lower versions. Users can easily circumvent these vulnerabilities as long as they upgrade the higher version and pay attention to the new vulnerability information in time. Although there are no related loopholes recently, these high-risk loopholes can not be ignored. Most of the vulnerabilities can be successfully attacked without complex configuration, thus executing arbitrary code and causing great harm. Therefore, in the process of using Spring for development, developers must pay attention to its historical risk points, avoid high-risk vulnerabilities as far as possible, and reduce unnecessary configuration information modification.

Vulnerability exploitation chain

The above vulnerabilities can be directly obtained without relying on other Spring vulnerabilities. The following figure provides a brief overview of how to exploit them:

Analysis of highly available vulnerabilities

1 CVE-2018-1270

1.1 threat level

Serious

1.2 scope of influence

Spring Framework 5.0-5.0.5

Spring Framework 4.3-4.3.15

1.3 difficulty of utilization

simple

1.4 vulnerability description

In the vulnerable version of Spring Framework described above, applications are allowed to create WebSocket through an in-memory STOMP agent of the spring-messaging module. An attacker can send a message to the agent, resulting in a remote code execution attack.

1.5 vulnerability analysis

Clicking connect will first trigger the addSubscriptionInternal method in DefaultSubscriptionRegistry.java

Line 80 takes out the value of the selector field in the header, which is the malicious expression we passed in before, and then to line 83, we are very familiar with this step, using the parser to parse the expression, obviously at this time there is another getValue method triggered and the expression we passed in can be executed directly without using simpleEvaluationContext.

When monitoring network traffic and finding later send information, the message will be distributed to different subscribers, and the forwarded message will also contain the context of the previous connect, that is, the expression will be included.

So, try typing something randomly into the text box, then click Send, and eventually trigger the sendMessageToSubscribers method in SimpleBrokerMessageHandler.java as follows:

Go on to the findSubscriptions method, and keep going down, you can finally find that the expresion in the context is extracted in the filterSubscriptions method in DefaultSubscriptionRegistry.java, and the context is specified using StandardEvaluationContext, that is, the code can be executed directly without any restrictions. And finally in line 164, use the getValue method to trigger the vulnerability and pop up the calculator.

1.6 Patch Analysis

The patch directly replaces the above StandardEvaluationContext with SimpleEvaluationContext, which avoids the loading of malicious classes.

2 CVE-2018-1273

2.1 threat level

Serious

2.2 scope of influence

Spring Data Commons 1.13-1.13.10 (Ingalls SR10)

Spring Data REST 2.6-2.6.10 (Ingalls SR10)

Spring Data Commons 2.0 to 2.0.5 (Kay SR5)

Spring Data REST 3.0-3.0.5 (Kay SR5)

2.3 difficulty of utilization

simple

2.4 vulnerability description

There is a remote code execution vulnerability in the Spring Data Commons component, where an attacker can construct SPEL expressions containing malicious code to implement remote code attacks and directly gain server control privileges.

2.5 vulnerability analysis

From the / users entry above, the user name will eventually be called into the MapPropertyAccessor static class to process the user name. The conditions that need to be met for SpEL injection are included in this class:

● first creates the parser:

● then uses the Standard context

● then contains the expression to be parsed

● finally uses setValue to trigger

2.6 Patch Analysis

The patch still directly replaces the above StandardEvaluationContext with SimpleEvaluationContext, which avoids the loading of malicious classes.

3 CNVD-2016-04742

3.1 threat level

Serious

3.2 scope of influence

Springboot 1.1.0-1.1.12

Springboot 1.2.0-1.2.7

Springboot 1.3.0

3.3 difficulty of utilization

simple

3.4 vulnerability description

The lower version of springboot uses spel expressions when dealing with internal 500 errors, and recursively parses nested ones, in which the message parameter is passed from the outside, and the user can construct a spel expression to achieve the effect of remote code execution.

3.5 vulnerability analysis

By accessing the URL above, you can access our controller and immediately throw an exception as follows:

Enter the exception code, and after lengthy code debugging, you can finally come to the render method of the key point:

Then go to the render method, where the replacePlaceholders method will replace the spel expression in the shape of ${}:

Enter the method to view, and finally enter the parseStringValue method, which loops to replace the contents of ${} in the HTML string of the error page with ${}, and the ${message} is the value we passed in.

So we can construct our payload and continue to parse the spel with the help of his loop, resulting in arbitrary code execution. The code for parsing spel is as follows:

3.6 Patch Analysis

Limit the value of secondary parsing by adding a NonRecursivePropertyPlaceholderHelper class:

4 CVE-2017-8046

4.1 threat level

Serious

4.2 scope of influence

Spring Data REST prior to 3.0.1 and Spring Boot versions prior to 1.5.9

Spring Data REST prior to 2.6.9 Spring Boot versions prior to 1.5.9

4.3 difficulty of utilization

simple

4.4 vulnerability description

When a user updates a value locally using the PATCH method, the path parameter is passed into the SpEL expression, which causes the code to execute.

4.5 vulnerability analysis

Execute the above payload and locate the entry to the program as follows:

(note: this class is in springmvc and its name is JsonPatchHandler)

Let's focus on this trinomial operation, where the judgment is to see whether the HTTP method is PATCH and content-type is the one we mentioned above, and then enter the this.applyPatch method, and then enter the corresponding processor according to the replace field we specified:

Then instantiate patchOperation and initialize the spel parser:

Finally, call setValue to trigger:

4.6 Patch Analysis

Here, take the repair scheme in 2.6.9 as an example, instead of directly setvalue in perform, we first do a parameter validity check (the SpelPath class is added here), and use the parameters in path with'.' Split, and then determine whether it is an attribute of the class in turn, and directly report an error as long as there is no one, thus solving the above problem. Some of the patch images are as follows:

5 CVE-2017-4971

5.1 threat level

Medium and dangerous

5.2 scope of influence

Spring Web Flow 2.4.0 ~ 2.4.4

Spring Web Flow 2.4.4 ~ 2.4.8

5.3 difficulty of utilization

Higher

5.4 vulnerability description

When a user uses an affected version of Spring Web Flow, if view-state is configured, but the corresponding binder is not configured, and the default false value of useSpringBeanBinding is not changed, when an attacker constructs a special http request, it can cause SpEL expression injection, resulting in a remote code execution vulnerability.

5.5 vulnerability analysis

First, by executing the confirm request, the breakpoint goes to the following location:

Here you can find that you can choose which processing method to enter by determining whether binderConfiguration is empty, where the binderConfiguration value refers to the binder content configured in the configuration file. Take a closer look at these two processing methods. In fact, all SpEL expressions are used, but the parameters passed in the addModelBindings method are the binder mentioned above, which are written in the xml file and cannot be changed, so consider entering the addDefaultMapping method without configuring binder.

As mentioned above, the function of the addDefaultMappings method is to traverse all the parameters, including the GET parameters and the parameters in POST, and then determine whether they start with "_" one by one, and enter the addEmptyValueMapping method for processing if they match, otherwise enter the addDefaultMapping method for processing. The trigger for this vulnerability is the one above, so let's take a closer look at the addEmptyValueMapping method.

You can see that this method parses the incoming variable name with an SpEL expression and later uses a get operation, which can lead to a vulnerability.

5.6 Patch Analysis

Check the official patch source code as follows:

The expression type is replaced with BeanWrapperExpressionParser, which avoids this problem because the internal implementation of the type cannot handle the class.

However, it is also mentioned above that if the parameter type does not start with "_", it will enter the addDefaultMapping method. Let's go to this method to check:

You can see that the passed-in parameters are also parsed here, but there is no obvious get method to trigger, so continue to look for the get method. First of all, the parser is put into the mapper, so let's focus on tracking the use of the mapper.

First of all, you can find that you go back to the previous bind method step by step, and you can find that the last line operates on the mapper and follows up the map method:

This is where the get operation takes place, which triggers the vulnerability again.

In this regard, it may also have nothing to do with this, the authorities eventually replaced the global parser with SimpleEvaluationContext to completely solve this problem.

6 CNVD-2019-11630

6.1 threat level

Serious

6.2 scope of influence

Spring Boot 1-1.4

Spring Boot 2.x

6.3 difficulty of utilization

simple

6.4 vulnerability description

When the user modifies the location of the spring.cloud.bootstrap.location through the env path, sets the address to a malicious address, and then triggers it using the refresh interface, it can cause the target to load the file in the malicious address and execute arbitrary code remotely.

6.5 vulnerability analysis

Set up the environment and attack as described above, and search for environment and refresh in spring-cloud-context-1.2.0.RELEASE.jar, and then follow up the breakpoint. You can find that the first env change will reflect the following:

In fact, it is to update the property value of the variable in the environment.

Then take a look at the key point refresh API. First, once the refresh API is triggered, the changed information and some basic information will be selected. As shown in the figure below, the previously changed values have been selected:

Then go to the addConfigFilesToEnvironment method for processing, first get all the environment values, and then set a listener to process the changed information in turn:

Here we jump directly to the key part of dealing with this malicious address and first enter the load method of ConfigFileApplicationListener:

First determine whether there is a file path in url, and enter to process the address only if it exists, otherwise, set the parameter of name to searchName for processing, where the value is "bootstrap", followed by a forced suffix. Then go all the way to the load method in the PropertySourcesLoader class:

First, a head request is sent to determine whether the file exists and whether it is a file, and then it can be parsed according to the file suffix, which is the yml file, so the judgment can be processed by the YamlPropertySourceLoader class. Then enter the load method of the class:

Here the remote yml file will be loaded and the contents will be processed, resulting in remote code execution.

6.6 Patch Analysis

In springboot 1.5 and later, authorities have added authorization authentication to these interfaces, so they can no longer be called arbitrarily.

After reading the above, do you know how to analyze all kinds of RCE vulnerabilities in Spring buckets? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report