ActivityPub-federated video streaming platform using P2P directly in your web browser
Security hardening
Chocobozzz863c6afc6a45
diff --git a/server/core/controllers/api/users/token.ts b/server/core/controllers/api/users/token.tsindex e1afb176d8..9c83a9656a 100644--- a/server/core/controllers/api/users/token.ts+++ b/server/core/controllers/api/users/token.ts@@ -7,7 +7,7 @@ import { OTP } from '@server/initializers/constants.js'import { BypassLogin } from '@server/lib/auth/bypass-login.model.js'import { consumeBypassFromExternalAuth, getAuthNameFromRefreshGrant, getBypassFromPasswordGrant } from '@server/lib/auth/external-auth.js'import { MissingTwoFactorError } from '@server/lib/auth/oauth-errors.js'-import { handleOAuthToken } from '@server/lib/auth/oauth-handlers.js'+import { handleOAuthClient, handleOAuthToken } from '@server/lib/auth/oauth-handlers.js'import { revokeToken } from '@server/lib/auth/oauth-token.js'import { Hooks } from '@server/lib/plugins/hooks.js'import {@@ -91,18 +91,20 @@ async function handleToken (req: express.Request, res: express.Response, next: econst grantType = req.body.grant_typetry {+ const client = await handleOAuthClient(req)+const bypassLogin = await buildByPassLogin(req, grantType)const refreshTokenAuthName = grantType === 'refresh_token'? await getAuthNameFromRefreshGrant(req.body.refresh_token): undefined- const options = {+ const token = await handleOAuthToken({+ req,+ client,refreshTokenAuthName,bypassLogin- }-- const token = await handleOAuthToken(req, options)+ })res.set('Cache-Control', 'no-store')res.set('Pragma', 'no-cache')diff --git a/server/core/lib/auth/external-auth.ts b/server/core/lib/auth/external-auth.tsindex 45597cee93..4af7cb431a 100644--- a/server/core/lib/auth/external-auth.ts+++ b/server/core/lib/auth/external-auth.ts@@ -186,7 +186,9 @@ function consumeBypassFromExternalAuth (username: string, externalAuthToken: str}if (user.username !== username) {- throw new Error(`Cannot authenticate user ${user.username} with invalid username ${username}`)+ logger.error(`Cannot authenticate user ${user.username} with invalid username ${username}`)++ throw new Error(`Cannot authenticate user with invalid username ${username}`)}logger.info(diff --git a/server/core/lib/auth/oauth-handlers.ts b/server/core/lib/auth/oauth-handlers.tsindex eee8fd1a59..12de93bc25 100644--- a/server/core/lib/auth/oauth-handlers.ts+++ b/server/core/lib/auth/oauth-handlers.ts@@ -18,7 +18,7 @@ import { Hooks } from '../plugins/hooks.js'import { BypassLogin } from './bypass-login.model.js'import { TooLongPasswordError } from './oauth-errors.js'import { buildToken, getAccessToken, getRefreshToken, revokeToken, saveToken } from './oauth-token.js'-import { getUserOrThrow } from './oauth-user.js'+import { checkUserNotBlockedOrThrow, getUserOrThrow } from './oauth-user.js'/*** Reimplement some functions of OAuth2Server to inject external auth methods@@ -36,9 +36,10 @@ const oAuthServer = new OAuth2Server({// ----------------------------------------------------------------------------export async function handleOAuthToken (req: express.Request, options: { refreshTokenAuthName?: string, bypassLogin?: BypassLogin }) {+// First handler called on the token endpoint: it also validates the shape of the request, so we don't run any+// plugin login or consume the external auth token of a request we will reject later anyway+export async function handleOAuthClient (req: express.Request) {const oauthRequest = new Request(req)- const { refreshTokenAuthName, bypassLogin } = optionsif (oauthRequest.method !== 'POST') {throw new InvalidRequestError('Invalid request: method must be POST')@@ -73,6 +74,20 @@ export async function handleOAuthToken (req: express.Request, options: { refreshthrow new UnauthorizedClientError('Unauthorized client: `grant_type` is invalid')}+ return client+}++export async function handleOAuthToken (options: {+ req: express.Request+ client: OAuthClientModel+ refreshTokenAuthName?: string+ bypassLogin?: BypassLogin+}) {+ const { req, client, refreshTokenAuthName, bypassLogin } = options++ const oauthRequest = new Request(req)++ const grantType = oauthRequest.body.grant_typeconst ip = req.ipconst userAgent = req.headers['user-agent']@@ -178,6 +193,8 @@ async function handleRefreshGrant (options: {throw new InvalidGrantError(req.t('Invalid grant: refresh token has expired'))}+ checkUserNotBlockedOrThrow(refreshToken.user, req)+await revokeToken({ refreshToken: refreshToken.refreshToken })const token = await buildToken({diff --git a/server/core/lib/auth/oauth-user.ts b/server/core/lib/auth/oauth-user.tsindex 9554f39b6c..62f6a84dcd 100644--- a/server/core/lib/auth/oauth-user.ts+++ b/server/core/lib/auth/oauth-user.ts@@ -11,6 +11,7 @@ import express from 'express'import { logger } from '../../helpers/logger.js'import { CONFIG } from '../../initializers/config.js'import { OTP } from '../../initializers/constants.js'+import { sequelizeTypescript } from '../../initializers/database.js'import { OAuthTokenModel } from '../../models/oauth/oauth-token.js'import { UserModel } from '../../models/user/user.js'import { Emailer } from '../emailer.js'@@ -141,9 +142,10 @@ async function handleGetUserBypass (options: {const user = await findExternalUserOrThrow({ externalUser, pluginName, userUpdater, req })- // If the user does not belongs to a plugin, it was created before its installation- // Then we just go through a regular login process+ // If the user does not belongs to a plugin, then we just go through a regular login processif (user.pluginAuth !== null) {+ checkUserNotBlockedOrThrow(user, req)+// This user does not belong to this pluginif (user.pluginAuth !== pluginName) {if (CONFIG.USER.ALLOW_CROSS_PROVIDER_AUTH !== true) {@@ -166,7 +168,7 @@ async function handleGetUserBypass (options: {)user.pluginAuth = pluginName- await updateUserFromExternal({ user, userOptions: externalUser, userUpdater, syncEmail: true })+ await updateUserFromExternal({ user, userOptions: externalUser, userUpdater, syncEmail: true, req })// Tokens issued under the previous auth plugin can no longer have their validity checked by that// plugin's hookTokenValidity (the user is not registered under it anymore), so force a fresh login@@ -174,8 +176,6 @@ async function handleGetUserBypass (options: {}}- checkUserNotBlockedOrThrow(user, req)-return user}@@ -196,8 +196,13 @@ async function findExternalUserOrThrow (options: {const userByExternalId = await UserModel.loadByPluginAuthExternalId(pluginName, externalUser.externalId)if (userByExternalId) {+ // Check the block before updating: a blocked account must not have its profile rewritten by the plugin+ checkUserNotBlockedOrThrow(userByExternalId, req)+// Authoritative match by stable external id: trust it even if the email changed at the identity provider- return updateUserFromExternal({ user: userByExternalId, userOptions: externalUser, userUpdater, syncEmail: true })+ await updateUserFromExternal({ user: userByExternalId, userOptions: externalUser, userUpdater, syncEmail: true, req })++ return userByExternalId}}@@ -217,7 +222,11 @@ async function findExternalUserOrThrow (options: {)}- return updateUserFromExternal({ user: userByEmail, userOptions: externalUser, userUpdater, syncEmail: false })+ checkUserNotBlockedOrThrow(userByEmail, req)++ await updateUserFromExternal({ user: userByEmail, userOptions: externalUser, userUpdater, syncEmail: false, req })++ return userByEmail}return userByEmail@@ -249,8 +258,9 @@ async function updateUserFromExternal (options: {userOptions: ExternalUseruserUpdater: RegisterServerAuthenticatedResult['userUpdater']syncEmail: boolean+ req: express.Request}) {- const { user, userOptions, userUpdater, syncEmail } = options+ const { user, userOptions, userUpdater, syncEmail, req } = optionsif (userUpdater) {{@@ -294,19 +304,30 @@ async function updateUserFromExternal (options: {}if (syncEmail && userOptions.email && user.email !== userOptions.email) {+ await checkExternalEmailIsFreeOrThrow(user, userOptions.email, req)+logger.info('Updating email of user %s to %s after successful external auth.', user.email, userOptions.email)user.email = userOptions.email}- user.Account = await user.Account.save()+ return sequelizeTypescript.transaction(async transaction => {+ user.Account = await user.Account.save({ transaction })- return user.save()+ return user.save({ transaction })+ })}-// ----------------------------------------------------------------------------// Private-// ---------------------------------------------------------------------------+async function checkExternalEmailIsFreeOrThrow (user: MUserDefault, email: string, req: express.Request) {+ const others = (await UserModel.loadByEmailCaseInsensitive(email)).filter(u => u.id !== user.id)+ if (others.length === 0) return++ logger.error('Cannot sync email %s of user %s after external auth: already used by user %s.', email, user.email, others[0].id)++ throw new AccessDeniedError(+ req.t('Refusing external auth bypass: {email} is already used by another account.', { email })+ )+}-function checkUserNotBlockedOrThrow (user: MUser, req: express.Request) {+export function checkUserNotBlockedOrThrow (user: MUser, req: express.Request) {if (user.blocked) throw new AccountBlockedError(req.t('User is blocked.'))}diff --git a/server/core/lib/plugins/plugin-manager.ts b/server/core/lib/plugins/plugin-manager.tsindex 4e4f1f9821..7a92eb06f4 100644--- a/server/core/lib/plugins/plugin-manager.ts+++ b/server/core/lib/plugins/plugin-manager.ts@@ -80,6 +80,10 @@ export class PluginManager implements ServerHook {private hooks: { [name: string]: HookInformationValue[] } = {}private translations: PluginLocalesTranslations = {}+ // Plugins are registered after the HTTP server started accepting requests+ // And are never registered at all when PeerTube runs with `--no-plugins`+ private registrationDone = false+private server: Serverprivate constructor () {@@ -224,8 +228,10 @@ export class PluginManager implements ServerHook {}async isTokenValid (token: MOAuthTokenUser, type: 'access' | 'refresh') {+ if (!this.registrationDone) return true+const auth = this.getAuth(token.User.pluginAuth, token.authName)- if (!auth) return true+ if (!auth) return false // Token is invalid since the auth doesn't exist anymoreif (auth.hookTokenValidity) {try {@@ -331,6 +337,8 @@ export class PluginManager implements ServerHook {}this.sortHooksByPriority()++ this.registrationDone = true}async removeUnsecurePluginsIfNeededBeforeRegistration () {diff --git a/server/core/models/oauth/oauth-token.ts b/server/core/models/oauth/oauth-token.tsindex 8516a38479..d69d54daaf 100644--- a/server/core/models/oauth/oauth-token.ts+++ b/server/core/models/oauth/oauth-token.ts@@ -1,4 +1,5 @@import { TokenSession } from '@peertube/peertube-models'+import { afterCommitIfTransaction } from '@server/helpers/database-utils.js'import { TokensCache } from '@server/lib/auth/tokens-cache.js'import { MUserAccountId } from '@server/types/models/index.js'import { MOAuthTokenUser } from '@server/types/models/oauth/oauth-token.js'@@ -280,20 +281,26 @@ export class OAuthTokenModel extends SequelizeModel<OAuthTokenModel> {// ---------------------------------------------------------------------------- static deleteUserToken (options: {+ static async deleteUserToken (options: {userId: numberaccessTokenException?: stringtransaction?: Transaction}) {const { userId, accessTokenException, transaction } = options- TokensCache.Instance.deleteUserTokens(userId, accessTokenException)-const where = accessTokenException? { userId, accessToken: { [Op.ne]: accessTokenException } }: { userId }- return OAuthTokenModel.destroy({ where, transaction })+ // Bulk destroy does not run the afterDestroy hook, so we have to invalidate the cache ourselves+ // It has to be done once the rows are gone+ const destroyed = await OAuthTokenModel.destroy({ where, transaction })++ afterCommitIfTransaction(transaction, () => {+ TokensCache.Instance.deleteUserTokens(userId, accessTokenException)+ })++ return destroyed}toSessionFormattedJSON (activeToken: string): TokenSession {