Skip to content

ActivityPub-federated video streaming platform using P2P directly in your web browser

Migrate OTP encryption to GCM

Chocobozzz0015dc35e312
diff --git a/client/src/app/+login/login.component.html b/client/src/app/+login/login.component.html
index 47bc00fe52..de97a56b17 100644
--- a/client/src/app/+login/login.component.html
+++ b/client/src/app/+login/login.component.html
@@ -92,7 +92,7 @@
<input type="submit" class="peertube-button primary-button w-100" i18n-value value="Login" [disabled]="!form.valid">
@if (!otpStep) {
- <div class="additional-links d-flex justify-content-center mt-4 mb-5 text-center">
+ <div class="additional-links d-flex justify-content-center my-4 text-center">
<button type="button" i18n class="button-unstyle link-primary mx-3" (click)="openForgotPasswordModal()" i18n-title title="Click here to reset your password">
I forgot my password
</button>
diff --git a/client/src/app/+login/login.component.scss b/client/src/app/+login/login.component.scss
index 8de4de5b80..5e8fb96227 100644
--- a/client/src/app/+login/login.component.scss
+++ b/client/src/app/+login/login.component.scss
@@ -1,6 +1,6 @@
-@use '_variables' as *;
-@use '_mixins' as *;
-@use '_form-mixins' as *;
+@use "_variables" as *;
+@use "_mixins" as *;
+@use "_form-mixins" as *;
label {
display: block;
@@ -9,8 +9,8 @@ label {
@include font-size(18px);
}
-input[type=text],
-input[type=email] {
+input[type="text"],
+input[type="email"] {
@include peertube-input-text(100%);
}
@@ -47,6 +47,7 @@ my-alert {
.external-login-blocks {
min-width: 200px;
+ margin-top: 1rem;
text-align: center;
.external-login-block {
@@ -75,7 +76,7 @@ my-alert {
@include margin-left(10px);
@include margin-right(10px);
@include margin-bottom(2.5rem);
- @include rfs (22rem, min-width);
+ @include rfs(22rem, min-width);
}
.terms-anchor {
diff --git a/client/src/app/+login/login.component.ts b/client/src/app/+login/login.component.ts
index 760592cf18..e8add0438b 100644
--- a/client/src/app/+login/login.component.ts
+++ b/client/src/app/+login/login.component.ts
@@ -1,5 +1,5 @@
import { NgClass } from '@angular/common'
-import { AfterViewInit, Component, ElementRef, LOCALE_ID, OnInit, inject, viewChild, ChangeDetectionStrategy } from '@angular/core'
+import { AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, LOCALE_ID, OnInit, inject, viewChild } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { ActivatedRoute, Router, RouterLink } from '@angular/router'
import { AuthService, Notifier, RedirectService, SessionStorageService, UserService } from '@app/core'
@@ -269,6 +269,11 @@ The link will expire within 1 hour.`
return
}
+ if (err.body?.code === ServerErrorCode.INVALID_TWO_FACTOR) {
+ this.error = $localize`Invalid two-factor authentication token.`
+ return
+ }
+
if (err.body?.code === ServerErrorCode.TOO_LONG_PASSWORD) {
this.error = $localize`Your current password is too long. Please reset it.`
this.passwordTooLongError = true
diff --git a/packages/tests/src/server-helpers/crypto.ts b/packages/tests/src/server-helpers/crypto.ts
index 92fdfcda79..93348f0dda 100644
--- a/packages/tests/src/server-helpers/crypto.ts
+++ b/packages/tests/src/server-helpers/crypto.ts
@@ -1,30 +1,69 @@
/* oxlint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
-import { expect } from 'chai'
import { decrypt, encrypt } from '@peertube/peertube-server/core/helpers/peertube-crypto.js'
+import { expect } from 'chai'
describe('Encrypt/Descrypt', function () {
- it('Should encrypt and decrypt the string', async function () {
- const secret = 'my_secret'
- const str = 'my super string'
+ const secret = 'my_secret'
+ const str = 'my super string'
+ it('Should encrypt and decrypt the string', async function () {
const encrypted = await encrypt(str, secret)
const decrypted = await decrypt(encrypted, secret)
- expect(str).to.equal(decrypted)
+ expect(decrypted).to.equal(str)
+ })
+
+ it('Should emit GCM format (salt:iv:authTag:ciphertext)', async function () {
+ const encrypted = await encrypt(str, secret)
+
+ expect(encrypted.split(':')).to.have.lengthOf(4)
+ })
+
+ it('Should not decrypt with a wrong secret', async function () {
+ const encrypted = await encrypt(str, secret)
+
+ await expectRejection(() => decrypt(encrypted, 'my_sicret'))
})
- it('Should not decrypt without the same secret', async function () {
- const str = 'my super string'
+ it('Should detect a tampered ciphertext', async function () {
+ const encrypted = await encrypt(str, secret)
+
+ const parts = encrypted.split(':')
+ // Flip the last byte of the ciphertext segment
+ const ciphertext = parts[3]
+ const lastByte = parseInt(ciphertext.slice(-2), 16) ^ 0xff
+ parts[3] = ciphertext.slice(0, -2) + lastByte.toString(16).padStart(2, '0')
- const encrypted = await encrypt(str, 'my_secret')
+ await expectRejection(() => decrypt(parts.join(':'), secret))
+ })
- let decrypted = ''
+ it('Should reject a truncated auth tag', async function () {
+ const encrypted = await encrypt(str, secret)
- try {
- decrypted = await decrypt(encrypted, 'my_sicret')
- } catch {}
+ const parts = encrypted.split(':')
+ // Shorten the auth tag segment (parts[2]) from 16 to 4 bytes: a shorter tag weakens forgery resistance
+ parts[2] = parts[2].slice(0, 8)
- expect(decrypted).to.not.equal(encrypted)
+ await expectRejection(() => decrypt(parts.join(':'), secret))
+ })
+
+ it('Should reject an unrecognized (non-GCM) format', async function () {
+ // A pre-GCM 2-part CBC value: no longer decryptable (migrated to GCM at boot by 1090-otp-secret-gcm)
+ const legacy = 'd49a7eafe7f4c39960a562672a3d6304:3be751a9187979523ea87bff3467a016e6a73ad36a513f7ce4719e963a3a29f3'
+
+ await expectRejection(() => decrypt(legacy, 'my_secret'))
})
})
+
+async function expectRejection (fn: () => Promise<any>) {
+ let thrown = false
+
+ try {
+ await fn()
+ } catch {
+ thrown = true
+ }
+
+ expect(thrown, 'expected the promise to reject').to.be.true
+}
diff --git a/server/core/helpers/peertube-crypto.ts b/server/core/helpers/peertube-crypto.ts
index 311f14cd37..b2ac0f56b8 100644
--- a/server/core/helpers/peertube-crypto.ts
+++ b/server/core/helpers/peertube-crypto.ts
@@ -1,6 +1,6 @@
import { ParsedDraftSignature, parseRequestSignature, verifyDraftSignature } from '@misskey-dev/node-http-message-signatures'
import { sha256 } from '@peertube/peertube-node-utils'
-import { createCipheriv, createDecipheriv, timingSafeEqual } from 'crypto'
+import { CipherGCM, createCipheriv, createDecipheriv, DecipherGCM, timingSafeEqual } from 'crypto'
import { Request } from 'express'
import { BCRYPT_SALT_SIZE, ENCRYPTION, PRIVATE_RSA_KEY_SIZE } from '../initializers/constants.js'
import { MActor } from '../types/models/index.js'
@@ -117,28 +117,53 @@ function buildDigest (body: any) {
// Encryption
// ---------------------------------------------------------------------------
+// Format: salt:iv:authTag:ciphertext in hex format
+// AES-256-GCM authenticates the ciphertext, so decrypt() returns exactly the bytes that were encrypted or throws
async function encrypt (str: string, secret: string) {
+ const salt = await randomBytesPromise(ENCRYPTION.SALT)
const iv = await randomBytesPromise(ENCRYPTION.IV)
- const key = await scryptPromise(secret, ENCRYPTION.SALT, 32)
- const cipher = createCipheriv(ENCRYPTION.ALGORITHM, key, iv)
+ const key = await scryptPromise(secret, salt.toString(ENCRYPTION.ENCODING), ENCRYPTION.KEY_LENGTH)
+ const cipher = createCipheriv(ENCRYPTION.ALGORITHM, key, iv) as CipherGCM
- let encrypted = iv.toString(ENCRYPTION.ENCODING) + ':'
- encrypted += cipher.update(str, 'utf8', ENCRYPTION.ENCODING)
- encrypted += cipher.final(ENCRYPTION.ENCODING)
+ let cipherText = cipher.update(str, 'utf8', ENCRYPTION.ENCODING)
+ cipherText += cipher.final(ENCRYPTION.ENCODING)
- return encrypted
+ // The auth tag is only available after final()
+ const authTag = cipher.getAuthTag()
+
+ return [
+ salt.toString(ENCRYPTION.ENCODING),
+ iv.toString(ENCRYPTION.ENCODING),
+ authTag.toString(ENCRYPTION.ENCODING),
+ cipherText
+ ].join(':')
}
async function decrypt (encryptedArg: string, secret: string) {
- const [ ivStr, encryptedStr ] = encryptedArg.split(':')
+ const parts = encryptedArg.split(':')
+
+ // Pre-GCM values (2-part CBC) are re-encrypted at boot by the 1090-otp-secret-gcm migration,
+ // so decrypt() only ever sees the GCM format at runtime
+ if (parts.length !== 4) {
+ throw new Error(`Unrecognized encrypted value format (${parts.length} parts)`)
+ }
+
+ const [ saltStr, ivStr, authTagStr, cipherText ] = parts
+
+ // Pin the auth tag to its expected length
+ const authTag = Buffer.from(authTagStr, ENCRYPTION.ENCODING)
+ if (authTag.length !== ENCRYPTION.AUTH_TAG) {
+ throw new Error(`Invalid auth tag length (${authTag.length} bytes)`)
+ }
- const iv = Buffer.from(ivStr, 'hex')
- const key = await scryptPromise(secret, ENCRYPTION.SALT, 32)
+ const key = await scryptPromise(secret, saltStr, ENCRYPTION.KEY_LENGTH)
- const decipher = createDecipheriv(ENCRYPTION.ALGORITHM, key, iv)
+ const decipher = createDecipheriv(ENCRYPTION.ALGORITHM, key, Buffer.from(ivStr, ENCRYPTION.ENCODING)) as DecipherGCM
+ decipher.setAuthTag(authTag)
- return decipher.update(encryptedStr, ENCRYPTION.ENCODING, 'utf8') + decipher.final('utf8')
+ // final() throws if the auth tag does not match
+ return decipher.update(cipherText, ENCRYPTION.ENCODING, 'utf8') + decipher.final('utf8')
}
// ---------------------------------------------------------------------------
diff --git a/server/core/initializers/constants.ts b/server/core/initializers/constants.ts
index 558d649dcb..fad91be6c8 100644
--- a/server/core/initializers/constants.ts
+++ b/server/core/initializers/constants.ts
@@ -62,7 +62,7 @@ import { CONFIG, registerConfigChangedHandler } from './config.js'
// ---------------------------------------------------------------------------
-export const LAST_MIGRATION_VERSION = 1085
+export const LAST_MIGRATION_VERSION = 1090
// ---------------------------------------------------------------------------
@@ -931,9 +931,11 @@ export let PRIVATE_RSA_KEY_SIZE = 2048
export const BCRYPT_SALT_SIZE = 10
export const ENCRYPTION = {
- ALGORITHM: 'aes-256-cbc',
- IV: 16,
- SALT: 'peertube',
+ ALGORITHM: 'aes-256-gcm',
+ IV: 12, // 96-bit IV, the NIST-recommended size for GCM
+ SALT: 16, // random salt length
+ AUTH_TAG: 16,
+ KEY_LENGTH: 32,
ENCODING: 'hex' as Encoding
}
diff --git a/server/core/initializers/migrations/1090-otp-secret-gcm.ts b/server/core/initializers/migrations/1090-otp-secret-gcm.ts
new file mode 100644
index 0000000000..f20822cc07
--- /dev/null
+++ b/server/core/initializers/migrations/1090-otp-secret-gcm.ts
@@ -0,0 +1,94 @@
+import { logger } from '@server/helpers/logger.js'
+import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from 'crypto'
+import * as Sequelize from 'sequelize'
+import { CONFIG } from '../config.js'
+
+// Crypto is inlined (rather than imported from peertube-crypto.ts) so this migration stays a frozen,
+// self-contained artifact: removing the legacy CBC fallback from the helper later cannot break it
+const ENCODING = 'hex'
+const KEY_LENGTH = 32
+
+async function up (utils: {
+ transaction: Sequelize.Transaction
+ queryInterface: Sequelize.QueryInterface
+ sequelize: Sequelize.Sequelize
+}): Promise<void> {
+ const rows = await utils.sequelize.query<{ id: number, otpSecret: string }>(
+ 'SELECT "id", "otpSecret" FROM "user" WHERE "otpSecret" IS NOT NULL',
+ { type: Sequelize.QueryTypes.SELECT as Sequelize.QueryTypes.SELECT, transaction: utils.transaction }
+ )
+
+ let removed = 0
+
+ for (const { id, otpSecret } of rows) {
+ try {
+ // Already migrated to the GCM format (salt:iv:authTag:ciphertext)
+ if (otpSecret.split(':').length === 4) continue
+
+ const secret = decryptLegacyCBC(otpSecret, CONFIG.SECRETS.PEERTUBE)
+ const newOtpSecret = encryptGCM(secret, CONFIG.SECRETS.PEERTUBE)
+
+ await utils.sequelize.query('UPDATE "user" SET "otpSecret" = :newOtpSecret WHERE "id" = :id', {
+ replacements: { newOtpSecret, id },
+ transaction: utils.transaction
+ })
+ } catch (err) {
+ // An unrecoverable secret (cannot decrypt/re-encrypt) is removed so the user falls back to
+ // password-only login instead of being locked out. Never abort the migration.
+ logger.error(`Failed to re-encrypt OTP secret of user ${id} to AES-256-GCM format, removing it`, { err })
+
+ try {
+ await utils.sequelize.query('UPDATE "user" SET "otpSecret" = NULL WHERE "id" = :id', {
+ replacements: { id },
+ transaction: utils.transaction
+ })
+ removed++
+ } catch (removeErr) {
+ logger.error(`Failed to remove OTP secret of user ${id}`, { err: removeErr })
+ }
+ }
+ }
+
+ if (removed > 0) {
+ logger.warn(
+ `OTP GCM migration removed ${removed}/${rows.length} unreadable two-factor secret(s). ` +
+ `Affected users now log in with password only and must re-enroll two-factor authentication.`
+ )
+ }
+}
+
+function down (options) {
+ throw new Error('Not implemented.')
+}
+
+export {
+ down,
+ up
+}
+
+// ---------------------------------------------------------------------------
+
+// Pre-migration format: iv:ciphertext in hex, aes-256-cbc, static 'peertube' scrypt salt
+function decryptLegacyCBC (encrypted: string, secret: string) {
+ const [ ivStr, ciphertext ] = encrypted.split(':')
+
+ const key = scryptSync(secret, 'peertube', KEY_LENGTH)
+ const decipher = createDecipheriv('aes-256-cbc', key, Buffer.from(ivStr, ENCODING))
+
+ return decipher.update(ciphertext, ENCODING, 'utf8') + decipher.final('utf8')
+}
+
+// Post-migration format: salt:iv:authTag:ciphertext (hex), aes-256-gcm, random per-message salt
+// Mimic function in peertube-crypto.ts
+function encryptGCM (str: string, secret: string) {
+ const salt = randomBytes(16)
+ const iv = randomBytes(12)
+
+ const key = scryptSync(secret, salt.toString(ENCODING), KEY_LENGTH)
+ const cipher = createCipheriv('aes-256-gcm', key, iv)
+
+ const ciphertext = cipher.update(str, 'utf8', ENCODING) + cipher.final(ENCODING)
+ const authTag = cipher.getAuthTag()
+
+ return [ salt.toString(ENCODING), iv.toString(ENCODING), authTag.toString(ENCODING), ciphertext ].join(':')
+}