CVE-2022–36635 — A SQL Injection in ZKSecurityBio to RCE
Published on medium.com
It was a Thursday, on a beautiful sunny morning, when another subdomain showed up during the recon phase of a Red Team Exercise. After we scanned it and discovered an odd web application server, the fun had started.
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.
Researched and written by: Caio Burgardt and Silton Santos
This is a write-up of CVE-2022-36635: a SQL injection found in a physical security platform called ZKSecurity Bio v4.1.3, covering access control, elevator control, guest management, patrol and parking management, and how it was used to obtain remote code execution.
Context
ZKSecurity Bio is a physical access control application. The vulnerable feature is the Operation Log functionality, inside the System menu. The report does not describe in detail what the Operation Log screen normally displays, beyond the fact that it takes a Time field as input and returns JSON data.
Setup
- The target was a subdomain discovered during the recon phase of a Red Team Exercise. Scanning it revealed an odd web application server.
- The team performed some password attacks and discovered a privilege escalation vulnerability, CVE-2022-36634.
- They then toured the application. As a physical access control application, it already allowed them to open doors, but they wanted something with more substance for their objective.
- They threw single quotes into request parameters of different functionalities and found a possible SQL injection.
- To test bypasses safely, they downloaded and installed the trial version of the ZK BioSecurity program in a controlled environment rather than experimenting on the live machine.
Finding it
In the Operation Log functionality, inside the System menu, inserting a single quote in the Time field made the application return data indicating that something went wrong with the request. Inserting two single quotes made the application return other JSON data, indicating that the request was accepted. This is common SQL injection behaviour. The requests and responses are shown in the next pictures:

Common SQL injection behaviour

Common SQL injection behaviour
However, a filter prevented simple exploitation: any attempt at exploiting the injection showed an error:

Error
Exploitation
Step 1: Read the query from the application logs
After installation of the trial version, the team found plenty of .jar files containing the application logic. Reverse engineering and decompiling them did not seem time-friendly during a red team exercise, so they took a quicker path: they used the logs of the application to help write the exploit.
With the log, it became possible to craft a good payload for the query by finishing the first query manually and using the stacked query technique to inject arbitrary content together. The next image shows a sample of the log:

holy log
Step 2: Bypass the sanitisation filter
The log showed the full query, but the sanitisation filter still had to be bypassed. The team used an old trick: replacing spaces with comments (/**/) in the SQL payload. This was enough to bypass the filter. The image below shows the injection of a sleep call of 5 seconds:

injection of a sleep call of 5 seconds
Step 3: Abuse the database for code execution
During analysis of the application in their environment, the team noticed that the application installs its own PostgreSQL instance. In this version of ZKSecurity, everyone uses the same database version, with the same user, in this case root.
They confirmed that the PostgreSQL version was vulnerable to the COPY FROM PROGRAM RCE trick, shown in the following SQL commands:
DROP TABLE IF EXISTS AAAAAA;
CREATE TABLE AAAAAA(filenam e text);
COPY AAAAAA FROM PROGRAM 'command';
SELECT * FROM AAAAAA ORDER BY filename ASC;
Step 4: Confirm remote code execution
To test the RCE, they used the trick above to execute a ping command that triggers a DNS lookup. The result shows the command was executed remotely, as shown in the next figures:

call of ping

