aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/helpers/peertube-crypto.ts
diff options
context:
space:
mode:
Diffstat (limited to 'server/helpers/peertube-crypto.ts')
-rw-r--r--server/helpers/peertube-crypto.ts208
1 files changed, 0 insertions, 208 deletions
diff --git a/server/helpers/peertube-crypto.ts b/server/helpers/peertube-crypto.ts
deleted file mode 100644
index 95e78a904..000000000
--- a/server/helpers/peertube-crypto.ts
+++ /dev/null
@@ -1,208 +0,0 @@
1import { compare, genSalt, hash } from 'bcrypt'
2import { createCipheriv, createDecipheriv, createSign, createVerify } from 'crypto'
3import { Request } from 'express'
4import { cloneDeep } from 'lodash'
5import { promisify1, promisify2 } from '@shared/core-utils'
6import { sha256 } from '@shared/extra-utils'
7import { BCRYPT_SALT_SIZE, ENCRYPTION, HTTP_SIGNATURE, PRIVATE_RSA_KEY_SIZE } from '../initializers/constants'
8import { MActor } from '../types/models'
9import { generateRSAKeyPairPromise, randomBytesPromise, scryptPromise } from './core-utils'
10import { jsonld } from './custom-jsonld-signature'
11import { logger } from './logger'
12
13const bcryptComparePromise = promisify2<any, string, boolean>(compare)
14const bcryptGenSaltPromise = promisify1<number, string>(genSalt)
15const bcryptHashPromise = promisify2<any, string | number, string>(hash)
16
17const httpSignature = require('@peertube/http-signature')
18
19function createPrivateAndPublicKeys () {
20 logger.info('Generating a RSA key...')
21
22 return generateRSAKeyPairPromise(PRIVATE_RSA_KEY_SIZE)
23}
24
25// ---------------------------------------------------------------------------
26// User password checks
27// ---------------------------------------------------------------------------
28
29function comparePassword (plainPassword: string, hashPassword: string) {
30 if (!plainPassword) return Promise.resolve(false)
31
32 return bcryptComparePromise(plainPassword, hashPassword)
33}
34
35async function cryptPassword (password: string) {
36 const salt = await bcryptGenSaltPromise(BCRYPT_SALT_SIZE)
37
38 return bcryptHashPromise(password, salt)
39}
40
41// ---------------------------------------------------------------------------
42// HTTP Signature
43// ---------------------------------------------------------------------------
44
45function isHTTPSignatureDigestValid (rawBody: Buffer, req: Request): boolean {
46 if (req.headers[HTTP_SIGNATURE.HEADER_NAME] && req.headers['digest']) {
47 return buildDigest(rawBody.toString()) === req.headers['digest']
48 }
49
50 return true
51}
52
53function isHTTPSignatureVerified (httpSignatureParsed: any, actor: MActor): boolean {
54 return httpSignature.verifySignature(httpSignatureParsed, actor.publicKey) === true
55}
56
57function parseHTTPSignature (req: Request, clockSkew?: number) {
58 const requiredHeaders = req.method === 'POST'
59 ? [ '(request-target)', 'host', 'digest' ]
60 : [ '(request-target)', 'host' ]
61
62 const parsed = httpSignature.parse(req, { clockSkew, headers: requiredHeaders })
63
64 const parsedHeaders = parsed.params.headers
65 if (!parsedHeaders.includes('date') && !parsedHeaders.includes('(created)')) {
66 throw new Error(`date or (created) must be included in signature`)
67 }
68
69 return parsed
70}
71
72// ---------------------------------------------------------------------------
73// JSONLD
74// ---------------------------------------------------------------------------
75
76function isJsonLDSignatureVerified (fromActor: MActor, signedDocument: any): Promise<boolean> {
77 if (signedDocument.signature.type === 'RsaSignature2017') {
78 return isJsonLDRSA2017Verified(fromActor, signedDocument)
79 }
80
81 logger.warn('Unknown JSON LD signature %s.', signedDocument.signature.type, signedDocument)
82
83 return Promise.resolve(false)
84}
85
86// Backward compatibility with "other" implementations
87async function isJsonLDRSA2017Verified (fromActor: MActor, signedDocument: any) {
88 const [ documentHash, optionsHash ] = await Promise.all([
89 createDocWithoutSignatureHash(signedDocument),
90 createSignatureHash(signedDocument.signature)
91 ])
92
93 const toVerify = optionsHash + documentHash
94
95 const verify = createVerify('RSA-SHA256')
96 verify.update(toVerify, 'utf8')
97
98 return verify.verify(fromActor.publicKey, signedDocument.signature.signatureValue, 'base64')
99}
100
101async function signJsonLDObject <T> (byActor: MActor, data: T) {
102 const signature = {
103 type: 'RsaSignature2017',
104 creator: byActor.url,
105 created: new Date().toISOString()
106 }
107
108 const [ documentHash, optionsHash ] = await Promise.all([
109 createDocWithoutSignatureHash(data),
110 createSignatureHash(signature)
111 ])
112
113 const toSign = optionsHash + documentHash
114
115 const sign = createSign('RSA-SHA256')
116 sign.update(toSign, 'utf8')
117
118 const signatureValue = sign.sign(byActor.privateKey, 'base64')
119 Object.assign(signature, { signatureValue })
120
121 return Object.assign(data, { signature })
122}
123
124// ---------------------------------------------------------------------------
125
126function buildDigest (body: any) {
127 const rawBody = typeof body === 'string' ? body : JSON.stringify(body)
128
129 return 'SHA-256=' + sha256(rawBody, 'base64')
130}
131
132// ---------------------------------------------------------------------------
133// Encryption
134// ---------------------------------------------------------------------------
135
136async function encrypt (str: string, secret: string) {
137 const iv = await randomBytesPromise(ENCRYPTION.IV)
138
139 const key = await scryptPromise(secret, ENCRYPTION.SALT, 32)
140 const cipher = createCipheriv(ENCRYPTION.ALGORITHM, key, iv)
141
142 let encrypted = iv.toString(ENCRYPTION.ENCODING) + ':'
143 encrypted += cipher.update(str, 'utf8', ENCRYPTION.ENCODING)
144 encrypted += cipher.final(ENCRYPTION.ENCODING)
145
146 return encrypted
147}
148
149async function decrypt (encryptedArg: string, secret: string) {
150 const [ ivStr, encryptedStr ] = encryptedArg.split(':')
151
152 const iv = Buffer.from(ivStr, 'hex')
153 const key = await scryptPromise(secret, ENCRYPTION.SALT, 32)
154
155 const decipher = createDecipheriv(ENCRYPTION.ALGORITHM, key, iv)
156
157 return decipher.update(encryptedStr, ENCRYPTION.ENCODING, 'utf8') + decipher.final('utf8')
158}
159
160// ---------------------------------------------------------------------------
161
162export {
163 isHTTPSignatureDigestValid,
164 parseHTTPSignature,
165 isHTTPSignatureVerified,
166 buildDigest,
167 isJsonLDSignatureVerified,
168 comparePassword,
169 createPrivateAndPublicKeys,
170 cryptPassword,
171 signJsonLDObject,
172
173 encrypt,
174 decrypt
175}
176
177// ---------------------------------------------------------------------------
178
179function hashObject (obj: any): Promise<any> {
180 return jsonld.promises.normalize(obj, {
181 safe: false,
182 algorithm: 'URDNA2015',
183 format: 'application/n-quads'
184 }).then(res => sha256(res))
185}
186
187function createSignatureHash (signature: any) {
188 const signatureCopy = cloneDeep(signature)
189 Object.assign(signatureCopy, {
190 '@context': [
191 'https://w3id.org/security/v1',
192 { RsaSignature2017: 'https://w3id.org/security#RsaSignature2017' }
193 ]
194 })
195
196 delete signatureCopy.type
197 delete signatureCopy.id
198 delete signatureCopy.signatureValue
199
200 return hashObject(signatureCopy)
201}
202
203function createDocWithoutSignatureHash (doc: any) {
204 const docWithoutSignature = cloneDeep(doc)
205 delete docWithoutSignature.signature
206
207 return hashObject(docWithoutSignature)
208}