import { Request } from 'express'
import { BCRYPT_SALT_SIZE, HTTP_SIGNATURE, PRIVATE_RSA_KEY_SIZE } from '../initializers/constants'
-import { ActorModel } from '../models/activitypub/actor'
-import { bcryptComparePromise, bcryptGenSaltPromise, bcryptHashPromise, createPrivateKey, getPublicKey, sha256 } from './core-utils'
-import { jsig, jsonld } from './custom-jsonld-signature'
+import { createPrivateKey, getPublicKey, promisify1, promisify2, sha256 } 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 { createSign, createVerify } from 'crypto'
+import * as bcrypt from 'bcrypt'
+import { MActor } from '../types/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 httpSignature = require('http-signature')
return true
}
-function isHTTPSignatureVerified (httpSignatureParsed: any, actor: ActorModel): boolean {
+function isHTTPSignatureVerified (httpSignatureParsed: any, actor: MActor): boolean {
return httpSignature.verifySignature(httpSignatureParsed, actor.publicKey) === true
}
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: ActorModel, 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
- }
-
- const publicKeyObject = {
- '@context': jsig.SECURITY_CONTEXT_URL,
- id: fromActor.url,
- type: 'CryptographicKey',
- owner: fromActor.url,
- publicKeyPem: fromActor.publicKey
+ return isJsonLDRSA2017Verified(fromActor, signedDocument)
}
- const publicKeyOwnerObject = {
- '@context': jsig.SECURITY_CONTEXT_URL,
- id: fromActor.url,
- publicKey: [ publicKeyObject ]
- }
-
- const options = {
- publicKey: publicKeyObject,
- publicKeyOwner: publicKeyOwnerObject
- }
+ logger.warn('Unknown JSON LD signature %s.', signedDocument.signature.type, signedDocument)
- 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: ActorModel, 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
-
+async function isJsonLDRSA2017Verified (fromActor: MActor, signedDocument: any) {
const [ documentHash, optionsHash ] = await Promise.all([
- hash(docWithoutSignature),
- hash(signatureCopy)
+ createDocWithoutSignatureHash(signedDocument),
+ createSignatureHash(signedDocument.signature)
])
const toVerify = optionsHash + documentHash
return verify.verify(fromActor.publicKey, signedDocument.signature.signatureValue, 'base64')
}
-function signJsonLDObject (byActor: ActorModel, 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')
}
// ---------------------------------------------------------------------------
isHTTPSignatureDigestValid,
parseHTTPSignature,
isHTTPSignatureVerified,
+ buildDigest,
isJsonLDSignatureVerified,
comparePassword,
createPrivateAndPublicKeys,
cryptPassword,
signJsonLDObject
}
+
+// ---------------------------------------------------------------------------
+
+function hash (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 hash(signatureCopy)
+}
+
+function createDocWithoutSignatureHash (doc: any) {
+ const docWithoutSignature = cloneDeep(doc)
+ delete docWithoutSignature.signature
+
+ return hash(docWithoutSignature)
+}