Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
},
"dependencies": {
"@homebridge/ciao": "1.4.1-beta.0",
"@noble/ciphers": "^2.4.0",
"bonjour-hap": "3.11.1-beta.0",
"dbus-native": "^0.16.3",
"debug": "^4.4.3",
Expand Down
57 changes: 56 additions & 1 deletion src/lib/util/hapCrypto.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Buffer } from 'node:buffer'
import crypto from 'node:crypto'

import tweetnacl from 'tweetnacl'
import { beforeEach, describe, expect, it } from 'vitest'
import { beforeEach, describe, expect, it, vi } from 'vitest'

import { HAPEncryption } from './eventedhttp.js'
import * as hapCrypto from './hapCrypto.js'
Expand Down Expand Up @@ -55,6 +55,61 @@ describe('hapCrypto', () => {

expect(() => hapCrypto.chacha20_poly1305_decryptAndVerify(key, nonce, aad, manipulated, tag)).toThrow()
})

describe('without native chacha20-poly1305 (fallback implementation)', () => {
// Runtimes implementing the node:crypto API on another backend (e.g. Bun on BoringSSL) lack this cipher.
// Load a fresh copy of hapCrypto with getCiphers() reporting it absent, so the @noble/ciphers path is used.
async function loadFallback(): Promise<typeof hapCrypto> {
vi.resetModules()
vi.doMock('node:crypto', async () => {
const actual = await vi.importActual<typeof import('node:crypto')>('node:crypto')
const getCiphers = () => actual.getCiphers().filter(name => name !== 'chacha20-poly1305')
return {
...actual,
getCiphers,
default: { ...actual, getCiphers },
}
})
try {
return await import('./hapCrypto.js')
} finally {
vi.doUnmock('node:crypto')
}
}

it('should produce the same ciphertext and tag as the native implementation', async () => {
const fallback = await loadFallback()
const encrypted = fallback.chacha20_poly1305_encryptAndSeal(key, nonce, aad, input)
expect(encrypted.ciphertext.toString('hex')).toBe(output.toString('hex'))
expect(encrypted.authTag.toString('hex')).toBe(tag.toString('hex'))
})

it('should decrypt what the native implementation encrypted', async () => {
const fallback = await loadFallback()
const plaintext = fallback.chacha20_poly1305_decryptAndVerify(key, nonce, aad, output, tag)
expect(plaintext.toString('hex')).toBe(input.toString('hex'))
})

it('should fail verification on manipulated data', async () => {
const fallback = await loadFallback()
const manipulated = Buffer.alloc(output.length)
output.copy(manipulated)
manipulated[3] = 5

expect(() => fallback.chacha20_poly1305_decryptAndVerify(key, nonce, aad, manipulated, tag)).toThrow()
})

it('should match the RFC 8439 section 2.8.2 AEAD test vector without AAD padding tricks', async () => {
const fallback = await loadFallback()
const rfcKey = fromHex('80818283 84858687 88898a8b 8c8d8e8f 90919293 94959697 98999a9b 9c9d9e9f')
const rfcNonce = fromHex('07000000 40414243 44454647')
const rfcAad = fromHex('50515253 c0c1c2c3 c4c5c6c7')
const rfcPlaintext = Buffer.from('Ladies and Gentlemen of the class of \'99: If I could offer you only one tip for the future, sunscreen would be it.')
const encrypted = fallback.chacha20_poly1305_encryptAndSeal(rfcKey, rfcNonce, rfcAad, rfcPlaintext)
expect(encrypted.ciphertext.subarray(0, 16).toString('hex')).toBe('d31a8d34648e60db7b86afbc53ef7ec2')
expect(encrypted.authTag.toString('hex')).toBe('1ae10b594f09e26a7e902ecbd0600691')
})
})
})

describe('HKDF', () => {
Expand Down
33 changes: 29 additions & 4 deletions src/lib/util/hapCrypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,21 @@ import type { HAPEncryption } from './eventedhttp.js'
import assert from 'node:assert'
import { Buffer } from 'node:buffer'
import crypto from 'node:crypto'
import process from 'node:process'

if (!crypto.getCiphers().includes('chacha20-poly1305')) {
// every supported Node.js version has this cipher, unless its OpenSSL was built without it or runs in FIPS mode
assert.fail(`The cipher 'chacha20-poly1305' is not supported by your Node.js ${process.version}. HAP-NodeJS cannot work without it!`)
import { chacha20poly1305 } from '@noble/ciphers/chacha.js'
import createDebug from 'debug'

const debug = createDebug('HAP-NodeJS:Crypto')

/**
* Whether `node:crypto` provides the ChaCha20-Poly1305 AEAD that HAP sessions use.
* Every supported Node.js version has it, unless its OpenSSL was built without it or runs in FIPS mode,
* and runtimes that implement the Node.js API on another crypto backend (Bun on BoringSSL) do not expose it.
* When it is missing, the pure-JavaScript implementation from `@noble/ciphers` is used instead.
*/
const NATIVE_CHACHA20_POLY1305 = crypto.getCiphers().includes('chacha20-poly1305')
if (!NATIVE_CHACHA20_POLY1305) {
debug('node:crypto does not provide chacha20-poly1305; using the @noble/ciphers implementation')
}

const X25519_PKCS8_PREFIX = Buffer.from('302e020100300506032b656e04220420', 'hex')
Expand Down Expand Up @@ -180,6 +190,12 @@ export function chacha20_poly1305_decryptAndVerify(key: Buffer, nonce: Buffer, a
])
}

if (!NATIVE_CHACHA20_POLY1305) {
// noble expects ciphertext || tag and throws if the tag does not verify
const sealed = Buffer.concat([ciphertext, authTag])
return Buffer.from(chacha20poly1305(key, nonce, aad ?? undefined).decrypt(sealed))
}

const decipher = crypto.createDecipheriv('chacha20-poly1305', key, nonce, { authTagLength: 16 })
if (aad) {
decipher.setAAD(aad, { plaintextLength: ciphertext.length })
Expand Down Expand Up @@ -210,6 +226,15 @@ export function chacha20_poly1305_encryptAndSeal(key: Buffer, nonce: Buffer, aad
])
}

if (!NATIVE_CHACHA20_POLY1305) {
// noble returns ciphertext || tag
const sealed = Buffer.from(chacha20poly1305(key, nonce, aad ?? undefined).encrypt(plaintext))
return {
ciphertext: sealed.subarray(0, sealed.length - 16),
authTag: sealed.subarray(sealed.length - 16),
}
}

const cipher = crypto.createCipheriv('chacha20-poly1305', key, nonce, { authTagLength: 16 })

if (aad) {
Expand Down
Loading