Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

harden protocol decode #859

Merged
merged 1 commit into from
Dec 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion api/stream-relay/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ export class Cache {

// follow the chain to get the buffers in order
const bufs = [...source.values()]
.filter(p => p.previousId.toString('hex') === previous.packetId.toString('hex'))
.filter(p => Buffer.from(p.previousId).toString('hex') === Buffer.from(previous.packetId).toString('hex'))
.sort((a, b) => a.index - b.index)

if (!indexes || bufs.length < indexes) return null
Expand Down
40 changes: 23 additions & 17 deletions api/stream-relay/packets.js
Original file line number Diff line number Diff line change
Expand Up @@ -200,27 +200,33 @@ export const decode = buf => {
for (const [k, spec] of Object.entries(PACKET_SPEC)) {
o[k] = spec.default

if (spec.encoding === 'number') {
const method = getMethod('read', spec.bytes, spec.signed)
o[k] = buf[method](offset)
offset += spec.bytes
continue
}
try {
if (spec.encoding === 'number') {
const method = getMethod('read', spec.bytes, spec.signed)
o[k] = buf[method](offset)
offset += spec.bytes
continue
}

const size = buf.readUInt16BE(offset)
offset += SIZE
let value = buf.slice(offset, offset + size)
offset += size
const size = buf.readUInt16BE(offset)
offset += SIZE
let value = buf.slice(offset, offset + size)
offset += size

if (spec.encoding === 'hex') value = Buffer.from(value, 'hex')
if (spec.encoding === 'base64') value = Buffer.from(value, 'base64')
if (spec.encoding === 'utf8') value = value.toString()
if (spec.bytes && size > spec.bytes) return null

if (k === 'message' && isEncodedAsJSON(o)) {
try { value = JSON.parse(value.toString()) } catch {}
}
if (spec.encoding === 'hex') value = Buffer.from(value, 'hex')
if (spec.encoding === 'base64') value = Buffer.from(value, 'base64')
if (spec.encoding === 'utf8') value = value.toString()

if (k === 'message' && isEncodedAsJSON(o)) {
try { value = JSON.parse(value.toString()) } catch {}
}

o[k] = value
o[k] = value
} catch (err) {
return null // completely bail
}
}

return o
Expand Down