Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.
TypeScript cloud-alternativecollaborationcollaborative-editingdropboxfile-serverfile-sharingfile-storagefile-syncfull-text-searchhomelabnextcloudon-premiseopen-sourceprivacy-firstprivate-cloudrealtimesecureself-hostedstorage-serverwebdav
fix(backend:users): prevent path traversal through federated user logins
johavenc2dd22e6d896
diff --git a/backend/src/applications/users/constants/user.ts b/backend/src/applications/users/constants/user.tsindex f3baa2c7..6192a602 100644--- a/backend/src/applications/users/constants/user.ts+++ b/backend/src/applications/users/constants/user.ts@@ -1,6 +1,5 @@export const USER_PASSWORD_MIN_LENGTH = 8export const USER_MAX_PASSWORD_ATTEMPTS = 10-export const USER_LOGIN_VALIDATION = /^(?! )(?!.* $)[a-zA-Z0-9@\-\\._ ]{2,255}$/export const USER_PATH = {TMP: 'tmp',diff --git a/backend/src/applications/users/dto/create-or-update-user.dto.ts b/backend/src/applications/users/dto/create-or-update-user.dto.tsindex fb7d3fa1..f7d671d7 100644--- a/backend/src/applications/users/dto/create-or-update-user.dto.ts+++ b/backend/src/applications/users/dto/create-or-update-user.dto.ts@@ -1,20 +1,7 @@import { Transform } from 'class-transformer'-import {- IsArray,- IsBoolean,- IsEmail,- IsEnum,- IsInt,- IsNotEmpty,- IsOptional,- IsString,- Matches,- Max,- MaxLength,- Min,- MinLength-} from 'class-validator'-import { USER_GROUP_ROLE, USER_LOGIN_VALIDATION, USER_NOTIFICATION, USER_PASSWORD_MIN_LENGTH, USER_ROLE } from '../constants/user'+import { IsArray, IsBoolean, IsEmail, IsEnum, IsInt, IsNotEmpty, IsOptional, IsString, Max, MaxLength, Min, MinLength } from 'class-validator'+import { USER_GROUP_ROLE, USER_NOTIFICATION, USER_PASSWORD_MIN_LENGTH, USER_ROLE } from '../constants/user'+import { IsUserLogin } from './user-login.dto.decorator'export class OptionalUserDto {@IsOptional()@@ -65,7 +52,7 @@ export class CreateUserDto extends OptionalUserDto {@Transform(({ value }) => (value ? value.trim() : ''))@MinLength(2)@MaxLength(255)- @Matches(USER_LOGIN_VALIDATION)+ @IsUserLogin()login: string@IsNotEmpty()@@ -91,7 +78,7 @@ export class UpdateUserDto extends OptionalUserDto {@Transform(({ value }) => (value ? value.trim() : ''))@MinLength(2)@MaxLength(255)- @Matches(USER_LOGIN_VALIDATION)+ @IsUserLogin()login?: string@IsOptional()diff --git a/backend/src/applications/users/dto/user-login.dto.decorator.ts b/backend/src/applications/users/dto/user-login.dto.decorator.tsnew file mode 100644index 00000000..554833d5--- /dev/null+++ b/backend/src/applications/users/dto/user-login.dto.decorator.ts@@ -0,0 +1,21 @@+import { registerDecorator, ValidationArguments, ValidationOptions } from 'class-validator'+import { isValidUserLogin } from '../utils/login'++export function IsUserLogin(validationOptions?: ValidationOptions) {+ return function (object: object, propertyName: string) {+ registerDecorator({+ name: 'IsUserLogin',+ target: object.constructor,+ propertyName,+ options: validationOptions,+ validator: {+ validate(value: unknown) {+ return isValidUserLogin(value)+ },+ defaultMessage(args: ValidationArguments) {+ return `${args.property} must be a valid user login`+ }+ }+ })+ }+}diff --git a/backend/src/applications/users/models/user.model.ts b/backend/src/applications/users/models/user.model.tsindex ff2088dd..4d42f351 100644--- a/backend/src/applications/users/models/user.model.ts+++ b/backend/src/applications/users/models/user.model.ts@@ -3,11 +3,13 @@ import fs from 'node:fs/promises'import path from 'node:path'import { popFromObject } from '../../../common/shared'import { configuration } from '../../../configuration/config.environment'+import { isPathInside } from '../../files/utils/files'import { SPACE_REPOSITORY } from '../../spaces/constants/spaces'import { GUEST_PERMISSION, USER_PATH, USER_PERMISSION, USER_PERMS_SEP, USER_ROLE } from '../constants/user'import type { Owner } from '../interfaces/owner.interface'import type { UserSecrets } from '../interfaces/user-secrets.interface'import type { User } from '../schemas/user.interface'+import { isSafePathSegment } from '../utils/login'export class UserModel implements User {id: number@@ -68,10 +70,7 @@ export class UserModel implements User {private _homePath: stringget homePath(): string {- if (this.isLink || this.isGuest) {- return (this._homePath ||= path.join(configuration.applications.files.tmpPath, this.isGuest ? 'guests' : 'links', this.login))- }- return (this._homePath ||= path.join(configuration.applications.files.usersPath, this.login))+ return (this._homePath ||= UserModel.getHomePath(this.login, this.isGuest, this.isLink))}private _filesPath: string@@ -134,10 +133,18 @@ export class UserModel implements User {}static getHomePath(userLogin: string, isGuest = false, isLink = false): string {- if (isGuest || isLink) {- return path.join(configuration.applications.files.tmpPath, isGuest ? 'guests' : 'links', userLogin)+ if (!isSafePathSegment(userLogin)) {+ throw new Error('User login must be a single path segment')+ }+ const basePath =+ isGuest || isLink+ ? path.join(configuration.applications.files.tmpPath, isGuest ? 'guests' : 'links')+ : configuration.applications.files.usersPath+ const homePath = path.resolve(basePath, userLogin)+ if (!isPathInside(basePath, homePath)) {+ throw new Error('User login resolves outside user data directory')}- return path.join(configuration.applications.files.usersPath, userLogin)+ return homePath}static getFilesPath(userLogin: string): string {diff --git a/backend/src/applications/users/services/admin-users-manager.service.spec.ts b/backend/src/applications/users/services/admin-users-manager.service.spec.tsindex fc4ac31b..ec45312b 100644--- a/backend/src/applications/users/services/admin-users-manager.service.spec.ts+++ b/backend/src/applications/users/services/admin-users-manager.service.spec.ts@@ -14,6 +14,7 @@ import { FilesQuotaManager } from '../../files/services/files-quota-manager.serv// mock file utils used by the service (delete/rename user space)jest.mock('../../files/utils/files', () => ({+ isPathInside: jest.fn(() => true),isPathExists: jest.fn(),moveFiles: jest.fn(),removeFiles: jest.fn()@@ -30,7 +31,12 @@ jest.mock('../../../common/functions', () => {})// Alias FS mocks (avoid repetitions)-const fs = jest.requireMock('../../files/utils/files') as { isPathExists: jest.Mock; moveFiles: jest.Mock; removeFiles: jest.Mock }+const fs = jest.requireMock('../../files/utils/files') as {+ isPathInside: jest.Mock+ isPathExists: jest.Mock+ moveFiles: jest.Mock+ removeFiles: jest.Mock+}// Helper utilitiesconst expectHttp = async (p: Promise<any>) => expect(p).rejects.toBeInstanceOf(HttpException)@@ -193,6 +199,12 @@ describe(AdminUsersManager.name, () => {adminQueriesMock.usersQueries.createUserOrGuest.mockRejectedValueOnce(new Error('db fail'))await expectHttp(service.createUserOrGuest({ login: 'bob', email: 'b@x', password: 'p', managers: [] } as any, USER_ROLE.USER, false))})++ it('rejects a login that would escape the user directory', async () => {+ await expectHttp(service.createUserOrGuest({ login: '..', email: 'bad@x', password: 'p', managers: [] } as any, USER_ROLE.USER, false))+ expect(adminQueriesMock.usersQueries.checkUserExists).not.toHaveBeenCalled()+ expect(adminQueriesMock.usersQueries.createUserOrGuest).not.toHaveBeenCalled()+ })})describe('updateUserOrGuest - USER branch', () => {@@ -234,6 +246,13 @@ describe(AdminUsersManager.name, () => {expect(adminQueriesMock.usersQueries.updateUserOrGuest).not.toHaveBeenCalled()})+ it('rejects a login that would escape the user directory before rename', async () => {+ setUser({ ...baseUser })+ await expectHttp(service.updateUserOrGuest(baseUser.id, { login: '../outside' } as any))+ expect(adminQueriesMock.usersQueries.checkUserExists).not.toHaveBeenCalled()+ expect(fs.moveFiles).not.toHaveBeenCalled()+ })+it('renameUserSpace impossible (new space exists)', async () => {const current = { ...baseUser }setUser(current)diff --git a/backend/src/applications/users/services/admin-users-manager.service.ts b/backend/src/applications/users/services/admin-users-manager.service.tsindex cfb7d433..f94e08ec 100644--- a/backend/src/applications/users/services/admin-users-manager.service.ts+++ b/backend/src/applications/users/services/admin-users-manager.service.ts@@ -18,6 +18,7 @@ import type { Member } from '../interfaces/member.interface'import { UserModel } from '../models/user.model'import type { Group } from '../schemas/group.interface'import type { User } from '../schemas/user.interface'+import { isValidUserLogin } from '../utils/login'import { AdminUsersQueries } from './admin-users-queries.service'import { FilesQuotaManager } from '../../files/services/files-quota-manager.service'import { FILE_REPOSITORY } from '../../files/constants/operations'@@ -56,6 +57,7 @@ export class AdminUsersManager {userRole: USER_ROLE = USER_ROLE.USER,asAdmin = false): Promise<UserModel | AdminUser | GuestUser> {+ this.validateUserLogin(createUserDto.login)await this.loginOrEmailAlreadyUsed(createUserDto.login, createUserDto.email)try {createUserDto.password = await hashPassword(createUserDto.password)@@ -96,6 +98,7 @@ export class AdminUsersManager {if (user.login === v) {break}+ this.validateUserLogin(v)if (await this.adminQueries.usersQueries.checkUserExists(v)) {throw new HttpException('Login already used', HttpStatus.FORBIDDEN)}@@ -389,6 +392,12 @@ export class AdminUsersManager {}}+ private validateUserLogin(login: string): void {+ if (!isValidUserLogin(login)) {+ throw new HttpException('Invalid login', HttpStatus.BAD_REQUEST)+ }+ }+private async loginOrEmailAlreadyUsed(login: string, email: string) {const exists = await this.adminQueries.usersQueries.checkUserExists(login, email)if (exists) {diff --git a/backend/src/applications/users/utils/login.ts b/backend/src/applications/users/utils/login.tsnew file mode 100644index 00000000..29a97d4a--- /dev/null+++ b/backend/src/applications/users/utils/login.ts@@ -0,0 +1,9 @@+const USER_LOGIN_VALIDATION = /^(?! )(?!.* $)[a-zA-Z0-9@\-._ ]{2,255}$/++export function isSafePathSegment(value: unknown): value is string {+ return typeof value === 'string' && !!value && value !== '.' && value !== '..' && !value.includes('/') && !value.includes('\\')+}++export function isValidUserLogin(login: unknown): login is string {+ return isSafePathSegment(login) && USER_LOGIN_VALIDATION.test(login)+}