SQL Injection in OSSEC's Database Output
OSSEC is a widely deployed, open-source host-based intrusion detection system (HIDS). Agents on each host collect logs and command output and report them to a central OSSEC server, which analyses them, raises alerts and can optionally store them in a MySQL or PostgreSQL database.
This post covers a SQL injection I found in that server-side database output in OSSEC 2.8.3, the latest stable release at the time. It follows a couple of other recent OSSEC issues (CVE-2014-5284 and CVE-2015-3222).
Why it matters
Exploiting this requires control of an agent: enough access to change its configuration and restart it. On its own, that sounds like it limits the damage to a single host. The injection, however, happens on the central server the agents report to, and in many environments that server sits in a more trusted, segregated part of the network. Compromising it can open the way to the other systems it monitors.
There's also an uncomfortable irony. OSSEC exists to detect intrusions, and this bug lets an attacker tamper with the very database where its alerts are stored, potentially removing evidence of the compromise (unless alerts are also being sent somewhere else, such as email). OSSEC is also commonly recommended as a remediation after failed PCI audits, so it often guards systems handling card data.
How I found it
I found this by accident. I was upgrading OSSEC on some machines and installed a development release candidate on one agent that reported to my 2.8.3 server. The agent immediately stopped reporting, and the server logs were full of SQL syntax errors:
2016/08/17 12:52:03 ossec-dbd(5203): ERROR: Error executing query 'SELECT id FROM location WHERE name = 'thedefaced->netstat -tan |grep LISTEN |grep -v '127.0.0.1' | sort' AND server_id = '1' LIMIT 1'. Error: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '127.0.0.1' | sort' AND server_id = '1' LIMIT 1' at line 1'.
The release candidate ships a default full_command entry, netstat -tan |grep LISTEN |grep -v '127.0.0.1', and its single quotes were breaking the server's query. The command string, the "location" of the event, was being inserted into SQL unescaped. This affects any server with database output enabled, MySQL and PostgreSQL alike. Since the release candidate ships that configuration, I assume its server side was already patched, but the fix hadn't been backported to the stable 2.8.3 release.
Root cause
The vulnerable code is in alert.c. OS_Alert_InsertDB passes al_data->location (lines 115, 118 and 119) to __DBSelectLocation (line 53) and __DBInsertLocation (line 79), which build their queries with snprintf and no escaping:
int __DBSelectLocation(char *location, DBConfig *db_config)
{
int result = 0;
char sql_query[OS_SIZE_1024];
memset(sql_query, '\0', OS_SIZE_1024);
/* Generating SQL */
snprintf(sql_query, OS_SIZE_1024 -1,
"SELECT id FROM "
"location WHERE name = '%s' AND server_id = '%d' "
"LIMIT 1",
location, db_config->server_id); // location is pushed into the sql_query buffer without being sanitized.
/* Checking return code. */
result = osdb_query_select(db_config->conn, sql_query); // osdb_query_select is passed sql_query with no additional processing.
return(result);
}
int __DBInsertLocation(char *location, DBConfig *db_config)
{
char sql_query[OS_SIZE_1024];
memset(sql_query, '\0', OS_SIZE_1024);
/* Generating SQL */
snprintf(sql_query, OS_SIZE_1024 -1,
"INSERT INTO "
"location(server_id, name) "
"VALUES ('%u', '%s')",
db_config->server_id, location); // Location parameter is pushed into the sql_query buffer without being sanitized.
/* Checking return code. */
if(!osdb_query_insert(db_config->conn, sql_query)) // sql_query is then passed to osdb_query_insert, where we already know no additional processing happens.
{
merror(DB_GENERROR, ARGV0);
}
return(0);
}
Other fields are handled correctly: al_data->user (line 108) and fulllog (line 152) both go through osdb_escapestr first. That's fortunate, because those values can come straight from logged data: a crafted username via a service like vsftpd, or protocol-mismatch messages in sshd's logs, would otherwise have made this exploitable without any access to an agent at all. After further auditing, al_data->location was the only injectable point I found in 2.8.3.
Below that, the database wrappers in db_op.c pass queries straight through. osdb_query is bound at build/install time to the MySQL or PostgreSQL implementation, and neither the _select nor the _insert variants sanitize anything:
int mysql_osdb_query_select(void *db_conn, char *query)
{
int result_int = 0;
MYSQL_RES *result_data;
MYSQL_ROW result_row;
/* Sending the query. It can not fail. */
if(mysql_query(db_conn, query) != 0)
{
int postgresql_osdb_query_select(void *db_conn, char *query)
{
int result_int = 0;
PGresult *result;
result = PQexec(db_conn, query);
What an attacker can do with it
It depends on the database backend:
- MySQL: the connection is opened with
mysql_real_connect(line 187) withoutCLIENT_MULTI_STATEMENTS, andmysql_set_server_optionis never called, so stacked queries aren't possible (MySQL C API: multiple statement execution). NoUPDATE,DELETEorINSERTpiggybacking. AUNION-based injection into theSELECTstill works, though, and if the OSSEC database user hasFILEprivileges,INTO OUTFILEcan write files to the server. - PostgreSQL: queries are executed with
PQexec(line 360), which accepts multiple statements (libpq command execution). I didn't test it, but stacked queries, and with them inserting, updating and deleting data, should be possible, andCOPYcould be used to write files, potentially leading to code execution through a web server running on the same host.
I'd rate it moderate to critical depending on configuration. It requires control of an agent, the injection is blind, and turning it into code execution requires knowing details of the server (database privileges, a writable location the web server will execute from). But in the worst case, a single compromised agent becomes a compromised OSSEC server.
Exploitation
The injection is triggered through the agent's own configuration. A localfile entry with log_format set to full_command runs a command periodically; the command string becomes the event's "location" and its output becomes fulllog.
That comes with a few constraints:
- The command must remain valid and keep producing output, or no event is sent.
- The configuration file is XML, so some payloads (anything containing
<?, for example) produce an invalid config. Recompiling the agent, or writing your own client for the agent protocol, would sidestep these limits. - SQL comments didn't work in my testing, and null bytes won't help either:
snprintfstops copying at the null, so it never ends up in the query.
The simplest approach was to piggyback on a command that already contains quotes. With grep -v, any string works as long as the command still produces output, so first I confirmed the command was valid on the agent:
root@thedefaced:/var/ossec/logs# netstat -tan|grep LISTEN |grep -v 'UNION ALL SELECT 1,2'
tcp 0 0 0.0.0.0:XXXX 0.0.0.0:* LISTEN
Then I applied it to the agent's configuration:
<localfile>
<log_format>full_command</log_format>
<command>netstat -tan |grep LISTEN |grep -v 'UNION ALL SELECT 1,2'</command>
</localfile>
After restarting the agent, the server's SELECT no longer errored (the INSERT still did, which doesn't matter, as only the SELECT needs to be injected). From there, in my test setup, I used INTO OUTFILE to write a PHP script into a world-writable directory served by the web server, and got a shell on the OSSEC server.
To be clear about the conditions: that proof of concept relied on the OSSEC MySQL user having file read/write privileges and on a web-accessible, world-writable directory. It's a staged scenario and not something I'd expect to see often in the wild, but nothing stops an installation from looking like that, and OSSEC should never be running its database as root or with privileges like these.
Fix
I submitted a pull request to the OSSEC project, and the fix is in commit 2145db5. Until a release includes it, upgrading to the current source version is the workaround. Thanks to the OSSEC team for working with me on the patch.

Comments