]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/peertube-crypto.ts
Move test functions outside extra-utils
[github/Chocobozzz/PeerTube.git] / server / helpers / peertube-crypto.ts
1 import { compare, genSalt, hash } from 'bcrypt'
2 import { createSign, createVerify } from 'crypto'
3 import { Request } from 'express'
4 import { cloneDeep } from 'lodash'
5 import { BCRYPT_SALT_SIZE, HTTP_SIGNATURE, PRIVATE_RSA_KEY_SIZE } from '../initializers/constants'
6 import { MActor } from '../types/models'
7 import { sha256 } from '@shared/core-utils/common/crypto'
8 import { createPrivateKey, getPublicKey, promisify1, promisify2 } from './core-utils'
9 import { jsonld } from './custom-jsonld-signature'
10 import { logger } from './logger'
11
12 const bcryptComparePromise = promisify2<any, string, boolean>(compare)
13 const bcryptGenSaltPromise = promisify1<number, string>(genSalt)
14 const bcryptHashPromise = promisify2<any, string | number, string>(hash)
15
16 const httpSignature = require('@peertube/http-signature')
17
18 async function createPrivateAndPublicKeys () {
19 logger.info('Generating a RSA key...')
20
21 const { key } = await createPrivateKey(PRIVATE_RSA_KEY_SIZE)
22 const { publicKey } = await getPublicKey(key)
23
24 return { privateKey: key, publicKey }
25 }
26
27 // User password checks
28
29 function comparePassword (plainPassword: string, hashPassword: string) {
30 return bcryptComparePromise(plainPassword, hashPassword)
31 }
32
33 async function cryptPassword (password: string) {
34 const salt = await bcryptGenSaltPromise(BCRYPT_SALT_SIZE)
35
36 return bcryptHashPromise(password, salt)
37 }
38
39 // HTTP Signature
40
41 function isHTTPSignatureDigestValid (rawBody: Buffer, req: Request): boolean {
42 if (req.headers[HTTP_SIGNATURE.HEADER_NAME] && req.headers['digest']) {
43 return buildDigest(rawBody.toString()) === req.headers['digest']
44 }
45
46 return true
47 }
48
49 function isHTTPSignatureVerified (httpSignatureParsed: any, actor: MActor): boolean {
50 return httpSignature.verifySignature(httpSignatureParsed, actor.publicKey) === true
51 }
52
53 function parseHTTPSignature (req: Request, clockSkew?: number) {
54 const headers = req.method === 'POST'
55 ? HTTP_SIGNATURE.REQUIRED_HEADERS.POST
56 : HTTP_SIGNATURE.REQUIRED_HEADERS.ALL
57
58 return httpSignature.parse(req, { clockSkew, headers })
59 }
60
61 // JSONLD
62
63 function isJsonLDSignatureVerified (fromActor: MActor, signedDocument: any): Promise<boolean> {
64 if (signedDocument.signature.type === 'RsaSignature2017') {
65 return isJsonLDRSA2017Verified(fromActor, signedDocument)
66 }
67
68 logger.warn('Unknown JSON LD signature %s.', signedDocument.signature.type, signedDocument)
69
70 return Promise.resolve(false)
71 }
72
73 // Backward compatibility with "other" implementations
74 async function isJsonLDRSA2017Verified (fromActor: MActor, signedDocument: any) {
75 const [ documentHash, optionsHash ] = await Promise.all([
76 createDocWithoutSignatureHash(signedDocument),
77 createSignatureHash(signedDocument.signature)
78 ])
79
80 const toVerify = optionsHash + documentHash
81
82 const verify = createVerify('RSA-SHA256')
83 verify.update(toVerify, 'utf8')
84
85 return verify.verify(fromActor.publicKey, signedDocument.signature.signatureValue, 'base64')
86 }
87
88 async function signJsonLDObject <T> (byActor: MActor, data: T) {
89 const signature = {
90 type: 'RsaSignature2017',
91 creator: byActor.url,
92 created: new Date().toISOString()
93 }
94
95 const [ documentHash, optionsHash ] = await Promise.all([
96 createDocWithoutSignatureHash(data),
97 createSignatureHash(signature)
98 ])
99
100 const toSign = optionsHash + documentHash
101
102 const sign = createSign('RSA-SHA256')
103 sign.update(toSign, 'utf8')
104
105 const signatureValue = sign.sign(byActor.privateKey, 'base64')
106 Object.assign(signature, { signatureValue })
107
108 return Object.assign(data, { signature })
109 }
110
111 function buildDigest (body: any) {
112 const rawBody = typeof body === 'string' ? body : JSON.stringify(body)
113
114 return 'SHA-256=' + sha256(rawBody, 'base64')
115 }
116
117 // ---------------------------------------------------------------------------
118
119 export {
120 isHTTPSignatureDigestValid,
121 parseHTTPSignature,
122 isHTTPSignatureVerified,
123 buildDigest,
124 isJsonLDSignatureVerified,
125 comparePassword,
126 createPrivateAndPublicKeys,
127 cryptPassword,
128 signJsonLDObject
129 }
130
131 // ---------------------------------------------------------------------------
132
133 function hashObject (obj: any): Promise<any> {
134 return jsonld.promises
135 .normalize(obj, {
136 algorithm: 'URDNA2015',
137 format: 'application/n-quads'
138 })
139 .then(res => sha256(res))
140 }
141
142 function createSignatureHash (signature: any) {
143 const signatureCopy = cloneDeep(signature)
144 Object.assign(signatureCopy, {
145 '@context': [
146 'https://w3id.org/security/v1',
147 { RsaSignature2017: 'https://w3id.org/security#RsaSignature2017' }
148 ]
149 })
150
151 delete signatureCopy.type
152 delete signatureCopy.id
153 delete signatureCopy.signatureValue
154
155 return hashObject(signatureCopy)
156 }
157
158 function createDocWithoutSignatureHash (doc: any) {
159 const docWithoutSignature = cloneDeep(doc)
160 delete docWithoutSignature.signature
161
162 return hashObject(docWithoutSignature)
163 }