-
Notifications
You must be signed in to change notification settings - Fork 2
/
envelopedData.ts
290 lines (257 loc) · 10.3 KB
/
envelopedData.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
// tslint:disable:no-object-mutation max-classes-per-file
import * as asn1js from 'asn1js';
import bufferToArray from 'buffer-to-arraybuffer';
import * as pkijs from 'pkijs';
import { CMS_OIDS, RELAYNET_OIDS } from '../../oids';
import { SessionKey } from '../../SessionKey';
import { generateRandom64BitValue } from '../_utils';
import { Certificate } from '../x509/Certificate';
import { assertPkiType, assertUndefined, deserializeContentInfo } from './_utils';
import { CMSError } from './CMSError';
import { derDeserializeECDHPublicKey, derSerializePrivateKey } from '../keys/serialisation';
import { NODE_ENGINE } from '../pkijs';
// CBC mode is temporary. See: https://github.com/relaycorp/relayverse/issues/16
const AES_CIPHER_MODE = 'AES-CBC';
const AES_KEY_SIZES: ReadonlyArray<number> = [128, 192, 256];
export interface EncryptionOptions {
/** The AES key size (128, 192 or 256) */
readonly aesKeySize: number;
}
/**
* Result of producing an EnvelopedData value with the Channel Session Protocol.
*/
export interface SessionEncryptionResult {
/** Id of ECDH key pair. */
readonly dhKeyId: ArrayBuffer;
/** Private key of the ECDH key pair */
readonly dhPrivateKey: CryptoKey;
/** EnvelopedData value using the Channel Session Protocol. */
readonly envelopedData: SessionEnvelopedData;
}
export abstract class EnvelopedData {
/**
* Deserialize an EnvelopedData value into a `SessionlessEnvelopedData` or `SessionEnvelopedData`
* instance.
*
* Depending on the type of RecipientInfo.
*
* @param envelopedDataSerialized
*/
public static deserialize(envelopedDataSerialized: ArrayBuffer): EnvelopedData {
const contentInfo = deserializeContentInfo(envelopedDataSerialized);
if (contentInfo.contentType !== CMS_OIDS.ENVELOPED_DATA) {
throw new CMSError(
`ContentInfo does not wrap an EnvelopedData value (got OID ${contentInfo.contentType})`,
);
}
let pkijsEnvelopedData;
try {
pkijsEnvelopedData = new pkijs.EnvelopedData({ schema: contentInfo.content });
} catch (error) {
throw new CMSError(error as Error, 'Invalid EnvelopedData value');
}
const recipientInfosLength = pkijsEnvelopedData.recipientInfos.length;
if (recipientInfosLength !== 1) {
throw new CMSError(
`EnvelopedData must have exactly one RecipientInfo (got ${recipientInfosLength})`,
);
}
const recipientInfo = pkijsEnvelopedData.recipientInfos[0];
if (![1, 2].includes(recipientInfo.variant)) {
throw new CMSError(`Unsupported RecipientInfo (variant: ${recipientInfo.variant})`);
}
const envelopedDataClass =
recipientInfo.variant === 1 ? SessionlessEnvelopedData : SessionEnvelopedData;
return new envelopedDataClass(pkijsEnvelopedData);
}
/**
* @internal
*/
public readonly pkijsEnvelopedData: pkijs.EnvelopedData;
/**
* @internal
*/
protected constructor(pkijsEnvelopedData: pkijs.EnvelopedData) {
this.pkijsEnvelopedData = pkijsEnvelopedData;
}
/**
* Return the DER serialization of the current EnvelopedData value.
*
* It'll be wrapped around a `ContentInfo` value.
*/
public serialize(): ArrayBuffer {
const contentInfo = new pkijs.ContentInfo({
content: this.pkijsEnvelopedData.toSchema(),
contentType: CMS_OIDS.ENVELOPED_DATA,
});
return contentInfo.toSchema().toBER(false);
}
/**
* Return the plaintext for the ciphertext contained in the current EnvelopedData value.
*
* @param privateKey The private key to decrypt the ciphertext.
*/
public async decrypt(privateKey: CryptoKey): Promise<ArrayBuffer> {
const privateKeyDer = await derSerializePrivateKey(privateKey);
const params = {
recipientPrivateKey: bufferToArray(privateKeyDer),
};
try {
return await this.pkijsEnvelopedData.decrypt(0, params, NODE_ENGINE);
} catch (error) {
throw new CMSError(error as Error, 'Decryption failed');
}
}
/**
* Return the id of the recipient's key used to encrypt the content.
*
* This id will often be the recipient's certificate's serial number, in which case the issuer
* will be ignored: This method is meant to be used by the recipient so it can look up the
* corresponding private key to decrypt the content. We could certainly extract the issuer to
* verify it matches the expected one, but if the id doesn't match any key decryption
* won't even be attempted, so there's really no risk from ignoring the issuer.
*/
public abstract getRecipientKeyId(): Buffer;
}
/**
* CMS EnvelopedData representation that doesn't use the Channel Session Protocol.
*
* Consequently, it uses the key transport choice (`KeyTransRecipientInfo`) from CMS.
*/
export class SessionlessEnvelopedData extends EnvelopedData {
/**
* Return an EnvelopedData value without using the Channel Session Protocol.
*
* @param plaintext The plaintext whose ciphertext has to be embedded in the EnvelopedData value.
* @param certificate The certificate for the recipient.
* @param options Any encryption options.
*/
public static async encrypt(
plaintext: ArrayBuffer,
certificate: Certificate,
options: Partial<EncryptionOptions> = {},
): Promise<SessionlessEnvelopedData> {
const pkijsEnvelopedData = new pkijs.EnvelopedData();
pkijsEnvelopedData.addRecipientByCertificate(
certificate.pkijsCertificate,
{ oaepHashAlgorithm: 'SHA-256' },
1,
NODE_ENGINE,
);
const aesKeySize = getAesKeySize(options.aesKeySize);
await pkijsEnvelopedData.encrypt(
{ name: AES_CIPHER_MODE, length: aesKeySize } as any,
plaintext,
NODE_ENGINE,
);
return new SessionlessEnvelopedData(pkijsEnvelopedData);
}
public getRecipientKeyId(): Buffer {
const recipientInfo = this.pkijsEnvelopedData.recipientInfos[0].value;
assertPkiType(recipientInfo, pkijs.KeyTransRecipientInfo, 'recipientInfo');
assertPkiType(recipientInfo.rid, pkijs.IssuerAndSerialNumber, 'recipientInfo.rid');
const serialNumberBlock = recipientInfo.rid.serialNumber;
return Buffer.from(serialNumberBlock.valueBlock.valueHexView);
}
}
function getAesKeySize(aesKeySize: number | undefined): number {
if (aesKeySize && !AES_KEY_SIZES.includes(aesKeySize)) {
throw new CMSError(`Invalid AES key size (${aesKeySize})`);
}
return aesKeySize || 128;
}
/**
* CMS EnvelopedData representation using the Channel Session Protocol.
*
* Consequently, it uses the key agreement (`KeyAgreeRecipientInfo`) from CMS.
*/
export class SessionEnvelopedData extends EnvelopedData {
/**
* Return an EnvelopedData value using the Channel Session Protocol.
*
* @param plaintext The plaintext whose ciphertext has to be embedded in the EnvelopedData value.
* @param recipientSessionKey The ECDH public key of the recipient.
* @param options Any encryption options.
*/
public static async encrypt(
plaintext: ArrayBuffer,
recipientSessionKey: SessionKey,
options: Partial<EncryptionOptions> = {},
): Promise<SessionEncryptionResult> {
// Generate id for generated (EC)DH key and attach it to unprotectedAttrs per RS-003:
const dhKeyId = generateRandom64BitValue();
const dhKeyIdAttribute = new pkijs.Attribute({
type: RELAYNET_OIDS.ORIGINATOR_EPHEMERAL_CERT_SERIAL_NUMBER,
values: [new asn1js.OctetString({ valueHex: dhKeyId })],
});
const pkijsEnvelopedData = new pkijs.EnvelopedData({
unprotectedAttrs: [dhKeyIdAttribute],
});
pkijsEnvelopedData.addRecipientByKeyIdentifier(
recipientSessionKey.publicKey,
recipientSessionKey.keyId,
undefined,
NODE_ENGINE,
);
const aesKeySize = getAesKeySize(options.aesKeySize);
const [pkijsEncryptionResult] = await pkijsEnvelopedData.encrypt(
{ name: AES_CIPHER_MODE, length: aesKeySize } as any,
plaintext,
NODE_ENGINE,
);
assertUndefined(pkijsEncryptionResult, 'pkijsEncryptionResult');
const dhPrivateKey = pkijsEncryptionResult.ecdhPrivateKey;
const envelopedData = new SessionEnvelopedData(pkijsEnvelopedData);
return { dhPrivateKey, dhKeyId, envelopedData };
}
/**
* Return the key of the ECDH key of the originator/producer of the EnvelopedData value.
*/
public async getOriginatorKey(): Promise<SessionKey> {
const keyId = extractOriginatorKeyId(this.pkijsEnvelopedData);
const recipientInfo = this.pkijsEnvelopedData.recipientInfos[0];
if (recipientInfo.variant !== 2) {
throw new CMSError(`Expected KeyAgreeRecipientInfo (got variant: ${recipientInfo.variant})`);
}
assertPkiType(recipientInfo.value, pkijs.KeyAgreeRecipientInfo, 'recipientInfo.value');
const originator = recipientInfo.value.originator.value;
const publicKeyDer = originator.toSchema().toBER(false);
const curveOid = originator.algorithm.algorithmParams.valueBlock.toString();
// @ts-ignore
const curveParams = NODE_ENGINE.getAlgorithmByOID(curveOid);
const publicKey = await derDeserializeECDHPublicKey(
Buffer.from(publicKeyDer),
(curveParams as any).name,
);
return { keyId, publicKey };
}
public getRecipientKeyId(): Buffer {
const keyInfo = this.pkijsEnvelopedData.recipientInfos[0].value;
assertPkiType(keyInfo, pkijs.KeyAgreeRecipientInfo, 'keyInfo');
const encryptedKey = keyInfo.recipientEncryptedKeys.encryptedKeys[0];
const subjectKeyIdentifierBlock = encryptedKey.rid.value.subjectKeyIdentifier;
return Buffer.from(subjectKeyIdentifierBlock.valueBlock.valueHex);
}
}
function extractOriginatorKeyId(envelopedData: pkijs.EnvelopedData): Buffer {
const unprotectedAttrs = envelopedData.unprotectedAttrs || [];
if (unprotectedAttrs.length === 0) {
throw new CMSError('unprotectedAttrs must be present when using channel session');
}
const matchingAttrs = unprotectedAttrs.filter(
(a) => a.type === RELAYNET_OIDS.ORIGINATOR_EPHEMERAL_CERT_SERIAL_NUMBER,
);
if (matchingAttrs.length === 0) {
throw new CMSError('unprotectedAttrs does not contain originator key id');
}
const originatorKeyIdAttr = matchingAttrs[0];
// @ts-ignore
const originatorKeyIds = originatorKeyIdAttr.values;
if (originatorKeyIds.length !== 1) {
throw new CMSError(
`Originator key id attribute must have exactly one value (got ${originatorKeyIds.length})`,
);
}
const serialNumberBlock = originatorKeyIds[0];
return Buffer.from(serialNumberBlock.valueBlock.valueHex);
}