signal-desktop/ts/textsecure/CDSSocket.ts

297 lines
8 KiB
TypeScript
Raw Normal View History

2021-11-08 23:32:31 +00:00
// Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import { EventEmitter } from 'events';
2022-03-09 19:28:40 +00:00
import { noop } from 'lodash';
import { Readable } from 'stream';
2021-11-08 23:32:31 +00:00
import type { HsmEnclaveClient } from '@signalapp/signal-client';
import type { connection as WebSocket } from 'websocket';
import Long from 'long';
import { strictAssert } from '../util/assert';
2021-12-06 22:54:20 +00:00
import { dropNull } from '../util/dropNull';
2021-11-08 23:32:31 +00:00
import { explodePromise } from '../util/explodePromise';
import * as durations from '../util/durations';
2022-03-09 19:28:40 +00:00
import * as log from '../logging/log';
2021-11-08 23:32:31 +00:00
import type { UUIDStringType } from '../types/UUID';
2021-12-06 22:54:20 +00:00
import { UUID_BYTE_SIZE } from '../types/UUID';
2021-11-08 23:32:31 +00:00
import * as Bytes from '../Bytes';
import * as Timers from '../Timers';
2021-12-06 22:54:20 +00:00
import { uuidToBytes, bytesToUuid } from '../Crypto';
import { SignalService as Proto } from '../protobuf';
2021-11-08 23:32:31 +00:00
enum State {
Handshake,
Established,
Closed,
}
2022-03-09 19:28:40 +00:00
export type CDSRequestOptionsType = Readonly<
{
auth: CDSAuthType;
e164s: ReadonlyArray<string>;
timeout?: number;
} & (
| {
version: 1;
acis?: undefined;
accessKeys?: undefined;
}
| {
version: 2;
acis: ReadonlyArray<UUIDStringType>;
accessKeys: ReadonlyArray<string>;
}
)
>;
2021-11-12 20:45:30 +00:00
export type CDSAuthType = Readonly<{
username: string;
password: string;
}>;
2021-12-06 22:54:20 +00:00
export type CDSSocketDictionaryEntryType = Readonly<{
aci: UUIDStringType | undefined;
pni: UUIDStringType | undefined;
}>;
export type CDSSocketDictionaryType = Readonly<
Record<string, CDSSocketDictionaryEntryType>
>;
export type CDSSocketResponseType = Readonly<{
dictionary: CDSSocketDictionaryType;
retryAfterSecs?: number;
}>;
2022-03-09 19:28:40 +00:00
const MAX_E164_COUNT = 5000;
2021-11-08 23:32:31 +00:00
const HANDSHAKE_TIMEOUT = 10 * durations.SECOND;
const REQUEST_TIMEOUT = 10 * durations.SECOND;
2021-12-06 22:54:20 +00:00
const E164_BYTE_SIZE = 8;
2022-03-09 19:28:40 +00:00
const TRIPLE_BYTE_SIZE = UUID_BYTE_SIZE * 2 + E164_BYTE_SIZE;
2021-11-08 23:32:31 +00:00
export class CDSSocket extends EventEmitter {
private state = State.Handshake;
private readonly finishedHandshake: Promise<void>;
2022-03-09 19:28:40 +00:00
private readonly responseStream = new Readable({
read: noop,
// Don't coalesce separate websocket messages
objectMode: true,
});
2021-11-08 23:32:31 +00:00
constructor(
private readonly socket: WebSocket,
private readonly enclaveClient: HsmEnclaveClient
) {
super();
const {
promise: finishedHandshake,
resolve,
reject,
} = explodePromise<void>();
this.finishedHandshake = finishedHandshake;
const timer = Timers.setTimeout(() => {
reject(new Error('CDS handshake timed out'));
}, HANDSHAKE_TIMEOUT);
socket.on('message', ({ type, binaryData }) => {
strictAssert(type === 'binary', 'Invalid CDS socket packet');
strictAssert(binaryData, 'Invalid CDS socket packet');
if (this.state === State.Handshake) {
this.enclaveClient.completeHandshake(binaryData);
this.state = State.Established;
Timers.clearTimeout(timer);
resolve();
return;
}
2022-03-09 19:28:40 +00:00
try {
this.responseStream.push(
this.enclaveClient.establishedRecv(binaryData)
);
} catch (error) {
this.responseStream.destroy(error);
}
2021-11-08 23:32:31 +00:00
});
socket.on('close', (code, reason) => {
2022-03-09 19:28:40 +00:00
if (this.state === State.Established) {
if (code === 1000) {
this.responseStream.push(null);
} else {
this.responseStream.destroy(
new Error(`Socket closed with code ${code} and reason ${reason}`)
);
}
}
2021-11-08 23:32:31 +00:00
this.state = State.Closed;
this.emit('close', code, reason);
});
socket.on('error', (error: Error) => this.emit('error', error));
socket.sendBytes(this.enclaveClient.initialRequest());
}
public close(code: number, reason: string): void {
this.socket.close(code, reason);
}
public async request({
2022-03-09 19:28:40 +00:00
version,
2021-11-08 23:32:31 +00:00
timeout = REQUEST_TIMEOUT,
2022-03-09 19:28:40 +00:00
e164s,
acis = [],
accessKeys = [],
2021-12-06 22:54:20 +00:00
}: CDSRequestOptionsType): Promise<CDSSocketResponseType> {
2021-11-08 23:32:31 +00:00
strictAssert(
2022-03-09 19:28:40 +00:00
e164s.length < MAX_E164_COUNT,
'CDSSocket does not support paging. Use this for one-off requests'
2021-11-08 23:32:31 +00:00
);
2022-03-09 19:28:40 +00:00
log.info('CDSSocket.request(): awaiting handshake');
await this.finishedHandshake;
2021-11-12 20:45:30 +00:00
strictAssert(
2022-03-09 19:28:40 +00:00
this.state === State.Established,
'Connection not established'
2021-11-12 20:45:30 +00:00
);
2021-12-06 22:54:20 +00:00
strictAssert(
acis.length === accessKeys.length,
`Number of ACIs ${acis.length} is different ` +
`from number of access keys ${accessKeys.length}`
);
2022-03-09 19:28:40 +00:00
const aciUakPairs = new Array<Uint8Array>();
2021-12-06 22:54:20 +00:00
for (let i = 0; i < acis.length; i += 1) {
2022-03-09 19:28:40 +00:00
aciUakPairs.push(
2021-12-06 22:54:20 +00:00
Bytes.concatenate([
uuidToBytes(acis[i]),
Bytes.fromBase64(accessKeys[i]),
])
);
}
const request = Proto.CDSClientRequest.encode({
2022-03-09 19:28:40 +00:00
newE164s: Buffer.concat(
e164s.map(e164 => {
// Long.fromString handles numbers with or without a leading '+'
return new Uint8Array(Long.fromString(e164).toBytesBE());
})
),
aciUakPairs: Buffer.concat(aciUakPairs),
2021-12-06 22:54:20 +00:00
}).finish();
2021-11-08 23:32:31 +00:00
const timer = Timers.setTimeout(() => {
2022-03-09 19:28:40 +00:00
this.responseStream.destroy(new Error('CDS request timed out'));
2021-11-08 23:32:31 +00:00
}, timeout);
2022-03-09 19:28:40 +00:00
log.info(`CDSSocket.request(): sending version=${version} request`);
2021-11-08 23:32:31 +00:00
this.socket.sendBytes(
2022-03-09 19:28:40 +00:00
this.enclaveClient.establishedSend(
Buffer.concat([Buffer.from([version]), request])
)
2021-11-08 23:32:31 +00:00
);
2022-03-09 19:28:40 +00:00
const resultMap: Map<string, CDSSocketDictionaryEntryType> = new Map();
let retryAfterSecs: number | undefined;
2021-11-08 23:32:31 +00:00
2022-03-09 19:28:40 +00:00
for await (const message of this.responseStream) {
log.info('CDSSocket.request(): processing response message');
2021-12-06 22:54:20 +00:00
2022-03-09 19:28:40 +00:00
const response = Proto.CDSClientResponse.decode(message);
const newRetryAfterSecs = dropNull(response.retryAfterSecs);
2021-12-06 22:54:20 +00:00
2022-03-09 19:28:40 +00:00
decodeSingleResponse(resultMap, response);
2021-12-06 22:54:20 +00:00
2022-03-09 19:28:40 +00:00
if (newRetryAfterSecs) {
retryAfterSecs = Math.max(newRetryAfterSecs, retryAfterSecs ?? 0);
}
}
2021-12-06 22:54:20 +00:00
2022-03-09 19:28:40 +00:00
const result: Record<string, CDSSocketDictionaryEntryType> =
Object.create(null);
2021-12-06 22:54:20 +00:00
2022-03-09 19:28:40 +00:00
for (const [key, value] of resultMap) {
result[key] = value;
2021-12-06 22:54:20 +00:00
}
2022-03-09 19:28:40 +00:00
log.info('CDSSocket.request(): done');
Timers.clearTimeout(timer);
2021-12-06 22:54:20 +00:00
return {
2022-03-09 19:28:40 +00:00
dictionary: result,
retryAfterSecs,
2021-12-06 22:54:20 +00:00
};
2021-11-08 23:32:31 +00:00
}
// EventEmitter types
public override on(
2021-11-08 23:32:31 +00:00
type: 'close',
callback: (code: number, reason?: string) => void
): this;
public override on(type: 'error', callback: (error: Error) => void): this;
2021-11-08 23:32:31 +00:00
public override on(
2021-11-08 23:32:31 +00:00
type: string | symbol,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
listener: (...args: Array<any>) => void
): this {
return super.on(type, listener);
}
public override emit(type: 'close', code: number, reason?: string): boolean;
public override emit(type: 'error', error: Error): boolean;
2021-11-08 23:32:31 +00:00
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public override emit(type: string | symbol, ...args: Array<any>): boolean {
2021-11-08 23:32:31 +00:00
return super.emit(type, ...args);
}
}
2022-03-09 19:28:40 +00:00
function decodeSingleResponse(
resultMap: Map<string, CDSSocketDictionaryEntryType>,
response: Proto.CDSClientResponse
): void {
for (
let i = 0;
i < response.e164PniAciTriples.length;
i += TRIPLE_BYTE_SIZE
) {
const tripleBytes = response.e164PniAciTriples.slice(
i,
i + TRIPLE_BYTE_SIZE
);
strictAssert(
tripleBytes.length === TRIPLE_BYTE_SIZE,
'Invalid size of CDS response triple'
);
let offset = 0;
const e164Bytes = tripleBytes.slice(offset, offset + E164_BYTE_SIZE);
offset += E164_BYTE_SIZE;
const pniBytes = tripleBytes.slice(offset, offset + UUID_BYTE_SIZE);
offset += UUID_BYTE_SIZE;
const aciBytes = tripleBytes.slice(offset, offset + UUID_BYTE_SIZE);
offset += UUID_BYTE_SIZE;
const e164Long = Long.fromBytesBE(Array.from(e164Bytes));
if (e164Long.isZero()) {
continue;
}
const e164 = `+${e164Long.toString()}`;
const pni = bytesToUuid(pniBytes);
const aci = bytesToUuid(aciBytes);
resultMap.set(e164, { pni, aci });
}
}