Moodle: Blind SQL Injection (CVE-2021-36393) and Broken Access Control (CVE-2021-36397)
Moodle had a blind SQL injection in the ORDER BY clause of a function that fetches recent courses, allowing any user to dump all data. A separate broken access control flaw let an unprivileged user delete chat messages for all users by supplying an admin's user ID.
Earlier this year I participated in the bug bounty program of Moodle. By doing both static and dynamic analysis I found a few vulnerabilities.
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
Moodle is a popular open-source learning management platform written in PHP. It is used by many schools and other educational institutions, and offers a platform where students, teachers and administrators can create courses, assignments and much more. Earlier this year I participated in the bug bounty program of Moodle. By doing both static and dynamic analysis I found a few vulnerabilities. This lead to a nice bounty and my very first CVE IDs. In this post we'll look at some of the details of the vulnerabilities using code and application flow, as well as my thought process on how I found these vulnerabilities. The vulnerabilities in this post are all patched and published.
Two of them are covered here: a blind SQL injection in the functionality that fetches a user's recent courses (CVE-2021-36393, disclosed by Moodle as MSA-21-0021), and a broken access control issue in a function that deletes a chat message for all users (CVE-2021-36397, disclosed as MSA-21-0025).
Setup
The work was done against the Moodle source code, combining static and dynamic analysis. The SQL injection was found by reading the source and then tracing which API call could reach the vulnerable function; the access control issue was found in the code of an API-callable function. The SQL injection could be exploited by any user, such as a student account with the lowest privileges. The access control issue required an unprivileged user and the user ID of an admin account.
Finding it
Finding and exploiting SQL injection is always fun, especially with the source code of the application. Even if an application is using parameterized queries, it might still be vulnerable if the queries are built through string concatenation. It is important to identify potential injection points and then backtrace the data flow from that point to a parameter that you control.
In the source code of Moodle, a lot of SQL query construction through concatenation can be found. These instances are mostly on ORDER BY clauses, while on WHERE clauses parameterized queries are used. Because of the concatenation, it is important to correctly sanitise all of the input that is placed directly into a SQL query string. Otherwise SQL injection becomes possible, as was the cause with the functionality that fetched a user's recent courses.
function course_get_recent_courses(
int $userid = null, int $limit = 0,
int $offset = 0, string $sort = null) {
[...]
$sort = trim($sort);
if (empty($sort)) {
$sort = 'timeaccess DESC';
} else {
$rawsorts = explode(',', $sort);
$sorts = array();
foreach ($rawsorts as $rawsort) {
$rawsort = trim($rawsort);
$sorts[] = trim($rawsort);
}
$sort = implode(',', $sorts);
}
$orderby = "ORDER BY $sort";
[...]
$sql .= $orderby;
$recentcourses = $DB->get_records_sql(
$sql, $params, $offset, $limit);
The function course_get_recent_courses can be called using an API endpoint and we control all 4 of the parameters. In the normal application flow, only the first 3 parameters are used. As a result the data is sorted by the default value timeaccess DESC and the parameter becomes hidden from dynamic analysis.
By doing static analysis on SQL queries, I found this function and saw that the $sort parameter was put directly into the SQL query string. The code simply checks whether it's empty and merely trims the value of whitespace. Afterwards, I found which API call could reach this function and confirmed that I had SQL injection in the ORDER BY clause.
Exploitation
SQL injection in the ORDER BY clause is blind and has to be exploited differently from the more standard union-based SQL injection. In case the sleep() function is working, a timing-based attack will work. Or if some data is returned, the order of the data (ascending or descending) can be used as an oracle for data exfiltration as well.
Step 1: Identify the sink
Static analysis of the SQL queries in the codebase surfaced course_get_recent_courses. The $sort parameter is concatenated into the query string as $orderby = "ORDER BY $sort"; and then appended to $sql, which is passed to $DB->get_records_sql. The only processing applied to the input is trim(), plus splitting on commas and trimming each element, so arbitrary content survives into the ORDER BY clause.
Step 2: Find a reachable API call
Because the function is callable through an API endpoint and all 4 parameters are attacker-controlled, the next step was to find which API call reaches it. In the normal application flow only the first 3 parameters are used, so the data is sorted by the default timeaccess DESC and the $sort parameter stays hidden from dynamic analysis. Once the API call was identified, the injection in the ORDER BY clause was confirmed.
Step 3: Exploit the blind injection
Since the injection point is an ORDER BY clause, the result is blind. Two approaches apply: a timing-based attack if the sleep() function is working, or, if some data is returned, using the order of the data (ascending or descending) as an oracle for data exfiltration.
Root cause
Moodle uses parameterized queries for WHERE clauses, but builds ORDER BY clauses through string concatenation. In course_get_recent_courses the $sort value is only checked for emptiness and trimmed of whitespace before being placed into the query string. That is not sufficient sanitisation for a value placed directly into SQL, so SQL injection becomes possible. The parameter being unused in the normal application flow meant it stayed hidden from dynamic analysis.
Impact
Successful exploitation of the SQL injection could lead to a complete dump of all data. The vulnerability could be exploited by any user, such as a student account with the lowest privileges.
For the broken access control issue, the impact of a vulnerability caused by broken access control completely depends on which functionality is incorrectly controlling access. In this case the issue was in a function that deletes a chat message for all users:
public static function delete_message_for_all_users(
int $messageid, int $userid) {
[...]
$user = core_user::get_user($params['userid'],
'*', MUST_EXIST);
core_user::require_active_user($user);
// Checks if a user can delete a message for all users.
if (core_message\api::can_delete_message_for_all_users(
$user->id, $params['messageid'])) {
\core_message\api::delete_message_for_all_users(
$params['messageid']);
} else {
throw new moodle_exception('You do
not have permission to delete
this message for everyone.');
}
return [];
}
The function delete_message_for_all_users can be called from the API and takes two parameters, messageid and userid. The messageid is used in a later internal call to actually delete that specific message. The more interesting part is that it fetches the user object from the userid parameter and puts it into the $user variable.
In Moodle code, the global $USER object can be used to access information of the logged in user that is calling some endpoint. This variable should therefore be used to check whether someone has access to functionality. However, in this case it checks for access by calling can_delete_message_for_all_users on $user->id instead, which we control through the $userid parameter.
As a result, this check can be bypassed by supplying the user ID of an admin account. The permissions of the admin are checked and the message gets deleted. This vulnerability allows an unprivileged user to mass delete chat messages between arbitrary users.
Fix
For the broken access control issue, the fix was a simple change of $user->id to $USER->id, so the permission of the calling user will be checked instead. Both vulnerabilities were fixed in a new release and disclosed on 19/07/2021.
Variants to test
- Look for
ORDER BYclauses built by concatenation in any PHP codebase, especially where the sort parameter is only trimmed or checked for emptiness. A positive result is a sort parameter that reaches the query string unchanged and changes the order of returned rows. - Trace API-callable functions whose parameters are not used in the normal application flow, as with the fourth parameter here. A positive result is a parameter that is accepted by the endpoint but hidden from the UI, giving an injection point that dynamic testing would miss.
- In functions that fetch a user object from a request parameter and then use it for an authorisation check, try supplying the ID of a higher-privileged account. A positive result is an action performed with the permissions of the supplied user rather than the caller.
- Compare authorisation checks that use
$user->idagainst those that use the global$USER->idin Moodle-style code. A positive result is a check that evaluates the permissions of a user the attacker chooses.
What happened, in plain words
Moodle is a free, open-source learning management platform written in PHP. Schools and other educational institutions use it to run courses, hand out assignments and much more: students, teachers and administrators all log in to the same site and see different things depending on who they are. Moodle runs a bug bounty programme: a scheme where the people who make the software pay security researchers for finding and reporting flaws.
The researcher took part in that programme and found several vulnerabilities by reading the Moodle source code (static analysis) and by using the running application (dynamic analysis). This led to a bounty payment and the researcher's first CVE IDs. A CVE ID is a public catalogue number given to a known security flaw so that everyone can refer to the same issue; the two in this post are CVE-2021-36393 and CVE-2021-36397. All the vulnerabilities described here have been fixed and published.
Two of them are covered in this post:
- A blind SQL injection in the functionality that fetches a user's recent courses (CVE-2021-36393, announced by Moodle as MSA-21-0021).
- A broken access control issue in a function that deletes a chat message for all users (CVE-2021-36397, announced as MSA-21-0025).
Before going further, two ideas need explaining, because everything below depends on them.
What is an API? Think of a restaurant. The dining room (the web page you see in your browser) is the front of house; the kitchen (the database and the server logic) does the real work. The waiter who carries your order to the kitchen and brings the food back is the API. In software, an API is a defined set of requests a program can send to a server to make it do something or return data. Web pages often use APIs behind the scenes: when you click a button, your browser quietly sends a request to an API endpoint (a specific address that accepts one kind of request) and the server answers with data. The important point for us is that an API endpoint can be called directly, not only through the buttons the website shows you. If an endpoint accepts a parameter (an input value) that the normal web page never sends, an attacker can still send it by hand.
What is SQL injection? A database is a big, organised store of information, and the server talks to it in a language called SQL. A typical instruction looks like "give me the courses for user 42, sorted by time". The server builds that instruction as text and sends it to the database. If part of that text comes from the user and is pasted in without care, the user can paste in extra SQL of their own, and the database will obediently run it. It is like a form where you write your name, and the clerk reads your name out loud to a colleague; if you write "John, and also open the safe", a careless clerk might do both. SQL injection is the class of bug where user input changes the meaning of a database instruction instead of just being data inside it.
Setup
The work was done against the Moodle source code, combining static and dynamic analysis. Static analysis means reading the code without running it, looking for dangerous patterns. Dynamic analysis means using the running application, clicking around and watching what it sends and receives. The SQL injection was found by reading the source and then tracing which API call could reach the vulnerable function; the access control issue was found in the code of an API-callable function. The SQL injection could be exploited by any user, such as a student account with the lowest privileges. The access control issue required an unprivileged user and the user ID of an admin account.
Finding it
Finding and exploiting SQL injection is always fun, especially with the source code of the application. Even if an application is using parameterized queries, it might still be vulnerable if the queries are built through string concatenation. It is important to identify potential injection points and then backtrace the data flow from that point to a parameter that you control.
Two more terms are needed here.
Parameterized queries are the safe way to put user input into SQL. Instead of pasting the value into the instruction text, you send the instruction with a blank placeholder and hand the value over separately, so the database treats it purely as data and never as SQL. It is the difference between a form with a box labelled "name" and a clerk who reads whatever you scribbled in the margin.
String concatenation is simply gluing pieces of text together, like joining beads on a string. If a program glues user input directly onto the end of a SQL instruction, the input becomes part of the instruction, and the safety of parameterized queries is lost.
In the source code of Moodle, a lot of SQL query construction through concatenation can be found. These instances are mostly on ORDER BY clauses, while on WHERE clauses parameterized queries are used. An ORDER BY clause is the part of a SQL instruction that says how to sort the results, for example newest first or alphabetically. A WHERE clause is the part that says which rows to pick, for example only rows belonging to user 42. Because of the concatenation, it is important to correctly sanitise all of the input that is placed directly into a SQL query string. Sanitising means cleaning input so that it cannot change the meaning of the instruction. Otherwise SQL injection becomes possible, as was the cause with the functionality that fetched a user's recent courses.
function course_get_recent_courses(
int $userid = null, int $limit = 0,
int $offset = 0, string $sort = null) {
[...]
$sort = trim($sort);
if (empty($sort)) {
$sort = 'timeaccess DESC';
} else {
$rawsorts = explode(',', $sort);
$sorts = array();
foreach ($rawsorts as $rawsort) {
$rawsort = trim($rawsort);
$sorts[] = trim($rawsort);
}
$sort = implode(',', $sorts);
}
$orderby = "ORDER BY $sort";
[...]
$sql .= $orderby;
$recentcourses = $DB->get_records_sql(
$sql, $params, $offset, $limit);
Line by line, in plain words:
function course_get_recent_courses(starts the definition of a function, a named block of code that can be called from elsewhere. Its name says what it does: get the courses a user has recently accessed.int $userid = null, int $limit = 0,declares the first two inputs.$useridis which user's courses to fetch;intmeans it should be a whole number.$limitis how many results to return at most.int $offset = 0, string $sort = null) {declares the last two inputs.$offsetsays where in the list to start (useful for paging through results), and$sortis a piece of text saying how to sort. The= nulland= 0parts are default values used when the caller does not supply that input.[...]marks code that was left out of the excerpt because it is not relevant to the bug.$sort = trim($sort);takes the sort input and removes whitespace from its beginning and end. That is the only cleaning applied at this stage.if (empty($sort)) {checks whether the sort input is now empty.$sort = 'timeaccess DESC';if it is empty, use a default: sort by the time of last access, descending (newest first).} else {otherwise, when the caller did supply something:$rawsorts = explode(',', $sort);splits the input on commas into a list of pieces.explodeis a PHP function that cuts a string wherever it finds a given character.$sorts = array();creates an empty list to hold the cleaned pieces.foreach ($rawsorts as $rawsort) {goes through each piece one at a time.$rawsort = trim($rawsort);trims whitespace from that piece.$sorts[] = trim($rawsort);trims it again (harmless, just redundant) and adds it to the cleaned list.}closes the loop.$sort = implode(',', $sorts);glues the cleaned pieces back together with commas.implodeis the opposite ofexplode.}closes the if/else.$orderby = "ORDER BY $sort";builds the text of the sorting clause by pasting$sortstraight into a string. This is the dangerous line: whatever survived the trimming ends up inside the SQL instruction.[...]more omitted code.$sql .= $orderby;appends the sorting clause to the rest of the SQL instruction..=means "add this to the end of the existing text".$recentcourses = $DB->get_records_sql(calls Moodle's database helper to run the finished instruction.$DBis the database object,get_records_sqlis the method that executes SQL and returns rows.$sql, $params, $offset, $limit);passes the instruction text, the separate parameter values (used safely for theWHEREpart), the offset and the limit.
The function course_get_recent_courses can be called using an API endpoint and we control all 4 of the parameters. In the normal application flow, only the first 3 parameters are used. As a result the data is sorted by the default value timeaccess DESC and the parameter becomes hidden from dynamic analysis. In other words: when you use the website normally, your browser never sends a sort value, so the vulnerable line always receives the harmless default. Someone testing only by clicking around would never see the problem.
By doing static analysis on SQL queries, I found this function and saw that the $sort parameter was put directly into the SQL query string. The code simply checks whether it's empty and merely trims the value of whitespace. Afterwards, I found which API call could reach this function and confirmed that I had SQL injection in the ORDER BY clause.
Exploitation
SQL injection in the ORDER BY clause is blind and has to be exploited differently from the more standard union-based SQL injection. "Blind" means the attacker does not see the database's answer directly on the page: no rows of stolen data appear in the response. Union-based injection is the classic kind where you tack an extra query onto the original one and its results are printed on the page. Here that does not work, so the attacker has to ask yes/no questions and watch for indirect signs.
In case the sleep() function is working, a timing-based attack will work. sleep() is a SQL function that makes the database pause for a given number of seconds. If the attacker can make the database pause only when a guessed condition is true, then the response time tells them the answer: slow means yes, fast means no. It is like asking a locked room a question and listening for a long pause before the knock comes back.
Or if some data is returned, the order of the data (ascending or descending) can be used as an oracle for data exfiltration as well. An oracle, in security, is any observable signal that reveals the answer to a question. Here the signal is the sorting: if a guessed condition is true, the list comes back in one order; if false, in another. By asking many such questions, an attacker can extract data one bit at a time.
Step 1: Identify the sink
Static analysis of the SQL queries in the codebase surfaced course_get_recent_courses. The $sort parameter is concatenated into the query string as $orderby = "ORDER BY $sort"; and then appended to $sql, which is passed to $DB->get_records_sql. The only processing applied to the input is trim(), plus splitting on commas and trimming each element, so arbitrary content survives into the ORDER BY clause.
A "sink" is the place in the code where dangerous data finally gets used, in this case the database call. The method is to start at the sink and walk backwards through the code to see where the data came from and whether an attacker can influence it.
Step 2: Find a reachable API call
Because the function is callable through an API endpoint and all 4 parameters are attacker-controlled, the next step was to find which API call reaches it. In the normal application flow only the first 3 parameters are used, so the data is sorted by the default timeaccess DESC and the $sort parameter stays hidden from dynamic analysis. Once the API call was identified, the injection in the ORDER BY clause was confirmed.
This is why the two kinds of analysis are used together. Reading the code shows that a dangerous parameter exists; using the application shows which request actually delivers it. Neither alone would have found the bug quickly.
Step 3: Exploit the blind injection
Since the injection point is an ORDER BY clause, the result is blind. Two approaches apply: a timing-based attack if the sleep() function is working, or, if some data is returned, using the order of the data (ascending or descending) as an oracle for data exfiltration.
Root cause
Moodle uses parameterized queries for WHERE clauses, but builds ORDER BY clauses through string concatenation. In course_get_recent_courses the $sort value is only checked for emptiness and trimmed of whitespace before being placed into the query string. That is not sufficient sanitisation for a value placed directly into SQL, so SQL injection becomes possible. The parameter being unused in the normal application flow meant it stayed hidden from dynamic analysis.
Impact
Successful exploitation of the SQL injection could lead to a complete dump of all data. The vulnerability could be exploited by any user, such as a student account with the lowest privileges. A "dump" means copying out the entire contents of the database.
For the broken access control issue, the impact of a vulnerability caused by broken access control completely depends on which functionality is incorrectly controlling access. Access control is the part of a program that decides who is allowed to do what: a student may read their own grades, a teacher may edit a course, an administrator may do almost anything. Broken access control means that decision is made wrongly, so someone gets to do something they should not. In this case the issue was in a function that deletes a chat message for all users:
public static function delete_message_for_all_users(
int $messageid, int $userid) {
[...]
$user = core_user::get_user($params['userid'],
'*', MUST_EXIST);
core_user::require_active_user($user);
// Checks if a user can delete a message for all users.
if (core_message\api::can_delete_message_for_all_users(
$user->id, $params['messageid'])) {
\core_message\api::delete_message_for_all_users(
$params['messageid']);
} else {
throw new moodle_exception('You do
not have permission to delete
this message for everyone.');
}
return [];
}
Line by line, in plain words:
public static function delete_message_for_all_users(starts a function that can be called from outside its own class (public) and belongs to the class itself rather than to one particular object (static). Its name says what it does: delete a chat message for everyone.int $messageid, int $userid) {declares its two inputs: which message to delete, and a user ID.[...]omitted code.$user = core_user::get_user($params['userid'],fetches the user record identified by theuseridinput and stores it in$user.$params['userid']is the value the caller supplied.'*', MUST_EXIST);asks for all fields of that user record, and says that if the user does not exist the program should stop with an error rather than continue.core_user::require_active_user($user);checks that this user account is active (not suspended or deleted).// Checks if a user can delete a message for all users.is a comment describing the next step.if (core_message\api::can_delete_message_for_all_users(calls a helper that answers the question "may this user delete this message for everyone?".$user->id, $params['messageid'])) {passes the ID of the user we just fetched, and the message ID. This is the flaw: the permission being checked is that of the user named in the request, not the user making the request.\core_message\api::delete_message_for_all_users(if the check passed, call the function that actually deletes the message.$params['messageid']);pass the message ID to delete.} else {if the check failed:throw new moodle_exception('You dostarts raising an error, with a message saying the caller does not have permission.not have permission to deletecontinues that message text.this message for everyone.');finishes the message and the error call.}closes the if/else.return [];returns an empty result to the caller, meaning the operation finished.
The function delete_message_for_all_users can be called from the API and takes two parameters, messageid and userid. The messageid is used in a later internal call to actually delete that specific message. The more interesting part is that it fetches the user object from the userid parameter and puts it into the $user variable.
In Moodle code, the global $USER object can be used to access information of the logged in user that is calling some endpoint. This variable should therefore be used to check whether someone has access to functionality. However, in this case it checks for access by calling can_delete_message_for_all_users on $user->id instead, which we control through the $userid parameter.
The difference between $USER and $user is the whole bug. $USER is the system's own record of who is actually logged in; the attacker cannot change it. $user here is a record the attacker asked for by number. It is like a bank teller checking the ID of the person named on a form the customer filled in, instead of checking the ID of the customer standing at the counter.
As a result, this check can be bypassed by supplying the user ID of an admin account. The permissions of the admin are checked and the message gets deleted. This vulnerability allows an unprivileged user to mass delete chat messages between arbitrary users.
Fix
For the broken access control issue, the fix was a simple change of $user->id to $USER->id, so the permission of the calling user will be checked instead. Both vulnerabilities were fixed in a new release and disclosed on 19/07/2021.
Variants to test
If you want to look for similar bugs yourself, these are the patterns worth trying:
- Look for
ORDER BYclauses built by concatenation in any PHP codebase, especially where the sort parameter is only trimmed or checked for emptiness. A positive result is a sort parameter that reaches the query string unchanged and changes the order of returned rows. - Trace API-callable functions whose parameters are not used in the normal application flow, as with the fourth parameter here. A positive result is a parameter that is accepted by the endpoint but hidden from the UI, giving an injection point that dynamic testing would miss.
- In functions that fetch a user object from a request parameter and then use it for an authorisation check, try supplying the ID of a higher-privileged account. A positive result is an action performed with the permissions of the supplied user rather than the caller.
- Compare authorisation checks that use
$user->idagainst those that use the global$USER->idin Moodle-style code. A positive result is a check that evaluates the permissions of a user the attacker chooses.
Glossary
- API: a defined set of requests a program can send to a server to make it do something or return data, like a waiter carrying orders between the dining room and the kitchen.
- API endpoint: a specific address that accepts one kind of API request.
- Parameter: an input value sent with a request, such as a user ID or a sort order.
- SQL: the language used to talk to a database, for example to fetch, sort or delete records.
- SQL injection: a bug where user input changes the meaning of a database instruction instead of being treated as plain data.
- Parameterized query: a safe way to send user input to a database, with the input kept separate from the instruction text.
- String concatenation: gluing pieces of text together, which becomes dangerous when one piece is user input and the result is SQL.
- Sanitise: clean input so that it cannot change the meaning of an instruction.
ORDER BYclause: the part of a SQL instruction that says how to sort the results.WHEREclause: the part of a SQL instruction that says which rows to select.- Blind SQL injection: injection where the attacker does not see the database's answer directly and must infer it from indirect signals.
- Union-based SQL injection: injection where an extra query is appended and its results are shown on the page.
- Oracle: any observable signal, such as a delay or a change in sorting, that reveals the answer to a yes/no question.
- Timing-based attack: an attack that uses how long a response takes as the signal.
sleep(): a SQL function that pauses the database for a given number of seconds.- Data exfiltration: extracting data from a system without authorisation.
- Sink: the place in code where dangerous data is finally used, such as a database call.
- Static analysis: examining source code without running the application.
- Dynamic analysis: testing the running application by interacting with it.
- Broken access control: a bug where the program decides wrongly who is allowed to do what.
- Authorisation check: the part of a program that verifies whether a user is permitted to perform an action.
$USER: in Moodle, the global record of the user who is actually logged in and making the request.$user: in this code, a user record fetched from a request parameter, which the attacker can choose.- Privilege: the level of permission an account has; an administrator has high privilege, a student has low privilege.
- CVE ID: a public catalogue number for a known security flaw.
- Bug bounty programme: a scheme where software makers pay researchers for finding and reporting security flaws.
- Bounty: the payment made for a valid report.
- Patch: a fix applied to the software.
- PHP: the programming language Moodle is written in.