SSD Advisory – Cisco Secure Manager Appliance remediation_request_utils SQL Injection Remote Code Execution
A SQL injection vulnerability in the remediation_request_utils module allows an authenticated high-privileged attacker to execute arbitrary code as root. The flaw arises because the batch_id field is embedded into an SQL query without sanitisation.
This vulnerability allows remote attackers to execute arbitrary code on affected installations of Cisco Secure Manager Appliance and Cisco Email Security Appliance. Authentication as a high-privileged user is required to exploit this vulnerability.
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
Cisco Secure Manager Appliance and Cisco Email Security Appliance expose a remediation feature that lets privileged operators act on messages held in the mail queue. The remediation request is submitted as a JSON POST body, parsed by the process_POST method, turned into a batch record plus a list of per-message records, and then written into a Postgres table through a chain of helper functions. The advisory covers a SQL injection in that write path, inside the remediation_request_utils module, which leads to remote code execution as root.
The report was published on 14 November 2022 and covers CVE-2022-20867 and CVE-2022-20868. A second advisory, for a hardcoded JWT secret in jwt_api_impl, was published alongside it. The two are independent: neither requires the other to be exploited. The report does note that a low-privileged user can combine both to obtain full admin privileges on an affected system.
Credit for the finding goes to Alex Birnberg (@alexbirnberg), reported through the SSD Secure Disclosure program.
Setup
The remediation functionality is restricted to users holding one of three roles: ADMIN, EMAIL_ADMIN or CLOUD_ADMIN. The report notes that since any user can be impersonated, a token for the admin account can be obtained, which satisfies the role requirement. Authentication as a high-privileged user is therefore a precondition for this vulnerability on its own.
No tooling, version strings or specific request captures are given in the report; the analysis is a source code review of the request handling and database layers.
Finding it
The researcher followed the path from the HTTP entry point down to the SQL string construction. The flaw is that user-supplied data reaches an INSERT statement without validation. The batch_id value, taken from the JSON body, is embedded into the query text with no sanitisation, while several neighbouring fields are passed through a sanitiser. That asymmetry is what makes the injection possible.
Exploitation
Step 1: the entry point reads batch_id from the body
The process_POST method loads the remediation_data object from the POST body [1]. If a batch_id is present in that object it is used as-is [2]; otherwise one is generated from the initiated username and initiated time. The batch_id is then used to create the record object [3], and the resulting remediation_request_records structure is passed to store_mor_details [4].
def process_POST(self, uri_ctx):
post_data = uri_ctx.request_body
if not post_data:
qlog.write('API.REQUEST.INFO', CONSTANTS.NO_CRITERIA)
return uri_handler.URI_Response(None, httplib.BAD_REQUEST, CONSTANTS.NO_CRITERIA)
else:
try:
remediation_data = json.loads(post_data, object_hook=stringyfy)['data'] # 1
except (SyntaxError, ValueError, KeyError):
qlog.write('API.REQUEST.INFO', CONSTANTS.MALFORMED_CRITERIA)
return uri_handler.URI_Response(None, httplib.BAD_REQUEST, CONSTANTS.MALFORMED_CRITERIA)
else:
try:
remediation_data[CONSTANTS.REMEDIATION_ACTION] = remediation_data[CONSTANTS.REMEDIATION_ACTION].lower()
initiated_username = uri_ctx.user_name
if not initiated_username:
initiated_username = remediation_data[CONSTANTS.INITIATED_USERNAME]
if not remediation_data.get(CONSTANTS.INITIATED_TIME):
remediation_data[CONSTANTS.INITIATED_TIME] = int(time.time())
batch_id = remediation_data.get(CONSTANTS.BATCH_ID) # 2
if not batch_id:
batch_id = generate_batch_id(initiated_username, remediation_data[CONSTANTS.INITIATED_TIME])
remediation_data[CONSTANTS.BATCH_ID] = batch_id
batch_info_record = create_batch_info_record(remediation_data)
batch_name = remediation_data[CONSTANTS.BATCH_NAME]
message_details = remediation_data[CONSTANTS.REMEDIATION_MESSAGE_DETAILS]
remediation_records = []
for remediation_item in message_details:
record = create_message_details_record(remediation_item, batch_id) # 3
remediation_records.extend(record)
# ...
try:
# ...
remediation_request_records = {CONSTANTS.BATCH_INFO_RECORD: batch_info_record,
CONSTANTS.REMEDIATION_RECORDS: remediation_records}
self.msgs_db_client.store_mor_details(remediation_request_records, True) # 4
The important detail is that an attacker who controls the JSON body controls batch_id directly, and that value is carried into every per-message record.
Step 2: the record travels through the RPC wrapper
store_mor_details is a thin RPC wrapper that calls write_mor_details_to_buffer [5].
def store_mor_details(self, remediation_data, immediate_msg_write=False):
return msgs_db_utils.write_mor_details_to_buffer(remediation_data, immediate_msg_write) # 5
Step 3: records are formatted for the INSERT
write_mor_details_to_buffer calls get_formatted_mor_record on each record [6] and then hands the formatted strings to mor_details_buffer_writer [7].
def write_mor_details_to_buffer(remediation_data, immediate_msg_write=False):
if remediation_data:
formatted_mor_records = [ get_formatted_mor_record(record) for record in remediation_data.get(remediation_consts.REMEDIATION_RECORDS) ] # 6
formatted_mor_batch_records = [
get_formatted_mor_batch_record(remediation_data.get(remediation_consts.BATCH_INFO_RECORD))]
msgs_db_handler = msgs_db_updater.get_msgs_db_handler()
msgs_db_handler.mor_details_buffer_writer(formatted_mor_records, immediate_msg_write) # 7
msgs_db_handler.mor_batch_details_buffer_writer(formatted_mor_batch_records, immediate_msg_write)
Step 4: batch_id is embedded without sanitisation
get_formatted_mor_record builds the tuple text for the INSERT. The subject, from addresses, recipients and message id go through _get_sanitized_record_field, but batch_id is placed straight into the string [8].
def get_formatted_mor_record(mor_data):
(batch_id, mid, subject, from_addrs, rcpts, ip, message_id, attempts, status, sent_at) = mor_data
record = "('%s', %s, '%s'" % (batch_id, mid, _get_sanitized_record_field(subject)) # 8
record = "%s, '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % (record, _get_sanitized_record_field(from_addrs),
_get_sanitized_record_field(rcpts), ip, _get_sanitized_record_field(message_id), attempts, status, sent_at)
return record
Step 5: the writer executes the query
mor_details_buffer_writer calls insert_mor_details with the formatted records [9].
def mor_details_buffer_writer(self, records, immediate_msg_write=False):
if not self.db_full and len(records) < self._limit:
conn = self._get_connection()
if immediate_msg_write and conn is not None:
self.insert_mor_details(conn, records) # 9
return
Step 6: the query is assembled and run
insert_mor_details builds the full query string [10] and executes it [11].
def insert_mor_details(self, conn, bulk_records):
query_str = msgs_db_query.get_mor_details_bulk_insert_query(bulk_records) # 10
msgs_db_defs.log_trace('Query string for mor_details: %s' % (query_str,))
try:
try:
self.query(conn, query_str) # 11
except (coro_postgres.QueryError, coro_postgres.InternalError), err:
msgs_db_defs.log('Database insertion error %s' % (
err,))
raise
except coro_postgres.ConnectionClosedError, err:
msgs_db_defs.log('Postgres connection closed. Reason: %s' % (err,))
raise
else:
self.db_empty = False
msgs_db_defs.log('%s records inserted' % (len(bulk_records),))
finally:
self._release_connection(conn)
Step 7: no further sanitisation in the query builder
get_mor_details_bulk_insert_query passes the column list, the records and the table name to _get_records_insert_query [12].
def get_mor_details_bulk_insert_query(bulk_records):
return _get_records_insert_query(msgs_db_defs.MOR_DETAILS_TABLE_COLUMNS, bulk_records, msgs_db_defs.MOR_DETAILS_TABLE) # 12
_get_records_insert_query joins the values and interpolates them into the statement [13].
def _get_records_insert_query(keys, values, table_name):
keys = (', ').join(keys)
values = (', ').join(values)
return 'INSERT INTO %s (%s) VALUES %s' % (table_name, keys, values) # 13
At this point the injected SQL from batch_id is part of the statement sent to Postgres.
Step 8: from SQL injection to command execution
The injection runs in the context of the pgsql user. The report says there are multiple ways to execute arbitrary commands from there; the method used in the exploit is to write to disk and load a Postgres extension and call its function pg_system. The extension source is:
#include <stdlib.h>
#include <postgres.h>
#include <fmgr.h>
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
PG_FUNCTION_INFO_V1(pg_system);
Datum pg_system(PG_FUNCTION_ARGS) {
text *commandText = PG_GETARG_TEXT_P(0);
int32 commandLen = VARSIZE(commandText) - VARHDRSZ;
char *command = (char *)palloc(commandLen + 1);
int32 result = 0;
memcpy(command, VARDATA(commandText), commandLen);
command[commandLen] = 0;
result = system(command);
pfree(command);
PG_RETURN_INT32(result);
}
pg_system takes a text argument, copies it into a null-terminated buffer and passes it to system(), so any command string supplied through SQL is executed by the database process.
Step 9: privilege escalation to root
To move from the pgsql user to root, the report points to a suid binary named runas. It allows any user to run commands as any other user by supplying the desired username as the first parameter. Combined with the extension, this gives code execution as root.
Root cause
The mistake is string interpolation of user-controlled data into SQL. batch_id is taken from the JSON request body and concatenated into the INSERT statement in get_formatted_mor_record, then carried unchanged through _get_records_insert_query into the query executed by insert_mor_details. Some fields are passed through _get_sanitized_record_field, but batch_id is not. No parameterised query or escaping is applied anywhere along the path, so the single quote in the attacker's value is enough to alter the statement. The injection runs in the context of the pgsql user, and the presence of the suid runas binary turns that into root.
Impact
A remote attacker who can authenticate as a high-privileged user (ADMIN, EMAIL_ADMIN or CLOUD_ADMIN) can execute arbitrary code as root on affected installations of Cisco Secure Manager Appliance and Cisco Email Security Appliance. The report also notes that a low-privileged user can chain this with the hardcoded JWT secret issue to reach full admin privileges, though the two vulnerabilities are independent and neither requires the other.
Fix
Cisco issued a patch for the vulnerability as part of its patches released on 11 November 2022, published in the advisory at https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-esasmawsa-vulns-YRuSW5mD. The report does not describe the code change itself.
Variants to test
- Other fields in the same record tuple: send values containing a single quote in
subject,from_addrs,rcpts,message_idand the other columns, and check whether the sanitiser actually neutralises them or whether any path bypasses it. - The batch info record:
create_batch_info_recordandget_formatted_mor_batch_recordhandle the samebatch_idand other batch fields; test whether the batch insert path is equally injectable. - Generated versus supplied
batch_id: whenbatch_idis absent it is generated from the initiated username and time. Try injecting throughINITIATED_USERNAMEor other inputs that feedgenerate_batch_id. - Other callers of
_get_records_insert_query: any code path that passes user-controlled values into this generic builder inherits the same flaw; look for other tables and modules using it. - Database privilege surface: on a test instance, check whether the application's database role can create extensions or write files, and whether a
suidhelper such asrunasexists, since these determine whether SQL injection becomes code execution.
A positive result for the injection tests is a query error revealing the injected syntax, a row containing the attacker's marker value, or a successful call to a function the attacker defined.
What happened, in plain words
Cisco makes two products that handle email for organisations: the Cisco Secure Manager Appliance and the Cisco Email Security Appliance. Both have a feature called remediation. When a message is stuck in the mail queue (for example because it looks suspicious), an operator with the right permissions can send the appliance an instruction to do something with that message: release it, delete it, and so on. That instruction is called a remediation request.
The request is sent to the appliance as a block of data in a format called JSON, which is just a way of writing structured information as text, a bit like a very strict shopping list. The appliance reads that text, turns it into records, and saves those records into a database. A database is an organised store of information, and this one is Postgres, a popular free database product.
The problem is in how one of those values, a field called batch_id, is put into the database command. The appliance builds the database command by gluing text together, and it glues batch_id in without checking it. If an attacker puts special characters in batch_id, they can change the meaning of the database command. This kind of flaw is called SQL injection: SQL is the language used to talk to databases, and injection means the attacker's text gets treated as part of the command instead of as plain data.
From there the attacker can make the database run commands on the underlying server, and because of a second weakness on the machine (a helper program called runas), they can end up running commands as the most powerful user on the system, root. Running code as root means having complete control of the machine.
The report was published on 14 November 2022 and covers two identifiers, CVE-2022-20867 and CVE-2022-20868. A CVE is a public catalogue number given to a security flaw so people can refer to it unambiguously. A second advisory, about a hardcoded JWT secret in a module called jwt_api_impl, was published alongside this one. A JWT is a signed token, a small piece of text that proves who you are, and "hardcoded secret" means the key used to sign it was baked into the software instead of being kept private. The two flaws are independent: neither needs the other to be exploited. The report does note that a low-privileged user can combine both to obtain full admin privileges on an affected system.
Credit for the finding goes to Alex Birnberg (@alexbirnberg), reported through the SSD Secure Disclosure program.
Setup
The remediation functionality is restricted to users holding one of three roles: ADMIN, EMAIL_ADMIN or CLOUD_ADMIN. A role is a label attached to an account that says what it is allowed to do. The report notes that since any user can be impersonated, a token for the admin account can be obtained, which satisfies the role requirement. A token here is the proof of identity the appliance accepts on each request, like a wristband at an event: show it and you are let in as whoever it belongs to. Authentication as a high-privileged user is therefore a precondition for this vulnerability on its own.
No tooling, version strings or specific request captures are given in the report; the analysis is a source code review of the request handling and database layers. Source code review means reading the program's own instructions, line by line, looking for mistakes, rather than poking at a running system.
Finding it
The researcher followed the path from the HTTP entry point down to the SQL string construction. HTTP is the protocol a browser uses to talk to a web server, and an entry point is the piece of code that first receives such a request. The flaw is that user-supplied data reaches an INSERT statement without validation. An INSERT statement is the database instruction that adds a new row of data to a table. The batch_id value, taken from the JSON body, is embedded into the query text with no sanitisation, while several neighbouring fields are passed through a sanitiser. Sanitising means cleaning a value so that special characters cannot change the meaning of a command. That asymmetry, one field cleaned and one not, is what makes the injection possible.
Exploitation
Step 1: the entry point reads batch_id from the body
The process_POST method loads the remediation_data object from the POST body [1]. A POST request is the kind of HTTP request a browser sends when you submit a form, carrying data in its body. If a batch_id is present in that object it is used as-is [2]; otherwise one is generated from the initiated username and initiated time. The batch_id is then used to create the record object [3], and the resulting remediation_request_records structure is passed to store_mor_details [4].
def process_POST(self, uri_ctx):
post_data = uri_ctx.request_body
if not post_data:
qlog.write('API.REQUEST.INFO', CONSTANTS.NO_CRITERIA)
return uri_handler.URI_Response(None, httplib.BAD_REQUEST, CONSTANTS.NO_CRITERIA)
else:
try:
remediation_data = json.loads(post_data, object_hook=stringyfy)['data'] # 1
except (SyntaxError, ValueError, KeyError):
qlog.write('API.REQUEST.INFO', CONSTANTS.MALFORMED_CRITERIA)
return uri_handler.URI_Response(None, httplib.BAD_REQUEST, CONSTANTS.MALFORMED_CRITERIA)
else:
try:
remediation_data[CONSTANTS.REMEDIATION_ACTION] = remediation_data[CONSTANTS.REMEDIATION_ACTION].lower()
initiated_username = uri_ctx.user_name
if not initiated_username:
initiated_username = remediation_data[CONSTANTS.INITIATED_USERNAME]
if not remediation_data.get(CONSTANTS.INITIATED_TIME):
remediation_data[CONSTANTS.INITIATED_TIME] = int(time.time())
batch_id = remediation_data.get(CONSTANTS.BATCH_ID) # 2
if not batch_id:
batch_id = generate_batch_id(initiated_username, remediation_data[CONSTANTS.INITIATED_TIME])
remediation_data[CONSTANTS.BATCH_ID] = batch_id
batch_info_record = create_batch_info_record(remediation_data)
batch_name = remediation_data[CONSTANTS.BATCH_NAME]
message_details = remediation_data[CONSTANTS.REMEDIATION_MESSAGE_DETAILS]
remediation_records = []
for remediation_item in message_details:
record = create_message_details_record(remediation_item, batch_id) # 3
remediation_records.extend(record)
# ...
try:
# ...
remediation_request_records = {CONSTANTS.BATCH_INFO_RECORD: batch_info_record,
CONSTANTS.REMEDIATION_RECORDS: remediation_records}
self.msgs_db_client.store_mor_details(remediation_request_records, True) # 4
Line by line, in plain words:
def process_POST(self, uri_ctx):declares the function that handles an incoming POST request.uri_ctxis the bundle of information about that request.post_data = uri_ctx.request_bodytakes the raw body of the request, the text the client sent.- The
if not post_data:block handles the case of an empty body: it writes a log line (a note in a log file, the appliance's diary) and returns aBAD_REQUESTresponse, which is the HTTP status code meaning "you sent me something I cannot use". remediation_data = json.loads(post_data, object_hook=stringyfy)['data'] # 1is the key line.json.loadsturns the JSON text into a Python object, a dictionary (a lookup table of names to values).object_hook=stringyfyruns a helper on each object as it is built. The['data']at the end picks thedataentry out of the result. This is where the attacker's JSON becomes data the program works with.- The
except (SyntaxError, ValueError, KeyError):block catches malformed JSON and returnsBAD_REQUESTagain. remediation_data[CONSTANTS.REMEDIATION_ACTION] = ...lower()lowercases the action field, soDELETEanddeleteare treated the same.initiated_username = uri_ctx.user_namereads the username from the request context; if it is empty, the code falls back to a username supplied in the JSON.- The
INITIATED_TIMElines set a timestamp if the client did not provide one. batch_id = remediation_data.get(CONSTANTS.BATCH_ID) # 2readsbatch_idfrom the JSON. If the client supplied one, this is the attacker's value. If not,generate_batch_idmakes one from the username and time.remediation_data[CONSTANTS.BATCH_ID] = batch_idwrites the value back into the data.batch_info_record = create_batch_info_record(remediation_data)builds a summary record for the whole batch.- The
for remediation_item in message_details:loop walks over each message in the request and callscreate_message_details_record(remediation_item, batch_id) # 3, passing the attacker-controlledbatch_idinto every per-message record. - Finally
self.msgs_db_client.store_mor_details(remediation_request_records, True) # 4hands the whole structure to the database client. TheTruemeans "write it immediately".
The important detail is that an attacker who controls the JSON body controls batch_id directly, and that value is carried into every per-message record.
Step 2: the record travels through the RPC wrapper
store_mor_details is a thin RPC wrapper that calls write_mor_details_to_buffer [5]. RPC stands for remote procedure call: code in one part of the system asking another part to run a function, as if it were local. A wrapper is a small function whose only job is to pass the request along.
def store_mor_details(self, remediation_data, immediate_msg_write=False):
return msgs_db_utils.write_mor_details_to_buffer(remediation_data, immediate_msg_write) # 5
This function takes the data and a flag saying whether to write immediately, and passes both straight to write_mor_details_to_buffer. Nothing is checked or changed here, so the attacker's batch_id keeps travelling untouched.
Step 3: records are formatted for the INSERT
write_mor_details_to_buffer calls get_formatted_mor_record on each record [6] and then hands the formatted strings to mor_details_buffer_writer [7].
def write_mor_details_to_buffer(remediation_data, immediate_msg_write=False):
if remediation_data:
formatted_mor_records = [ get_formatted_mor_record(record) for record in remediation_data.get(remediation_consts.REMEDIATION_RECORDS) ] # 6
formatted_mor_batch_records = [
get_formatted_mor_batch_record(remediation_data.get(remediation_consts.BATCH_INFO_RECORD))]
msgs_db_handler = msgs_db_updater.get_msgs_db_handler()
msgs_db_handler.mor_details_buffer_writer(formatted_mor_records, immediate_msg_write) # 7
msgs_db_handler.mor_batch_details_buffer_writer(formatted_mor_batch_records, immediate_msg_write)
if remediation_data:only proceeds when there is data to write.- The list comprehension
[ get_formatted_mor_record(record) for record in ... ] # 6runsget_formatted_mor_recordon every record and collects the results into a list. This is the step where each record becomes a piece of SQL text. formatted_mor_batch_recordsdoes the same for the batch summary record.msgs_db_handler = msgs_db_updater.get_msgs_db_handler()fetches the object that talks to the database.mor_details_buffer_writer(formatted_mor_records, immediate_msg_write) # 7sends the formatted records on to be written.- The last line does the same for the batch summary.
Step 4: batch_id is embedded without sanitisation
get_formatted_mor_record builds the tuple text for the INSERT. A tuple here means the parenthesised list of values that will become one row in the table. The subject, from addresses, recipients and message id go through _get_sanitized_record_field, but batch_id is placed straight into the string [8].
def get_formatted_mor_record(mor_data):
(batch_id, mid, subject, from_addrs, rcpts, ip, message_id, attempts, status, sent_at) = mor_data
record = "('%s', %s, '%s'" % (batch_id, mid, _get_sanitized_record_field(subject)) # 8
record = "%s, '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % (record, _get_sanitized_record_field(from_addrs),
_get_sanitized_record_field(rcpts), ip, _get_sanitized_record_field(message_id), attempts, status, sent_at)
return record
- The first line unpacks the record into named variables:
batch_id,mid,subject,from_addrs,rcpts,ip,message_id,attempts,status,sent_at. record = "('%s', %s, '%s'" % (batch_id, mid, _get_sanitized_record_field(subject)) # 8starts building the text. The%splaceholders are filled in order. Notice thatbatch_idgoes in bare, whilesubjectis wrapped in_get_sanitized_record_field. The surrounding single quotes are meant to mark the start and end of a text value in SQL.- The second line appends the remaining fields, again sanitising some and not others, and closes the parenthesis.
return recordhands back the finished text.
In everyday terms: imagine a form that says "write your name between these quote marks". If you write a quote mark yourself, everything after it is read as new instructions rather than as part of your name.
Step 5: the writer executes the query
mor_details_buffer_writer calls insert_mor_details with the formatted records [9].
def mor_details_buffer_writer(self, records, immediate_msg_write=False):
if not self.db_full and len(records) < self._limit:
conn = self._get_connection()
if immediate_msg_write and conn is not None:
self.insert_mor_details(conn, records) # 9
return
if not self.db_full and len(records) < self._limit:only proceeds if the database is not full and the batch is below a size limit. This is a safety valve so a huge batch does not overwhelm the database.conn = self._get_connection()obtains a database connection, the open channel through which commands are sent.if immediate_msg_write and conn is not None:checks that the caller asked for an immediate write and that a connection exists.self.insert_mor_details(conn, records) # 9passes the formatted records on to the function that will run the query.
Step 6: the query is assembled and run
insert_mor_details builds the full query string [10] and executes it [11].
def insert_mor_details(self, conn, bulk_records):
query_str = msgs_db_query.get_mor_details_bulk_insert_query(bulk_records) # 10
msgs_db_defs.log_trace('Query string for mor_details: %s' % (query_str,))
try:
try:
self.query(conn, query_str) # 11
except (coro_postgres.QueryError, coro_postgres.InternalError), err:
msgs_db_defs.log('Database insertion error %s' % (
err,))
raise
except coro_postgres.ConnectionClosedError, err:
msgs_db_defs.log('Postgres connection closed. Reason: %s' % (err,))
raise
else:
self.db_empty = False
msgs_db_defs.log('%s records inserted' % (len(bulk_records),))
finally:
self._release_connection(conn)
query_str = msgs_db_query.get_mor_details_bulk_insert_query(bulk_records) # 10asks another module to build the full SQL text from the records.msgs_db_defs.log_trace(...)writes the query into a trace log. Trace logs are detailed diaries kept for debugging; they can be useful to an investigator, and also to an attacker who can read them.self.query(conn, query_str) # 11is the moment of execution: the text is sent to Postgres and run.- The
exceptblocks catch database errors (QueryError,InternalError,ConnectionClosedError), log them, and re-raise them so the caller knows something went wrong. - The
else:block runs when no error occurred: it marks the database as no longer empty and logs how many records were inserted. finally: self._release_connection(conn)always runs, error or not, and returns the connection to the pool so it can be reused.
Step 7: no further sanitisation in the query builder
get_mor_details_bulk_insert_query passes the column list, the records and the table name to _get_records_insert_query [12].
def get_mor_details_bulk_insert_query(bulk_records):
return _get_records_insert_query(msgs_db_defs.MOR_DETAILS_TABLE_COLUMNS, bulk_records, msgs_db_defs.MOR_DETAILS_TABLE) # 12
This function is a one-liner: it takes the list of column names, the already-formatted record strings, and the table name, and hands them to the generic builder.
_get_records_insert_query joins the values and interpolates them into the statement [13].
def _get_records_insert_query(keys, values, table_name):
keys = (', ').join(keys)
values = (', ').join(values)
return 'INSERT INTO %s (%s) VALUES %s' % (table_name, keys, values) # 13
keys = (', ').join(keys)glues the column names together with commas, producing something likecol1, col2, col3.values = (', ').join(values)glues the record strings together the same way.return 'INSERT INTO %s (%s) VALUES %s' % (table_name, keys, values) # 13fills the template. The result is a complete SQL statement of the formINSERT INTO table (columns) VALUES (rows).
At this point the injected SQL from batch_id is part of the statement sent to Postgres. Nothing between the JSON body and this line has removed the attacker's quote mark.
Step 8: from SQL injection to command execution
The injection runs in the context of the pgsql user. Every program on a Unix-like system runs as some user account, and that account decides what the program is allowed to touch. The report says there are multiple ways to execute arbitrary commands from there; the method used in the exploit is to write to disk and load a Postgres extension and call its function pg_system. A Postgres extension is a compiled add-on that the database can load to gain new functions, much like installing a plugin in a browser. The extension source is:
#include <stdlib.h>
#include <postgres.h>
#include <fmgr.h>
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
PG_FUNCTION_INFO_V1(pg_system);
Datum pg_system(PG_FUNCTION_ARGS) {
text *commandText = PG_GETARG_TEXT_P(0);
int32 commandLen = VARSIZE(commandText) - VARHDRSZ;
char *command = (char *)palloc(commandLen + 1);
int32 result = 0;
memcpy(command, VARDATA(commandText), commandLen);
command[commandLen] = 0;
result = system(command);
pfree(command);
PG_RETURN_INT32(result);
}
- The
#includelines pull in standard C headers and Postgres headers, which declare the types and macros used below. PG_MODULE_MAGIC;is a marker Postgres checks to confirm the file was built against a compatible version.PG_FUNCTION_INFO_V1(pg_system);registers the function with Postgres so SQL can call it by name.Datum pg_system(PG_FUNCTION_ARGS) {begins the function.Datumis Postgres's generic return type.text *commandText = PG_GETARG_TEXT_P(0);takes the first SQL argument as a text value.int32 commandLen = VARSIZE(commandText) - VARHDRSZ;works out how many characters the text holds, subtracting the header size.char *command = (char *)palloc(commandLen + 1);allocates memory for the command plus one extra byte for a terminator.memcpy(command, VARDATA(commandText), commandLen);copies the characters into that buffer.command[commandLen] = 0;adds the null terminator, the zero byte that marks the end of a C string.result = system(command);hands the string to the operating system'ssystem()call, which runs it as a shell command.pfree(command);frees the memory.PG_RETURN_INT32(result);returns the exit status to SQL.
pg_system takes a text argument, copies it into a null-terminated buffer and passes it to system(), so any command string supplied through SQL is executed by the database process.
Step 9: privilege escalation to root
To move from the pgsql user to root, the report points to a suid binary named runas. A binary is a compiled program. suid (set user ID) is a permission bit that makes a program run with the privileges of its owner rather than of whoever launched it, which is how ordinary users can use tools that need extra rights. root is the all-powerful administrator account on Unix-like systems. runas allows any user to run commands as any other user by supplying the desired username as the first parameter. Combined with the extension, this gives code execution as root.
Root cause
The mistake is string interpolation of user-controlled data into SQL. Interpolation here means pasting a value into a template string. batch_id is taken from the JSON request body and concatenated into the INSERT statement in get_formatted_mor_record, then carried unchanged through _get_records_insert_query into the query executed by insert_mor_details. Some fields are passed through _get_sanitized_record_field, but batch_id is not. No parameterised query or escaping is applied anywhere along the path, so the single quote in the attacker's value is enough to alter the statement. A parameterised query is the safe alternative: the command and the data travel separately, so data can never be mistaken for command. The injection runs in the context of the pgsql user, and the presence of the suid runas binary turns that into root.
Impact
A remote attacker who can authenticate as a high-privileged user (ADMIN, EMAIL_ADMIN or CLOUD_ADMIN) can execute arbitrary code as root on affected installations of Cisco Secure Manager Appliance and Cisco Email Security Appliance. The report also notes that a low-privileged user can chain this with the hardcoded JWT secret issue to reach full admin privileges, though the two vulnerabilities are independent and neither requires the other.
Fix
Cisco issued a patch for the vulnerability as part of its patches released on 11 November 2022, published in the advisory at https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-esasmawsa-vulns-YRuSW5mD. A patch is an update that corrects the flaw. The report does not describe the code change itself.
Variants to test
- Other fields in the same record tuple: send values containing a single quote in
subject,from_addrs,rcpts,message_idand the other columns, and check whether the sanitiser actually neutralises them or whether any path bypasses it. - The batch info record:
create_batch_info_recordandget_formatted_mor_batch_recordhandle the samebatch_idand other batch fields; test whether the batch insert path is equally injectable. - Generated versus supplied
batch_id: whenbatch_idis absent it is generated from the initiated username and time. Try injecting throughINITIATED_USERNAMEor other inputs that feedgenerate_batch_id. - Other callers of
_get_records_insert_query: any code path that passes user-controlled values into this generic builder inherits the same flaw; look for other tables and modules using it. - Database privilege surface: on a test instance, check whether the application's database role can create extensions or write files, and whether a
suidhelper such asrunasexists, since these determine whether SQL injection becomes code execution.
A positive result for the injection tests is a query error revealing the injected syntax, a row containing the attacker's marker value, or a successful call to a function the attacker defined.
Glossary
- API: the defined set of requests a program accepts from other programs, like a service counter with a fixed list of things you can ask for.
- Authentication: proving who you are, usually with a username and password or a token.
- Binary: a compiled program file that the computer can run directly.
- CVE: a public catalogue number assigned to a security flaw so it can be referenced unambiguously.
- Database: an organised store of data that can be searched and updated, here Postgres.
- Dictionary: in Python, a lookup table mapping names to values.
- Entry point: the first piece of code that receives an incoming request.
- Escaping: marking special characters in a value so they are treated as plain text rather than as part of a command.
- Extension (Postgres): a compiled add-on loaded into the database to add new functions.
- Function: a named block of code that performs a task and can be called by name.
- HTTP: the protocol browsers and servers use to exchange requests and responses.
- INSERT statement: the SQL instruction that adds a new row to a database table.
- Interpolation: pasting a value into a template string.
- JSON: a text format for structured data, made of names and values.
- JWT: a signed token that proves identity; the signature uses a secret key.
- List comprehension: a Python expression that builds a list by applying an operation to each item.
- Log: a diary file where a program records events.
- Method: in Python, a function attached to an object.
- Null terminator: the zero byte that marks the end of a C string.
- Parameterised query: a database command where the command text and the data are sent separately, so data cannot change the command.
- Patch: an update that fixes a flaw.
- POST request: an HTTP request that carries data in its body, typically used to submit forms or API calls.
- Privilege escalation: gaining more rights on a system than you were given.
pgsql: the database user account under which the injected SQL runs.- Remote code execution (RCE): making a target machine run commands of your choosing over a network.
- Role: a label on an account that determines what it may do.
root: the all-powerful administrator account on Unix-like systems.- RPC (remote procedure call): code in one part of a system asking another part to run a function.
- Sanitisation: cleaning a value so special characters cannot change the meaning of a command.
- Source code review: reading a program's instructions looking for mistakes.
- SQL: the language used to talk to relational databases.
- SQL injection: a flaw where attacker text is treated as part of a database command instead of as data.
suid(set user ID): a permission bit that makes a program run with the privileges of its owner rather than of the user who launched it.- Table: a grid of rows and columns inside a database.
- Token: a piece of text that proves identity on each request, like a wristband at an event.
- Trace log: a detailed log kept for debugging.
- Tuple: here, the parenthesised list of values that becomes one database row.
- Wrapper: a small function whose only job is to pass a request along.