Jumpserver Preauth RCE Exploit Chain
JumpServer generated password reset verification codes with Python's non-cryptographic random module, and the captcha library reseeded that same generator with a client-visible key. An attacker could predict the codes and reset any account, including the administrator, then use a path traversal in the playbook file API to write a file and gain remote code execution.
Published on sites.google.com
JumpServer is a well-known open-source Privileged Access Management (PAM) system https://www.jumpserver.org/, widely adopted for its simplicity, ease of use, and open-source security features. Around Sep 2023, we discovered a pre-auth RCE chain in JumpServer.
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.
Context
JumpServer is an open-source Privileged Access Management (PAM) system, widely adopted for its simplicity, ease of use and open-source security features. Around September 2023, while auditing its authentication code, we discovered a pre-authentication RCE chain in JumpServer.
The chain combines two vulnerabilities:
- CVE-2023-42820: prediction of reset password verification codes in JumpServer.
- CVE-2023-42819: authenticated users can perform arbitrary file read/write operations across directories in JumpServer.
A related issue is CVE-2023-46138: an unregistered default built-in email domain for the administrator account leads to password reset and account takeover.
The feature at the centre of the first bug is the ordinary password reset flow: a user asks for a reset, receives a verification code by email or phone, submits it, and is then allowed to set a new password. A graphic captcha guards the early steps to slow down brute force.
Setup
The work started from the source code at https://github.com/jumpserver/jumpserver. No special accounts are needed for the pre-auth part: the attacker only interacts with the password reset and captcha endpoints. JumpServer runs under Gunicorn, which uses the pre-fork worker model, so requests are spread across several worker processes; that detail matters later for the reliability of the attack.
Finding it
Following the usual practice, we scrutinised the code logic related to authentication. After some time reading the password reset code, we found that the flow itself is quite common. The key steps are:
- The client requests the
/core/auth/password/forget/previewing/endpoint with the submitted username parameter. The server queries the database to confirm the existence of the user and caches the user information. - The client submits an email or phone number to the
/api/v1/authentication/password/reset-code/endpoint. After validating the legitimacy of the email or phone number, the server generates and sends a valid verification code to the email or phone. - The client submits the verification code to the
/api/v1/authentication/password/forgot/endpoint. The server verifies whether the cached information and the corresponding verification code match. If successful, it redirects the client to the password reset link. - The client submits the new password to the
/api/v1/authentication/password/reset/endpoint, and the server completes the password reset.
Everything seems right, except for the verification code generation logic:
def create(self, request, *args, **kwargs):
...
random_string(6, lower=False, upper=False) # [1]
...
def random_string(length: int, lower=True, upper=True, digit=True, special_char=False):
args_names = ['lower', 'upper', 'digit', 'special_char']
args_values = [lower, upper, digit, special_char]
args_string = [string.ascii_lowercase, string.ascii_uppercase, string.digits, string_punctuation]
args_string_map = dict(zip(args_names, args_string))
kwargs = dict(zip(args_names, args_values))
kwargs_keys = list(kwargs.keys())
kwargs_values = list(kwargs.values())
args_true_count = len([i for i in kwargs_values if i])
assert any(kwargs_values), f'Parameters {kwargs_keys} must have at least one `True`'
assert length >= args_true_count, f'Expected length >= {args_true_count}, bug got {length}'
can_startswith_special_char = args_true_count == 1 and special_char
chars = ''.join([args_string_map[k] for k, v in kwargs.items() if v])
while True:
password = list(random.choice(chars) for i in range(length)) # [2]
for k, v in kwargs.items():
if v and not (set(password) & set(args_string_map[k])):
break
else:
if not can_startswith_special_char and password[0] in args_string_map['special_char']:
continue
else:
break
password = ''.join(password)
return password
From the call at [1] we can confirm that the verification code is a 6-digit numeric string. The generation is based on Python's random library, and the critical line is the one marked [2]:
password = list(random.choice(chars) for i in range(length)) # [2]
The security risk lies in using Python's random library to generate the verification code. Numbers from random are not cryptographically secure, and the Python documentation explicitly warns against using them for security or cryptographic purposes (https://docs.python.org/3/library/random.html):
Warning The pseudo-random generators of this module should not be used for security purposes. For security or cryptographic uses, see the
secretsmodule.
The random library uses the Mersenne Twister algorithm, and one of its characteristics is that the same seed produces the exact same sequence of random numbers:
>>> random.seed(0x2BBD9883B80) # Set seed: 0x2BBD9883B80
>>> [random.choice(range(10)) for i in range(10)]
[6, 0, 4, 5, 9, 6, 8, 4, 6, 2] # Generate a sequence of 10 random numbers
>>> [random.choice(range(10)) for i in range(10)]
[3, 6, 9, 1, 4, 0, 0, 3, 8, 0] # Continue generating another sequence of 10 random numbers
>>> random.seed(0x2BBD9883B80) # Resetting the same seed: 0x2BBD9883B80
>>> [random.choice(range(10)) for i in range(10)]
[6, 0, 4, 5, 9, 6, 8, 4, 6, 2] # As can be seen, it generates the same sequence as the first one
In other words, if we can determine the seed used by the random library, we can predict the subsequent random numbers. On its own this is not always severe, because in general we do not know the seed. We were about to give up on auditing these features when we noticed that the seemingly ordinary graphic captcha feature also had a significant problem. Combined with the captcha issue, the vulnerability emerges.
Exploitation
Step 1: leak the random seed through the captcha
Like most programs with password login and password reset, JumpServer puts a graphic captcha before submitting parameters to prevent simple programmatic brute force. JumpServer, built on the Django web framework, implements the captcha by introducing the django-simple-captcha library (https://github.com/mbi/django-simple-captcha) and registering its view. The generation and validation logic is:
- The client requests the
/refreshendpoint. The server generates the answer to the graphic captcha and stores it in the database, returning the key containing a 32-byte hexadecimal string hex_key. - The client, with hex_key, requests the
/image/{hex_key}endpoint. The server, based on hex_key, retrieves the captcha answer from the database, generates an image with rotation and random noise to increase the difficulty of machine image recognition, and returns it to the client. - The client submits hex_key and the captcha answer as parameters to the
/previewingendpoint. The server checks if the graphic captcha matches the database, and if it does, continues with the remaining logic of the/previewingendpoint.
In step 2, after generating the image, the hex_key is set as the random library's seed. The critical code snippet is:
def captcha_image(request, key, scale=1):
if scale == 2 and not settings.CAPTCHA_2X_IMAGE:
raise Http404
try:
store = CaptchaStore.objects.get(hashkey=key)
except CaptchaStore.DoesNotExist:
# HTTP 410 Gone status so that crawlers don't index these expired urls.
return HttpResponse(status=410)
random.seed(key) # Do not generate different images for the same key [1]
As established above, knowing the seed of the random library lets us predict the subsequent sequence. The key parameter at [1] is the hex_key, which the client can obtain.
Step 2: predict the verification code and reset any password
Combining the two issues, we can predict the captcha code and thereby reset the password of any account, including administrator accounts. The exploitation process is:
- Request the
/refreshendpoint to obtain hex_key, the random number seed to be used later. - Launch multiple threads, repeatedly call the
/image/{hex_key}endpoint with hex_key as the request parameter, continuously resetting the random number seed of the current process to hex_key. - The main thread sets hex_key as the seed for the random library, generates a random sequence of a certain length (
rand_str) based on the server'srandom_stringfunction logic. - The main thread requests the
/api/v1/authentication/password/reset-code/endpoint, triggering the verification code generation logic. - The main thread iteratively extracts a 6-byte substring from rand_str (e.g.
rand_str[i:i+6]) as the verification code, submits it to the/api/v1/authentication/password/forgot/endpoint, and checks for a successful redirection in the Location header to confirm whether the brute force attempt is successful.
Because JumpServer uses Gunicorn to start the Python web application, and Gunicorn employs the pre-fork worker model where requests are distributed among worker processes (https://docs.gunicorn.org/en/stable/design.html), the goal in steps 0 and 1 is to contaminate the random number seed of as many processes as possible, to increase the success rate in step 4.
In actual exploitation tests, rand_str needed to be skipped by at least 980 bytes before performing the substring extraction to maximise success within 100 brute force attempts. The reason is that between setting the seed in step 1 and triggering the verification code generation in step 3, some other code logic uses the random library to generate a sequence of random numbers, and that length has to be skipped.
Step 3: post-auth arbitrary file write (CVE-2023-42819)
JumpServer supports setting up playbook scripts to automate a series of operations on a large number of machines. That is a useful business feature, but the related API logic allows directory traversal, enabling file creation, writing, modification and deletion in any directory. Here is a snippet of the vulnerable code:
def post(self, request, **kwargs):
content = request.data.get('content', '')
name = request.data.get('name', '') # [1]
def find_new_name(p, is_file=False):
if not p:
if is_file:
p = 'new_file.yml'
else:
p = 'new_dir'
np = os.path.join(full_path, p) # [2]
n = 0
while os.path.exists(np):
n += 1
np = os.path.join(full_path, '{}({})'.format(p, n))
return np
if is_directory:
new_file_path = find_new_name(name)
os.makedirs(new_file_path)
else:
new_file_path = find_new_name(name, True)
with open(new_file_path, 'w') as f:
f.write(content)
A straightforward path concatenation leads to directory traversal: the name parameter from the request at [1] is directly concatenated at [2]. The name parameter can therefore be something like ../../test.py or /tmp/test.py. Absolute paths also work because Python's os.path.join ignores the previous concatenated content when it encounters an absolute path in a later parameter:
>>> import os
>>> os.path.join("/etc/a/b", "/tmp/test.py")
'/tmp/test.py'
Remote code execution is achieved by writing to certain dynamically loaded Python files. Combined with CVE-2023-42820, this forms a complete pre-auth RCE attack chain.
Step 4: the default admin email (CVE-2023-46138)
During our security assessment of the password reset functionality, we found that the default administrator account admin is associated with a default email [redacted]. That may be an attacker-controllable domain: if a malicious attacker buys the domain, they can reset every default admin password in a JumpServer instance. Because CVE-2023-42820 exists, we do not need to buy the domain to reset the admin password.
Root cause
Two independent mistakes combine into the chain.
First, the verification code is generated with Python's random library, a Mersenne Twister PRNG that is deterministic given its seed and explicitly not intended for security purposes. The seed is not secret: django-simple-captcha calls random.seed(key) with the client-visible hex_key when rendering the captcha image, so any client that can request /image/{hex_key} can reproduce the server's random stream. The captcha, meant as an anti-automation control, becomes the very thing that leaks the seed. The pre-fork worker model of Gunicorn means the seed has to be planted in many processes, which is why the attack floods /image/{hex_key} from multiple threads and why a skip of at least 980 bytes is needed to account for other random consumption before the code is generated.
Second, the playbook API builds a file path by joining a user-supplied name onto a base directory with os.path.join, without constraining the result to that directory. Traversal sequences and absolute paths both escape it, and os.path.join adopting an absolute later argument makes the absolute-path case trivial.
The default [redacted] address on the built-in administrator account is a separate design weakness: the domain may be attacker-controllable, so whoever buys it could receive the reset mail.
Impact
CVE-2023-42820 allows takeover of any user account, including administrator accounts, without authentication, by predicting the reset verification code. CVE-2023-42819 lets an authenticated user create, write, modify and delete files in any directory, and writing to dynamically loaded Python files yields code execution. Chained, they give pre-auth RCE. CVE-2023-46138 means whoever controls the default domain, if it can be bought, could reset the password of every default admin account on an affected instance.
The same weakness is not limited to JumpServer. Because django-simple-captcha leaks the random seed and allows adjustable settings, it poses a security risk to any project using it. For example, treeio (https://github.com/treeio/treeio) exhibits almost identical vulnerabilities in its password reset functionality and is similarly affected as CVE-2023-42820.
Fix
The lesson is that introducing uncontrollable code can amplify and escalate inherent security risks within an application. During a code audit it is crucial not to assume the security of any code, especially third-party code libraries.
RCE demo Video
Variants to test
- Other
django-simple-captchadeployments. Request/refresh, take the returned hex_key, call/image/{hex_key}, then seed a local Pythonrandomwith the same key and compare generated values against anything the application later produces fromrandom. A positive result is a captcha answer, token or code that matches your locally generated stream. - Password reset codes on other Django applications. Look for
random.choice,random.randintorrandom_stringhelpers behind reset-code generation. A positive result is a code that can be reproduced from a known or guessable seed. - Playbook or script upload APIs. Submit a
namecontaining../or an absolute path such as/tmp/test.pyand check whether the file lands outside the intended directory. A positive result is a file created at the traversed location. - Default administrator email addresses. Check whether the built-in admin account is tied to a domain that is unregistered. A positive result is a reset mail delivered to a mailbox you can register.
- Seed contamination under pre-fork servers. On Gunicorn or similar pre-fork deployments, flood the seeding endpoint from many threads and measure how often the predicted value is accepted within a bounded number of attempts. A positive result is a success rate high enough to make brute force practical.
Credit
Lawliet & Zhiniang Peng (@edwardzpeng)
What happened, in plain words
JumpServer is a piece of software that companies install on their own servers to manage access to their computers. Think of it as a very secure key cabinet: instead of every employee holding dozens of passwords for dozens of servers, the passwords live inside JumpServer, and people log in to JumpServer to be let through to the machines they are allowed to use. It is open source, meaning anyone can download and read its code, and it is popular because it is simple and free.
In September 2023, two researchers read through JumpServer's code and found a way for an outsider, someone with no account at all, to take over the system completely. They did it by combining two separate mistakes:
- CVE-2023-42820: the six-digit codes that JumpServer emails people when they forget their password can be predicted in advance.
- CVE-2023-42819: a logged-in user can write files anywhere on the server's disk, including places where the server will later run them as programs.
A third, related issue is CVE-2023-46138: the built-in administrator account ships with an email address on a domain that nobody owns, so whoever buys that domain can receive the administrator's password reset emails.
"CVE" stands for Common Vulnerabilities and Exposures. It is a public catalogue number given to a security flaw so that everyone can refer to the same bug unambiguously. "Pre-auth" means the attack works before logging in; "post-auth" means it needs a valid account first. "RCE" stands for Remote Code Execution: the attacker can make the server run their own commands, which is about as bad as it gets.
The feature at the centre of the first bug is the most ordinary thing imaginable: the "forgot my password" button. You type your username, you receive a short code by email or text message, you type the code back, and then you are allowed to choose a new password. A picture of distorted letters, a captcha, sits in front of these steps to stop automated programs from hammering the form. The researchers found that the captcha, which exists to stop automation, was itself handing out the secret that makes automation possible.
Setup
The work started from the source code published at https://github.com/jumpserver/jumpserver. "Source code" is the human-readable text that a program is built from; because JumpServer is open source, anyone can download it and read every line, which is exactly what a code audit is: reading software carefully to spot mistakes before an attacker does.
The pre-auth part of the attack needs no account at all. The attacker only talks to the password reset and captcha pages, the same ones any visitor can reach.
One technical detail matters later: JumpServer runs under a program called Gunicorn. A web application written in Python can only handle one request at a time by itself, so Gunicorn starts several copies of the application, called worker processes, and hands each incoming request to one of them. This is the "pre-fork worker model": the main process starts first and then forks (copies) itself into several workers. The consequence is that the server's memory is not one shared room but several separate rooms, and an attacker who wants to influence all of them has to knock on every door.
Finding it
Following the usual practice, the researchers scrutinised the code logic related to authentication. "Authentication" is simply the process of proving who you are, the login step. After some time reading the password reset code, they found that the flow itself is quite common. The key steps are:
- The client requests the
/core/auth/password/forget/previewing/endpoint with the submitted username parameter. The server queries the database to confirm the existence of the user and caches the user information. - The client submits an email or phone number to the
/api/v1/authentication/password/reset-code/endpoint. After validating the legitimacy of the email or phone number, the server generates and sends a valid verification code to the email or phone. - The client submits the verification code to the
/api/v1/authentication/password/forgot/endpoint. The server verifies whether the cached information and the corresponding verification code match. If successful, it redirects the client to the password reset link. - The client submits the new password to the
/api/v1/authentication/password/reset/endpoint, and the server completes the password reset.
A few words in that list deserve unpacking. The "client" is your browser, or any program acting like one. An "endpoint" is a specific address on the server that accepts a particular kind of request, like a counter in a post office: you go to the counter for passports, not the one for parcels. An "API" (Application Programming Interface) is the set of such counters a program offers to other programs. A "parameter" is a piece of data you hand over with the request, such as the username. To "cache" something is to keep it temporarily in memory so it can be used again shortly without another database lookup. A "redirect" is the server telling your browser "the thing you want is over there", by sending a response with a Location header naming the new address.
Everything seems right, except for the verification code generation logic:
def create(self, request, *args, **kwargs):
...
random_string(6, lower=False, upper=False) # [1]
...
def random_string(length: int, lower=True, upper=True, digit=True, special_char=False):
args_names = ['lower', 'upper', 'digit', 'special_char']
args_values = [lower, upper, digit, special_char]
args_string = [string.ascii_lowercase, string.ascii_uppercase, string.digits, string_punctuation]
args_string_map = dict(zip(args_names, args_string))
kwargs = dict(zip(args_names, args_values))
kwargs_keys = list(kwargs.keys())
kwargs_values = list(kwargs.values())
args_true_count = len([i for i in kwargs_values if i])
assert any(kwargs_values), f'Parameters {kwargs_keys} must have at least one `True`'
assert length >= args_true_count, f'Expected length >= {args_true_count}, bug got {length}'
can_startswith_special_char = args_true_count == 1 and special_char
chars = ''.join([args_string_map[k] for k, v in kwargs.items() if v])
while True:
password = list(random.choice(chars) for i in range(length)) # [2]
for k, v in kwargs.items():
if v and not (set(password) & set(args_string_map[k])):
break
else:
if not can_startswith_special_char and password[0] in args_string_map['special_char']:
continue
else:
break
password = ''.join(password)
return password
Line by line, in plain words:
def create(self, request, *args, **kwargs):starts the function that handles the request to send a reset code. The...lines are omitted code.random_string(6, lower=False, upper=False) # [1]is the call that actually builds the code. It asks for a string of length 6, with lowercase letters off and uppercase letters off. Since digits were not switched off, only digits remain, so the code is six digits.def random_string(...)defines the helper that builds such strings. Its four switches say which character sets may be used: lowercase letters, uppercase letters, digits, and special characters.- The
args_names,args_valuesandargs_stringlines pair each switch name with its on/off value and with the matching set of characters. args_string_map = dict(zip(args_names, args_string))builds a lookup table from switch name to character set, andkwargs = dict(zip(args_names, args_values))builds one from switch name to on/off value.args_true_countcounts how many switches are on. The twoassertlines are safety checks: at least one switch must be on, and the requested length must be at least the number of switches that are on.chars = ''.join(...)collects all allowed characters into one string, which here is just the ten digits.password = list(random.choice(chars) for i in range(length)) # [2]is the critical line: it picks a random character fromchars,lengthtimes, using Python'srandomlibrary. This is where the security problem lives.- The
while True:loop and the checks inside it re-roll the string until it contains at least one character from every switched-on set and does not start with a special character when that is disallowed. With only digits enabled, the first roll always passes. password = ''.join(password)glues the list of characters into one string, andreturn passwordhands it back.
From the call at [1] we can confirm that the verification code is a 6-digit numeric string. The generation is based on Python's random library, and the critical line is the one marked [2]:
password = list(random.choice(chars) for i in range(length)) # [2]
The security risk lies in using Python's random library to generate the verification code. Numbers from random are not cryptographically secure, and the Python documentation explicitly warns against using them for security or cryptographic purposes (https://docs.python.org/3/library/random.html):
Warning The pseudo-random generators of this module should not be used for security purposes. For security or cryptographic uses, see the
secretsmodule.
To understand why, imagine two ways of shuffling a deck of cards. A cryptographic shuffle is like a dealer who genuinely mixes at random, and nobody, not even the dealer, can say what the next card will be. Python's random is more like a very long list of numbers written down in advance: the list looks random, but it is fixed, and anyone holding the same starting point can read the same list. That starting point is called the seed. "Pseudo-random" means exactly this: it looks random but is produced by a deterministic recipe. "Cryptographically secure" means the output cannot be predicted even by someone who knows the recipe, which is what security needs.
The random library uses the Mersenne Twister algorithm, and one of its characteristics is that the same seed produces the exact same sequence of random numbers:
>>> random.seed(0x2BBD9883B80) # Set seed: 0x2BBD9883B80
>>> [random.choice(range(10)) for i in range(10)]
[6, 0, 4, 5, 9, 6, 8, 4, 6, 2] # Generate a sequence of 10 random numbers
>>> [random.choice(range(10)) for i in range(10)]
[3, 6, 9, 1, 4, 0, 0, 3, 8, 0] # Continue generating another sequence of 10 random numbers
>>> random.seed(0x2BBD9883B80) # Resetting the same seed: 0x2BBD9883B80
>>> [random.choice(range(10)) for i in range(10)]
[6, 0, 4, 5, 9, 6, 8, 4, 6, 2] # As can be seen, it generates the same sequence as the first one
This is a Python interactive session, where >>> marks what a person typed and the lines below are the answers. Line by line:
random.seed(0x2BBD9883B80)sets the starting point of the number list to a specific value. The0xprefix just means the number is written in hexadecimal, a base-16 notation.- The first list comprehension asks for ten digits chosen from 0 to 9 and gets
[6, 0, 4, 5, 9, 6, 8, 4, 6, 2]. - The second one continues from where the list left off and gets a different ten digits,
[3, 6, 9, 1, 4, 0, 0, 3, 8, 0]. - The third line resets the seed to the same value, and the fourth line produces
[6, 0, 4, 5, 9, 6, 8, 4, 6, 2]again, identical to the first result.
In other words, if we can determine the seed used by the random library, we can predict the subsequent random numbers. On its own this is not always severe, because in general we do not know the seed. The researchers were about to give up on auditing these features when they noticed that the seemingly ordinary graphic captcha feature also had a significant problem. Combined with the captcha issue, the vulnerability emerges.
Exploitation
Step 1: leak the random seed through the captcha
Like most programs with password login and password reset, JumpServer puts a graphic captcha before submitting parameters to prevent simple programmatic brute force. "Brute force" means trying every possibility in turn, very fast, until one works; a six-digit code has a million possibilities, which a computer can walk through in no time if nothing slows it down. A captcha is meant to be that brake, because reading distorted letters is easy for a person and hard for a program.
JumpServer, built on the Django web framework, implements the captcha by introducing the django-simple-captcha library (https://github.com/mbi/django-simple-captcha) and registering its view. A "framework" is a ready-made skeleton that handles common chores so developers only write the specific parts; a "library" is a collection of ready-made code that a project pulls in rather than writing itself. A "view" in Django is the function that runs when a particular address is requested. The generation and validation logic is:
- The client requests the
/refreshendpoint. The server generates the answer to the graphic captcha and stores it in the database, returning the key containing a 32-byte hexadecimal string hex_key. - The client, with hex_key, requests the
/image/{hex_key}endpoint. The server, based on hex_key, retrieves the captcha answer from the database, generates an image with rotation and random noise to increase the difficulty of machine image recognition, and returns it to the client. - The client submits hex_key and the captcha answer as parameters to the
/previewingendpoint. The server checks if the graphic captcha matches the database, and if it does, continues with the remaining logic of the/previewingendpoint.
In plain terms: the server invents a puzzle, files the answer under a reference number (the hex_key), and gives you the reference number. You ask for the picture using that number, and later you send the number back together with your answer so the server can look up what it filed. "Hexadecimal" is just a way of writing numbers using sixteen symbols instead of ten; a 32-byte hexadecimal string is a long, hard-to-guess identifier. "Random noise" here means speckles and lines drawn over the image so that software has more trouble reading it.
In step 2, after generating the image, the hex_key is set as the random library's seed. The critical code snippet is:
def captcha_image(request, key, scale=1):
if scale == 2 and not settings.CAPTCHA_2X_IMAGE:
raise Http404
try:
store = CaptchaStore.objects.get(hashkey=key)
except CaptchaStore.DoesNotExist:
# HTTP 410 Gone status so that crawlers don't index these expired urls.
return HttpResponse(status=410)
random.seed(key) # Do not generate different images for the same key [1]
Line by line:
def captcha_image(request, key, scale=1):is the function that serves the captcha picture.keyis the hex_key from the URL, andscalesays whether a double-size image was asked for.if scale == 2 and not settings.CAPTCHA_2X_IMAGE:checks whether double-size images are switched off in the settings; if so,raise Http404returns the standard "page not found" error.store = CaptchaStore.objects.get(hashkey=key)looks up the stored captcha record in the database using the key.except CaptchaStore.DoesNotExist:handles the case where no such record exists, andreturn HttpResponse(status=410)replies with HTTP status 410, which means "gone". The comment explains the choice: search engines are told the address is permanently gone so they stop indexing expired links.random.seed(key) # Do not generate different images for the same key [1]is the flaw. The developer's intention was sensible: seed the random generator with the key so that the same key always produces the same picture, instead of a new one on every load. Butkeyis the hex_key, and the client knows it.
As established above, knowing the seed of the random library lets us predict the subsequent sequence. The key parameter at [1] is the hex_key, which the client can obtain. The brake that was supposed to stop automation now tells the attacker exactly which numbers the server will produce next.
Step 2: predict the verification code and reset any password
Combining the two issues, we can predict the captcha code and thereby reset the password of any account, including administrator accounts. The exploitation process is:
- Request the
/refreshendpoint to obtain hex_key, the random number seed to be used later. - Launch multiple threads, repeatedly call the
/image/{hex_key}endpoint with hex_key as the request parameter, continuously resetting the random number seed of the current process to hex_key. - The main thread sets hex_key as the seed for the random library, generates a random sequence of a certain length (
rand_str) based on the server'srandom_stringfunction logic. - The main thread requests the
/api/v1/authentication/password/reset-code/endpoint, triggering the verification code generation logic. - The main thread iteratively extracts a 6-byte substring from rand_str (e.g.
rand_str[i:i+6]) as the verification code, submits it to the/api/v1/authentication/password/forgot/endpoint, and checks for a successful redirection in the Location header to confirm whether the brute force attempt is successful.
A "thread" is one line of work inside a program; a program with several threads can do several things at once, like a cook with several pans on the stove. The "main thread" is the one doing the important sequence while the others keep the server busy. rand_str is simply the name the researchers gave to the long string of predicted digits. rand_str[i:i+6] means "take six characters starting at position i", the same slicing notation Python uses for any string.
Why each step:
- Step 0 gets the key, because everything else depends on knowing it.
- Step 1 exists because of Gunicorn. Each worker process has its own copy of the random generator, and only the process that serves a given request will use its seed. By calling
/image/{hex_key}over and over from many threads, the attacker spreads the same seed into as many worker processes as possible, so that whichever worker later handles the reset-code request is likely to be one that was already primed. - Step 2 reproduces, on the attacker's own machine, the exact sequence the server will produce, because the same seed gives the same sequence.
- Step 3 asks the server to generate a real code, which consumes numbers from that same sequence.
- Step 4 tries the predicted six-digit windows one after another against the endpoint that checks the code. The check for a redirect in the
Locationheader is how the attacker knows a guess was right: a correct code sends the browser onward to the reset page, a wrong one does not.
Because JumpServer uses Gunicorn to start the Python web application, and Gunicorn employs the pre-fork worker model where requests are distributed among worker processes (https://docs.gunicorn.org/en/stable/design.html), the goal in steps 0 and 1 is to contaminate the random number seed of as many processes as possible, to increase the success rate in step 4.
In actual exploitation tests, rand_str needed to be skipped by at least 980 bytes before performing the substring extraction to maximise success within 100 brute force attempts. The reason is that between setting the seed in step 1 and triggering the verification code generation in step 3, some other code logic uses the random library to generate a sequence of random numbers, and that length has to be skipped. In other words, the server draws a number of values for its own purposes before it draws the code, so the attacker must throw away the first part of the predicted sequence to line up with the right position. The figure of 100 attempts is the budget the researchers allowed themselves; the skip made the correct code fall inside it.
Step 3: post-auth arbitrary file write (CVE-2023-42819)
JumpServer supports setting up playbook scripts to automate a series of operations on a large number of machines. A "playbook" is a saved list of steps, like a recipe, that the system carries out on many servers at once instead of an administrator typing each command by hand. That is a useful business feature, but the related API logic allows directory traversal, enabling file creation, writing, modification and deletion in any directory.
"Directory traversal" means tricking a program that is supposed to stay inside one folder into walking out of it. Folders on a disk are arranged in a tree, and .. is the shorthand for "the folder above this one". If a program glues a user-supplied name onto a base folder without checking the result, a name containing .. climbs the tree, and a name starting with / jumps to the very top. Here is a snippet of the vulnerable code:
def post(self, request, **kwargs):
content = request.data.get('content', '')
name = request.data.get('name', '') # [1]
def find_new_name(p, is_file=False):
if not p:
if is_file:
p = 'new_file.yml'
else:
p = 'new_dir'
np = os.path.join(full_path, p) # [2]
n = 0
while os.path.exists(np):
n += 1
np = os.path.join(full_path, '{}({})'.format(p, n))
return np
if is_directory:
new_file_path = find_new_name(name)
os.makedirs(new_file_path)
else:
new_file_path = find_new_name(name, True)
with open(new_file_path, 'w') as f:
f.write(content)
Line by line:
def post(self, request, **kwargs):handles a POST request, the kind a browser sends when you submit a form or upload something.content = request.data.get('content', '')takes the file contents from the request, defaulting to empty.name = request.data.get('name', '') # [1]takes the file or folder name from the request. This is the value the attacker controls.def find_new_name(p, is_file=False):is a helper that works out a path that does not already exist.- The
if not p:block supplies a default name,new_file.ymlfor a file ornew_dirfor a folder, when none was given. np = os.path.join(full_path, p) # [2]is the flaw: it glues the base folderfull_pathand the user-supplied nameptogether with no check that the result stays insidefull_path.- The
while os.path.exists(np):loop appends(1),(2)and so on until the name is free, so an existing file is never overwritten by accident. if is_directory:chooses between making a folder withos.makedirs(new_file_path)and writing a file withopen(new_file_path, 'w')followed byf.write(content).
A straightforward path concatenation leads to directory traversal: the name parameter from the request at [1] is directly concatenated at [2]. The name parameter can therefore be something like ../../test.py or /tmp/test.py. Absolute paths also work because Python's os.path.join ignores the previous concatenated content when it encounters an absolute path in a later parameter:
>>> import os
>>> os.path.join("/etc/a/b", "/tmp/test.py")
'/tmp/test.py'
This session shows the behaviour directly. import os loads Python's operating-system helpers. os.path.join("/etc/a/b", "/tmp/test.py") is supposed to join two pieces of a path, but because the second piece starts with / it is an "absolute path", a full address from the root of the disk, and the result is just '/tmp/test.py'. The first piece is silently thrown away. So a name beginning with / lands wherever the attacker likes, and a name beginning with ../ climbs out of the intended folder.
Remote code execution is achieved by writing to certain dynamically loaded Python files. "Dynamically loaded" means the server reads and runs those files while it is working, rather than only at start-up, so a file planted there is executed without anyone restarting anything. Combined with CVE-2023-42820, this forms a complete pre-auth RCE attack chain: the first bug gives a login, the second turns that login into command execution on the server.
Step 4: the default admin email (CVE-2023-46138)
During our security assessment of the password reset functionality, we found that the default administrator account admin is associated with a default email [redacted]. That may be an attacker-controllable domain: if a malicious attacker buys the domain, they can reset every default admin password in a JumpServer instance. The reasoning is simple: the reset code is emailed to whatever address is on the account, so whoever owns that domain receives the code. Because CVE-2023-42820 exists, we do not need to buy the domain to reset the admin password.
Root cause
Two independent mistakes combine into the chain.
First, the verification code is generated with Python's random library, a Mersenne Twister PRNG that is deterministic given its seed and explicitly not intended for security purposes. "PRNG" stands for pseudo-random number generator, the recipe that produces the fixed-looking list of numbers described earlier. The seed is not secret: django-simple-captcha calls random.seed(key) with the client-visible hex_key when rendering the captcha image, so any client that can request /image/{hex_key} can reproduce the server's random stream. The captcha, meant as an anti-automation control, becomes the very thing that leaks the seed. The pre-fork worker model of Gunicorn means the seed has to be planted in many processes, which is why the attack floods /image/{hex_key} from multiple threads and why a skip of at least 980 bytes is needed to account for other random consumption before the code is generated.
Second, the playbook API builds a file path by joining a user-supplied name onto a base directory with os.path.join, without constraining the result to that directory. Traversal sequences and absolute paths both escape it, and os.path.join adopting an absolute later argument makes the absolute-path case trivial.
The default [redacted] address on the built-in administrator account is a separate design weakness: the domain may be attacker-controllable, so whoever buys it could receive the reset mail.
Impact
CVE-2023-42820 allows takeover of any user account, including administrator accounts, without authentication, by predicting the reset verification code. CVE-2023-42819 lets an authenticated user create, write, modify and delete files in any directory, and writing to dynamically loaded Python files yields code execution. Chained, they give pre-auth RCE. CVE-2023-46138 means whoever controls the default domain, if it can be bought, could reset the password of every default admin account on an affected instance.
The same weakness is not limited to JumpServer. Because django-simple-captcha leaks the random seed and allows adjustable settings, it poses a security risk to any project using it. For example, treeio (https://github.com/treeio/treeio) exhibits almost identical vulnerabilities in its password reset functionality and is similarly affected as CVE-2023-42820. This is the wider lesson of third-party code: a library pulled in for one small job can carry a flaw into every project that uses it.
Fix
The lesson is that introducing uncontrollable code can amplify and escalate inherent security risks within an application. During a code audit it is crucial not to assume the security of any code, especially third-party code libraries.
RCE demo Video
The video below is an RCE demo.
Variants to test
These are the same ideas applied elsewhere, useful when checking other systems:
- Other
django-simple-captchadeployments. Request/refresh, take the returned hex_key, call/image/{hex_key}, then seed a local Pythonrandomwith the same key and compare generated values against anything the application later produces fromrandom. A positive result is a captcha answer, token or code that matches your locally generated stream. - Password reset codes on other Django applications. Look for
random.choice,random.randintorrandom_stringhelpers behind reset-code generation. A positive result is a code that can be reproduced from a known or guessable seed. - Playbook or script upload APIs. Submit a
namecontaining../or an absolute path such as/tmp/test.pyand check whether the file lands outside the intended directory. A positive result is a file created at the traversed location. - Default administrator email addresses. Check whether the built-in admin account is tied to a domain that is unregistered. A positive result is a reset mail delivered to a mailbox you can register.
- Seed contamination under pre-fork servers. On Gunicorn or similar pre-fork deployments, flood the seeding endpoint from many threads and measure how often the predicted value is accepted within a bounded number of attempts. A positive result is a success rate high enough to make brute force practical.
Credit
Lawliet & Zhiniang Peng (@edwardzpeng)
Glossary
- API (Application Programming Interface): the set of addresses and rules a program offers so other programs can talk to it.
- Absolute path: a full file address starting from the root of the disk, such as
/tmp/test.py. - Authentication: the process of proving who you are, the login step.
- Brute force: trying every possible value in turn, quickly, until one works.
- Cache: to keep data temporarily in memory so it can be reused without another lookup.
- Captcha: a small puzzle, usually distorted letters, meant to be easy for people and hard for programs.
- Client: the program making requests, usually a browser.
- Code audit: reading software's source code carefully to find mistakes before attackers do.
- Cryptographically secure: unpredictable even to someone who knows how the value is produced.
- CVE: a public catalogue number for a security flaw, so everyone can refer to the same bug.
- Deterministic: producing the same output every time from the same input.
- Directory traversal: tricking a program into leaving its intended folder by using
..or absolute paths. - Django: a popular framework for building websites in Python.
- Dynamically loaded file: a file the server reads and runs while working, not only at start-up.
- Endpoint: a specific address on a server that accepts a particular kind of request.
- Framework: a ready-made skeleton that handles common chores so developers write only the specific parts.
- Gunicorn: a program that runs Python web applications and spreads requests across several worker processes.
- Header: extra information sent alongside a request or response, such as
Location. - Hexadecimal: a way of writing numbers with sixteen symbols instead of ten.
- HTTP status 410: the server's reply meaning a page is permanently gone.
- Library: a collection of ready-made code a project pulls in instead of writing it itself.
- Location header: the response header that names where a redirect points.
- Mersenne Twister: the algorithm behind Python's
randomlibrary; fast, but predictable from its seed. - Open source: software whose source code anyone can download and read.
- PAM (Privileged Access Management): software that stores and controls access to powerful accounts across many machines.
- Parameter: a piece of data sent along with a request, such as a username.
- Playbook: a saved list of steps the system carries out on many machines at once.
- POST request: the kind of request a browser sends when submitting a form or uploading data.
- Pre-auth / post-auth: before logging in / after logging in.
- PRNG (pseudo-random number generator): a recipe that produces numbers that look random but are fixed by their seed.
- Pre-fork worker model: a server design where a main process copies itself into several workers, each handling requests separately.
- RCE (Remote Code Execution): making a server run the attacker's own commands.
- Redirect: the server telling the browser the wanted thing is at another address.
- Seed: the starting value that fixes the whole sequence a pseudo-random generator will produce.
- Source code: the human-readable text a program is built from.
- Thread: one line of work inside a program; several threads let it do several things at once.
- View: in Django, the function that runs when a particular address is requested.
- Worker process: one of the separate copies of an application that a server like Gunicorn starts to handle requests.