request DNS, result of ping
Root cause
The Time field of the Operation Log functionality is vulnerable to SQL injection: a single quote breaks the query and two quotes are accepted. A sanitisation filter was present, but it only blocked simple payloads: replacing spaces with /**/ comments was enough to get past it, and stacked queries allowed the attacker to append arbitrary statements. On top of that, the application installs its own PostgreSQL instance, and in this version every installation uses the same database version and the same user, root, which made the COPY FROM PROGRAM technique viable.
Impact
An attacker able to reach the Operation Log functionality could inject arbitrary SQL through the Time field and, because stacked queries and COPY FROM PROGRAM were available under the root database user, execute commands on the host. The report demonstrates this with a ping that triggered a DNS lookup. The conditions are that the attacker can reach the vulnerable endpoint and that the target runs the affected version with its bundled PostgreSQL instance.
Fix
The report does not describe the vendor's fix. The timeline records responsible disclosure to the vendor on 16/07/2022, CVE reservation on 18/07/2022, a vendor response saying it would check on 18/07/2022, and a vendor response informing public fixing on 24/08/2022.
Variants to test
- Send a single quote and then two single quotes in any parameter that reaches a SQL query. A positive result is an error on the first and valid JSON on the second.
- When a filter blocks spaces, replace them with
/**/in the payload. A positive result is that the payload executes, for example a five-second sleep. - Try stacked queries after finishing the original query manually. A positive result is that the appended statement runs.
- On PostgreSQL, try
COPY ... FROM PROGRAMwhen the database user has sufficient privileges. A positive result is command output returned through the table, or an out-of-band DNS lookup from a ping. - Check whether the application ships its own database using the same user,
root, across installations. A positive result is that the same user and version are present.
What happened, in plain words
A security team was doing a Red Team Exercise. That is a test where a group of security people pretend to be attackers against their own organisation, with permission, to find weaknesses before real criminals do. During the early stage of that exercise, called recon (short for reconnaissance, meaning looking around and mapping what exists), they found a subdomain they had not seen before. A subdomain is a smaller address under a main domain, like shop.example.com under example.com. They scanned it and found an unusual web application server running there.
The application turned out to be ZKSecurity Bio, version 4.1.3. It is a physical security platform: software that manages real-world access, such as doors, elevators, guests, patrols and parking. The team found a SQL injection in one of its screens, and then used that injection to run their own commands on the server. That second step is called remote code execution, or RCE: making the target machine execute commands of your choosing.
The vulnerability was published as CVE-2022-36635. A CVE is a public catalogue number for a known security flaw, so that everyone can refer to the same issue by the same name. The report was researched and written by Caio Burgardt and Silton Santos.
Background: what SQL injection is
Before the details, it helps to understand the vulnerability class itself, because the whole story rests on it.
Most web applications sit in front of a database. A database is an organised store of information, like a very large and very strict spreadsheet, kept by a database server. When you use a website, the website often asks the database a question and shows you the answer. Those questions are written in a language called SQL (Structured Query Language).
A SQL injection (SQLi) happens when the application builds a SQL question by gluing together fixed text and whatever the user typed, without checking the user's input. If the user types something clever, it stops being data and becomes part of the question itself. The attacker can then change what the database is asked, retrieve information, or control the database.
The report gives a simple example of a login query:
SELECT id,name,key FROM users WHERE username = '{USER_INPUT}' AND password = {HASH_OF_PASSWORD}
Line by line:
SELECT id,name,keymeans "give me back the id, name and key columns".FROM usersmeans "from the table called users", which is where accounts are stored.WHERE username = '{USER_INPUT}'means "only rows where the username matches what the user typed". The{USER_INPUT}placeholder is where the application pastes the text from the login form.AND password = {HASH_OF_PASSWORD}means "and where the password matches the stored password hash". A hash is a scrambled fingerprint of a password, so the real password is not stored in plain form.
If the application does not check USER_INPUT, an attacker can type the username admin' -- . The single quote closes the text value early, and -- starts a SQL comment, which tells the database to ignore everything after it. The password check is commented out, so the login succeeds without the right password. This is why testers often throw single quotes into input fields: a quote is the cheapest way to see whether the application is gluing your text into a query.
Finding the injection
The team went back to the application and looked around. Because it is a physical access control application, they could already open doors with it, but they wanted something with more substance for their objective. They started throwing single quotes into request parameters of different functionalities.
A request parameter is a named value sent with a web request, for example the time value in a URL or in a form submission. A request is simply the message your browser sends to a server asking for something; the response is the server's reply.
They found a possible SQL injection in the Operation Log functionality, inside the System menu. The Operation Log screen takes a Time field as input and returns JSON data. JSON is a text format for structured data, made of names and values in curly braces, and it is what many web applications use to send results back to the browser.
When they inserted a single quote in the Time field, the application returned data indicating that something went wrong with the request. When they inserted two single quotes, the application returned other JSON data, indicating that the request was accepted. This is common SQL injection behaviour: one quote breaks the query, two quotes put a valid quote back and the query runs again. The requests and responses are shown in the next pictures:

Common SQL injection behaviour

