]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/helpers/peertube-crypto.ts
Remove unnecessary NPM_RUN_BUILD_OPTS docker arg
[github/Chocobozzz/PeerTube.git] / server / helpers / peertube-crypto.ts
index 085cd62c90df1cc5d05610f9b6f9f04f6bf5634d..b8f7c782ae7b88ba88463d14f156d43d65a9dec1 100644 (file)
@@ -1,20 +1,19 @@
+import { compare, genSalt, hash } from 'bcrypt'
+import { createSign, createVerify } from 'crypto'
 import { Request } from 'express'
+import { cloneDeep } from 'lodash'
+import { sha256 } from '@shared/extra-utils'
 import { BCRYPT_SALT_SIZE, HTTP_SIGNATURE, PRIVATE_RSA_KEY_SIZE } from '../initializers/constants'
-import { ActorModel } from '../models/activitypub/actor'
-import { createPrivateKey, getPublicKey, promisify1, promisify2, sha256 } from './core-utils'
-import { jsig, jsonld } from './custom-jsonld-signature'
+import { MActor } from '../types/models'
+import { createPrivateKey, getPublicKey, promisify1, promisify2 } from './core-utils'
+import { jsonld } from './custom-jsonld-signature'
 import { logger } from './logger'
-import { cloneDeep } from 'lodash'
-import { createVerify } from 'crypto'
-import { buildDigest } from '../lib/job-queue/handlers/utils/activitypub-http-utils'
-import * as bcrypt from 'bcrypt'
-import { MActor } from '../typings/models'
 
-const bcryptComparePromise = promisify2<any, string, boolean>(bcrypt.compare)
-const bcryptGenSaltPromise = promisify1<number, string>(bcrypt.genSalt)
-const bcryptHashPromise = promisify2<any, string | number, string>(bcrypt.hash)
+const bcryptComparePromise = promisify2<any, string, boolean>(compare)
+const bcryptGenSaltPromise = promisify1<number, string>(genSalt)
+const bcryptHashPromise = promisify2<any, string | number, string>(hash)
 
-const httpSignature = require('http-signature')
+const httpSignature = require('@peertube/http-signature')
 
 async function createPrivateAndPublicKeys () {
   logger.info('Generating a RSA key...')
@@ -52,75 +51,30 @@ function isHTTPSignatureVerified (httpSignatureParsed: any, actor: MActor): bool
 }
 
 function parseHTTPSignature (req: Request, clockSkew?: number) {
-  return httpSignature.parse(req, { authorizationHeaderName: HTTP_SIGNATURE.HEADER_NAME, clockSkew })
+  const headers = req.method === 'POST'
+    ? HTTP_SIGNATURE.REQUIRED_HEADERS.POST
+    : HTTP_SIGNATURE.REQUIRED_HEADERS.ALL
+
+  return httpSignature.parse(req, { clockSkew, headers })
 }
 
 // JSONLD
 
