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