Common SQL injection behaviour
However, a filter prevented simple exploitation. A filter here means a piece of code that inspects incoming input and blocks anything that looks dangerous. Any attempt at exploiting the injection showed an error:

Error
So the injection existed, but the obvious ways to use it were being stopped.
Step 1: Read the query from the application logs
Trying bypasses on the target's live machine is not smart, because a failed attempt can crash the service or leave traces. So the team searched for, downloaded and installed the trial version of the ZK BioSecurity program in a controlled environment. A controlled environment is a machine or lab you own, where you can break things freely.
After installation, they found plenty of .jar files containing the application logic. A .jar file is a package of Java code, and Java is a programming language commonly used for business applications. Reading that code would have meant reverse engineering and decompiling it, which did not seem time-friendly during a red team exercise. Reverse engineering means working backwards from a finished program to understand how it works; decompiling means turning compiled code back into a readable form.
Instead they took a quicker path: they used the logs of the application to help write the exploit. A log is a file where a program records what it did, often including the exact database queries it ran. With the log, it became possible to craft a good payload for the query by finishing the first query manually and using the stacked query technique to inject arbitrary content together.
A payload is the piece of input you send to trigger the vulnerability. A stacked query is when the database accepts more than one SQL statement in a single call, separated by semicolons, so an attacker can append statements of their own after the original one. The next image shows a sample of the log:

holy log
Step 2: Bypass the sanitisation filter
The log showed the full query, but the sanitisation filter still had to be bypassed. Sanitisation means cleaning input before using it, and the filter here was blocking the payloads the team tried. They used an old trick: replacing spaces with comments (/**/) in the SQL payload. In SQL, /* starts a comment and */ ends it, so /**/ is an empty comment. The database ignores it, but the filter sees something that is not a space. This was enough to bypass the filter. The image below shows the injection of a sleep call of 5 seconds:

injection of a sleep call of 5 seconds
A sleep call is a SQL instruction that makes the database wait for a number of seconds before answering. It is a safe way to prove an injection works: if the response comes back five seconds late, the injected instruction really ran.
Step 3: Abuse the database for code execution
During analysis of the application in their environment, the team noticed that the application installs its own PostgreSQL instance. PostgreSQL is a popular open-source database server. An instance is one running copy of it. In this version of ZKSecurity, everyone uses the same database version, with the same user, in this case root. The database user here is root, the same account across installations in this version.
They confirmed that the PostgreSQL version was vulnerable to the COPY FROM PROGRAM RCE trick. COPY is a PostgreSQL command for moving data between a table and a file; COPY ... FROM PROGRAM makes the database run a shell command and read its output as if it were a file. If the database user is powerful enough, that means command execution on the server. The following SQL commands show the trick:
DROP TABLE IF EXISTS AAAAAA;
CREATE TABLE AAAAAA(filenam e text);
COPY AAAAAA FROM PROGRAM 'command';
SELECT * FROM AAAAAA ORDER BY filename ASC;
Line by line:
DROP TABLE IF EXISTS AAAAAA;deletes a table calledAAAAAAif it is already there, so the next step starts clean.CREATE TABLE AAAAAA(filenam e text);creates a new table calledAAAAAAwith one text column. The column name is writtenfilenam ewith a space in it, exactly as in the report.COPY AAAAAA FROM PROGRAM 'command';runs the shell commandcommandon the database server and copies its output into the table.SELECT * FROM AAAAAA ORDER BY filename ASC;reads the table back, sorted by thefilenamecolumn.
Step 4: Confirm remote code execution
To test the RCE, they used the trick above to execute a ping command that triggers a DNS lookup. ping is a standard command that sends a small network message to another machine to see whether it answers. A DNS lookup is the step where a computer asks the domain name system to translate a name like example.com into a numeric address. If the target machine performs that lookup, the attacker's own DNS server sees the request, which proves the command ran on the target. The result shows the command was executed remotely, as shown in the next figures:

call of ping

