085cd62c90df1cc5d05610f9b6f9f04f6bf5634d
[oweals/peertube.git] / server / helpers / peertube-crypto.ts
1 import { Request } from 'express'
2 import { BCRYPT_SALT_SIZE, HTTP_SIGNATURE, PRIVATE_RSA_KEY_SIZE } from '../initializers/constants'
3 import { ActorModel } from '../models/activitypub/actor'
4 import { createPrivateKey, getPublicKey, promisify1, promisify2, sha256 } from './core-utils'
5 import { jsig, jsonld } from './custom-jsonld-signature'
6 import { logger } from './logger'
7 import { cloneDeep } from 'lodash'
8 import { createVerify } from 'crypto'
9 import { buildDigest } from '../lib/job-queue/handlers/utils/activitypub-http-utils'
10 import * as bcrypt from 'bcrypt'
11 import { MActor } from '../typings/models'
12
13 const bcryptComparePromise = promisify2<any, string, boolean>(bcrypt.compare)
14 const bcryptGenSaltPromise = promisify1<number, string>(bcrypt.genSalt)
15 const bcryptHashPromise = promisify2<any, string | number, string>(bcrypt.hash)
16
17 const httpSignature = require('http-signature')
18
19 async function createPrivateAndPublicKeys () {
20   logger.info('Generating a RSA key...')
21
22   const { key } = await createPrivateKey(PRIVATE_RSA_KEY_SIZE)
23   const { publicKey } = await getPublicKey(key)
24
25   return { privateKey: key, publicKey }
26 }
27
28 // User password checks
29
30 function comparePassword (plainPassword: string, hashPassword: string) {
31   return bcryptComparePromise(plainPassword, hashPassword)
32 }
33
34 async function cryptPassword (password: string) {
35   const salt = await bcryptGenSaltPromise(BCRYPT_SALT_SIZE)
36
37   return bcryptHashPromise(password, salt)
38 }
39
40 // HTTP Signature
41
42 function isHTTPSignatureDigestValid (rawBody: Buffer, req: Request): boolean {
43   if (req.headers[HTTP_SIGNATURE.HEADER_NAME] && req.headers['digest']) {
44     return buildDigest(rawBody.toString()) === req.headers['digest']
45   }
46
47   return true
48 }
49
50 function isHTTPSignatureVerified (httpSignatureParsed: any, actor: MActor): boolean {
51   return httpSignature.verifySignature(httpSignatureParsed, actor.publicKey) === true
52 }
53
54 function parseHTTPSignature (req: Request, clockSkew?: number) {
55   return httpSignature.parse(req, { authorizationHeaderName: HTTP_SIGNATURE.HEADER_NAME, clockSkew })
56 }
57
58 // JSONLD
59
60 async function isJsonLDSignatureVerified (fromActor: MActor, signedDocument: any): Promise<boolean> {
61   if (signedDocument.signature.type === 'RsaSignature2017') {
62     // Mastodon algorithm
63     const res = await isJsonLDRSA2017Verified(fromActor, signedDocument)
64     // Success? If no, try with our library
65     if (res === true) return true
66   }
67
68   const publicKeyObject = {
69     '@context': jsig.SECURITY_CONTEXT_URL,
70     id: fromActor.url,
71     type: 'CryptographicKey',
72     owner: fromActor.url,
73     publicKeyPem: fromActor.publicKey
74   }
75
76   const publicKeyOwnerObject = {
77     '@context': jsig.SECURITY_CONTEXT_URL,
78     id: fromActor.url,
79     publicKey: [ publicKeyObject ]
80   }
81
82   const options = {
83     publicKey: publicKeyObject,
84     publicKeyOwner: publicKeyOwnerObject
85   }
86
87   return jsig.promises
88              .verify(signedDocument, options)
89              .then((result: { verified: boolean }) => result.verified)
90              .catch(err => {
91                logger.error('Cannot check signature.', { err })
92                return false
93              })
94 }
95
96 // Backward compatibility with "other" implementations
97 async function isJsonLDRSA2017Verified (fromActor: MActor, signedDocument: any) {
98   function hash (obj: any): Promise<any> {
99     return jsonld.promises
100                  .normalize(obj, {
101                    algorithm: 'URDNA2015',
102                    format: 'application/n-quads'
103                  })
104                  .then(res => sha256(res))
105   }
106
107   const signatureCopy = cloneDeep(signedDocument.signature)
108   Object.assign(signatureCopy, {
109     '@context': [
110       'https://w3id.org/security/v1',
111       { RsaSignature2017: 'https://w3id.org/security#RsaSignature2017' }
112     ]
113   })
114   delete signatureCopy.type
115   delete signatureCopy.id
116   delete signatureCopy.signatureValue
117
118   const docWithoutSignature = cloneDeep(signedDocument)
119   delete docWithoutSignature.signature
120
121   const [ documentHash, optionsHash ] = await Promise.all([
122     hash(docWithoutSignature),
123     hash(signatureCopy)
124   ])
125
126   const toVerify = optionsHash + documentHash
127
128   const verify = createVerify('RSA-SHA256')
129   verify.update(toVerify, 'utf8')
130
131   return verify.verify(fromActor.publicKey, signedDocument.signature.signatureValue, 'base64')
132 }
133
134 function signJsonLDObject (byActor: MActor, data: any) {
135   const options = {
136     privateKeyPem: byActor.privateKey,
137     creator: byActor.url,
138     algorithm: 'RsaSignature2017'
139   }
140
141   return jsig.promises.sign(data, options)
142 }
143
144 // ---------------------------------------------------------------------------
145
146 export {
147   isHTTPSignatureDigestValid,
148   parseHTTPSignature,
149   isHTTPSignatureVerified,
150   isJsonLDSignatureVerified,
151   comparePassword,
152   createPrivateAndPublicKeys,
153   cryptPassword,
154   signJsonLDObject
155 }
156
157 // ---------------------------------------------------------------------------