-async function isJsonLDSignatureVerified (fromActor: MActor, signedDocument: any): Promise<boolean> {
+function isJsonLDSignatureVerified (fromActor: MActor, signedDocument: any): Promise<boolean> {
   if (signedDocument.signature.type === 'RsaSignature2017') {
-    // Mastodon algorithm
-    const res = await isJsonLDRSA2017Verified(fromActor, signedDocument)
-    // Success? If no, try with our library
-    if (res === true) return true
+    return isJsonLDRSA2017Verified(fromActor, signedDocument)
   }
 
-  const publicKeyObject = {
-    '@context': jsig.SECURITY_CONTEXT_URL,
-    id: fromActor.url,
-    type: 'CryptographicKey',
-    owner: fromActor.url,
-    publicKeyPem: fromActor.publicKey
-  }
+  logger.warn('Unknown JSON LD signature %s.', signedDocument.signature.type, signedDocument)
 
-  const publicKeyOwnerObject = {
-    '@context': jsig.SECURITY_CONTEXT_URL,
-    id: fromActor.url,
-    publicKey: [ publicKeyObject ]
-  }
-
-  const options = {
-    publicKey: publicKeyObject,
-    publicKeyOwner: publicKeyOwnerObject
-  }
-
-  return jsig.promises
-             .verify(signedDocument, options)
-             .then((result: { verified: boolean }) => result.verified)
-             .catch(err => {
-               logger.error('Cannot check signature.', { err })
-               return false
-             })
+  return Promise.resolve(false)
 }
 
 // Backward compatibility with "other" implementations
 async function isJsonLDRSA2017Verified (fromActor: MActor, signedDocument: any) {
-  function hash (obj: any): Promise<any> {
-    return jsonld.promises
-                 .normalize(obj, {
-                   algorithm: 'URDNA2015',
-                   format: 'application/n-quads'
-                 })
-                 .then(res => sha256(res))
-  }
-
-  const signatureCopy = cloneDeep(signedDocument.signature)
-  Object.assign(signatureCopy, {
-    '@context': [
-      'https://w3id.org/security/v1',
-      { RsaSignature2017: 'https://w3id.org/security#RsaSignature2017' }
-    ]
-  })
-  delete signatureCopy.type
-  delete signatureCopy.id
-  delete signatureCopy.signatureValue
-
-  const docWithoutSignature = cloneDeep(signedDocument)
-  delete docWithoutSignature.signature
-
   const [ documentHash, optionsHash ] = await Promise.all([
-    hash(docWithoutSignature),
-    hash(signatureCopy)
+    createDocWithoutSignatureHash(signedDocument),
+    createSignatureHash(signedDocument.signature)
   ])
 
   const toVerify = optionsHash + documentHash
@@ -131,14 +85,33 @@ async function isJsonLDRSA2017Verified (fromActor: MActor, signedDocument: any)
   return verify.verify(fromActor.publicKey, signedDocument.signature.signatureValue, 'base64')
 }
 
-function signJsonLDObject (byActor: MActor, data: any) {
-  const options = {
-    privateKeyPem: byActor.privateKey,
+async function signJsonLDObject <T> (byActor: MActor, data: T) {
+  const signature = {
+    type: 'RsaSignature2017',
     creator: byActor.url,
-    algorithm: 'RsaSignature2017'
+    created: new Date().toISOString()
   }
 
-  return jsig.promises.sign(data, options)
+  const [ documentHash, optionsHash ] = await Promise.all([
+    createDocWithoutSignatureHash(data),
+    createSignatureHash(signature)
+  ])
+
+  const toSign = optionsHash + documentHash
+
+  const sign = createSign('RSA-SHA256')
+  sign.update(toSign, 'utf8')
+
+  const signatureValue = sign.sign(byActor.privateKey, 'base64')
+  Object.assign(signature, { signatureValue })
+
+  return Object.assign(data, { signature })
+}
+
+function buildDigest (body: any) {
+  const rawBody = typeof body === 'string' ? body : JSON.stringify(body)
+
+  return 'SHA-256=' + sha256(rawBody, 'base64')
 }
 
 // ---------------------------------------------------------------------------
@@ -147,6 +120,7 @@ export {
   isHTTPSignatureDigestValid,
   parseHTTPSignature,
   isHTTPSignatureVerified,
+  buildDigest,
   isJsonLDSignatureVerified,
   comparePassword,
   createPrivateAndPublicKeys,
@@ -155,3 +129,35 @@ export {
 }
 
 // ---------------------------------------------------------------------------
+
+function hashObject (obj: any): Promise<any> {
+  return jsonld.promises
+               .normalize(obj, {
+                 algorithm: 'URDNA2015',
+                 format: 'application/n-quads'
+               })
+               .then(res => sha256(res))
+}
+
+function createSignatureHash (signature: any) {
+  const signatureCopy = cloneDeep(signature)
+  Object.assign(signatureCopy, {
+    '@context': [
+      'https://w3id.org/security/v1',
+      { RsaSignature2017: 'https://w3id.org/security#RsaSignature2017' }
+    ]
+  })
+
+  delete signatureCopy.type
+  delete signatureCopy.id
+  delete signatureCopy.signatureValue
+
+  return hashObject(signatureCopy)
+}
+
+function createDocWithoutSignatureHash (doc: any) {
+  const docWithoutSignature = cloneDeep(doc)
+  delete docWithoutSignature.signature
+
+  return hashObject(docWithoutSignature)
+}