request DNS, result of ping
Why it worked
The Time field of the Operation Log functionality is vulnerable to SQL injection: a single quote breaks the query and two quotes are accepted. Concatenation means gluing text together; parameterisation means sending user input separately from the query so it can never become part of the query's structure. Because of that, a single quote breaks the query and two quotes are accepted.
A sanitisation filter was present, but it only blocked simple payloads. Replacing spaces with /**/ comments was enough to get past it, and stacked queries allowed the attacker to append arbitrary statements. On top of that, the application installs its own PostgreSQL instance, and in this version every installation uses the same database version and the same user, root, which made the COPY FROM PROGRAM technique viable.
What an attacker could do
An attacker able to reach the Operation Log functionality could inject arbitrary SQL through the Time field and, because stacked queries and COPY FROM PROGRAM were available under the root database user, execute commands on the host. The report demonstrates this with a ping that triggered a DNS lookup. The conditions are that the attacker can reach the vulnerable endpoint and that the target runs the affected version with its bundled PostgreSQL instance.
How it was fixed
The report does not describe the vendor's fix. The timeline records responsible disclosure to the vendor on 16/07/2022, CVE reservation on 18/07/2022, a vendor response saying it would check on 18/07/2022, and a vendor response informing public fixing on 24/08/2022. Responsible disclosure is the practice of telling the vendor privately first, so they have time to fix the issue before it becomes public.
Things to try if you are learning
- Send a single quote and then two single quotes in any parameter that reaches a SQL query. A positive result is an error on the first and valid JSON on the second.
- When a filter blocks spaces, replace them with
/**/in the payload. A positive result is that the payload executes, for example a five-second sleep. - Try stacked queries after finishing the original query manually. A positive result is that the appended statement runs.
- On PostgreSQL, try
COPY ... FROM PROGRAMwhen the database user has sufficient privileges. A positive result is command output returned through the table, or an out-of-band DNS lookup from a ping. - Check whether the application ships its own database using the same user,
root, across installations. A positive result is that the same user and version are present.
Glossary
- CVE: a public catalogue number for a known security flaw, so everyone can refer to the same issue by the same name.
- Red Team Exercise: an authorised test where security people act as attackers against their own organisation to find weaknesses first.
- Recon: short for reconnaissance, the early stage of looking around and mapping what exists on a target.
- Subdomain: a smaller address under a main domain, such as
shop.example.comunderexample.com. - RCE (remote code execution): making a target machine run commands of your choosing from a distance.
- Database: an organised store of information, kept and queried by a database server.
- SQL: Structured Query Language, the language used to ask questions of a database.
- SQL injection (SQLi): a flaw where user input becomes part of a SQL query, letting an attacker change what the database is asked.
- Hash: a scrambled fingerprint of a value such as a password, so the real value is not stored in plain form.
- Request: the message a browser sends to a server asking for something.
- Response: the server's reply to a request.
- Request parameter: a named value sent with a web request, such as a field in a form or a value in a URL.
- JSON: a text format for structured data, made of names and values, commonly used between web applications and browsers.
- Filter: code that inspects incoming input and blocks anything that looks dangerous.
- Controlled environment: a machine or lab you own, where you can test and break things safely.
.jarfile: a package of Java code, where Java is a programming language used for many business applications.- Reverse engineering: working backwards from a finished program to understand how it works.
- Decompiling: turning compiled code back into a readable form.
- Log: a file where a program records what it did, often including the exact database queries it ran.
- Payload: the piece of input you send to trigger a vulnerability.
- Stacked query: when a database accepts more than one SQL statement in a single call, so an attacker can append statements of their own.
- Sanitisation: cleaning input before using it, so dangerous content cannot take effect.
- Comment (SQL): text between
/*and*/, or after--, that the database ignores. - Sleep call: a SQL instruction that makes the database wait a number of seconds, used to prove an injection ran.
- PostgreSQL: a popular open-source database server.
- Instance: one running copy of a database server.
root: the most powerful user account on a system.COPY FROM PROGRAM: a PostgreSQL command that runs a shell command and reads its output as data.ping: a standard command that sends a small network message to another machine to see whether it answers.- DNS lookup: the step where a computer asks the domain name system to translate a name into a numeric address.
- Out-of-band: a result observed through a separate channel, such as a DNS request, rather than in the normal response.
- Concatenation: gluing pieces of text together, which is how the vulnerable query was built.
- Parameterisation: sending user input separately from the query so it can never become part of the query's structure.
- Responsible disclosure: telling the vendor privately first, so they can fix an issue before it becomes public.
- Endpoint: a specific address and function in a web application that accepts requests.