/
PairSetup.js
337 lines (268 loc) · 9.68 KB
/
PairSetup.js
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
"use strict";
const crypto = require('crypto');
const srp = require('fast-srp-hap');
const hkdf = require('../crypto/hkdf').HKDF;
const encryption = require('../crypto/encryption');
const ed25519 = require('ed25519');
const uuid = require('uuid/v4');
const OpCodes = require('./../OpCodes');
const TLV8Decoder = require('./../Tlv8Decoder');
const TLV8Encoder = require('./../Tlv8Encoder');
const TlvKeys = require('./../TlvKeys');
const TLVType = require('./TLVType');
/**
*
* Pairing commands are encapsulated in regular characteristic writes, within
* the HAP-Param-Value type and must also include an additional
* HAP-Param-Return-Response key with a 1.
*
* Responses are similarly TLV packed in a HAP-Param-Value TLV.
*
*/
class PairSetup {
constructor(log, attributeDatabase, pin) {
this.log = log;
this._state = 0;
this._acknowledgeFragment = false;
this._address = {
service: '000000550000100080000026bb765291',
characteristic: '0000004c0000100080000026bb765291'
};
this._cid = attributeDatabase.getCharacteristic(this._address).cid;
this._encryptionKey;
this._error = undefined;
this._key = crypto.randomBytes(32);
this._params = srp.params["3072"];
this._pin = pin;
this._srp;
this._rangerPairingID;
this._rangerPublicKey;
this._rangerProof;
this._rangerLTPK;
this._rangerLTSK;
this._reassemblyBuffer = Buffer.alloc(0);
this._srpSharedSecret;
}
hasMoreRequests() {
return this._error === undefined
&& (this._state < 6 || this._acknowledgeFragment);
}
getRequest() {
if (this._acknowledgeFragment) {
this.log('Acknowledging received fragment.');
this._acknowledgeFragment = false;
return this.acknowledgeFragment();
}
this._state++;
this.log(`Returning pairing request for M${this._state}`);
switch (this._state) {
case 1:
return this.getM1Request();
case 3:
return this.getM3Request();
case 5:
return this.getM5Request();
}
}
getM1Request() {
const tlv = {};
tlv[TLVType.State] = Buffer.from([this._state]);
tlv[TLVType.Method] = Buffer.from([1]);
const payload = {};
payload[TlvKeys.Value] = TLV8Encoder.encode(tlv);
payload[TlvKeys.ReturnResponse] = new Buffer([1]);
return {
address: this._address,
opcode: OpCodes.CharacteristicWrite,
cid: this._cid,
payload: payload,
insecure: true
};
}
getM3Request() {
const identity = Buffer.from('Pair-Setup');
const password = Buffer.from(this._pin); // Accessory pin
this._srp = new srp.Client(this._params, this._salt, identity, password, this._key);
this._srp.setB(this._accessoryPublicKey);
this._rangerPublicKey = this._srp.computeA();
this._rangerProof = this._srp.computeM1();
const tlv = {};
tlv[TLVType.State] = Buffer.from([this._state]);
tlv[TLVType.PublicKey] = this._rangerPublicKey;
tlv[TLVType.Proof] = this._rangerProof;
const payload = {};
payload[TlvKeys.Value] = TLV8Encoder.encode(tlv);
payload[TlvKeys.ReturnResponse] = new Buffer([1]);
return {
address: this._address,
opcode: OpCodes.CharacteristicWrite,
cid: this._cid,
payload: payload,
insecure: true
};
}
getM5Request() {
const seed = crypto.randomBytes(32);
const keyPair = ed25519.MakeKeypair(seed);
this._rangerPairingID = Buffer.from(uuid());
this._rangerLTSK = keyPair.privateKey;
this._rangerLTPK = keyPair.publicKey;
this._srpSharedSecret = this._srp.computeK();
const controllerSalt = Buffer.from("Pair-Setup-Controller-Sign-Salt");
const controllerInfo = Buffer.from("Pair-Setup-Controller-Sign-Info");
const iOSDeviceX = hkdf("sha512", controllerSalt, this._srpSharedSecret, controllerInfo, 32);
const iOSDeviceInfo = Buffer.concat([iOSDeviceX, this._rangerPairingID, this._rangerLTPK]);
const iOSDeviceSignature = ed25519.Sign(iOSDeviceInfo, this._rangerLTSK);
let subtlv = {};
subtlv[TLVType.Identifier] = this._rangerPairingID;
subtlv[TLVType.PublicKey] = this._rangerLTPK;
subtlv[TLVType.Signature] = iOSDeviceSignature;
subtlv = TLV8Encoder.encode(subtlv);
var ciphertextBuffer = Buffer.alloc(subtlv.length);
var macBuffer = Buffer.alloc(16);
var encSalt = Buffer.from("Pair-Setup-Encrypt-Salt");
var encInfo = Buffer.from("Pair-Setup-Encrypt-Info");
this._encryptionKey = hkdf("sha512", encSalt, this._srpSharedSecret, encInfo, 32);
encryption.encryptAndSeal(this._encryptionKey, Buffer.from("PS-Msg05"), subtlv, null, ciphertextBuffer, macBuffer);
const tlv = {};
tlv[TLVType.State] = Buffer.from([this._state]);
tlv[TLVType.EncryptedData] = Buffer.concat([ciphertextBuffer, macBuffer]);
let value = TLV8Encoder.encode(tlv);
// if (this._usesFragments) {
// this.log(`Packing HAP-Value in FragmentData`);
// const fragmentBuffer = {};
// fragmentBuffer[TLVType.FragmentData] = value;
// value = TLV8Encoder.encode(fragmentBuffer);
// }
const payload = {};
payload[TlvKeys.Value] = value;
payload[TlvKeys.ReturnResponse] = new Buffer([1]);
return {
address: this._address,
opcode: OpCodes.CharacteristicWrite,
cid: this._cid,
payload: payload,
insecure: true
};
}
acknowledgeFragment() {
this.log(`Sending acknowledgement fragment. More data needed in response.`);
const tlv = {};
tlv[TLVType.FragmentData] = Buffer.alloc(0); // Empty buffer signals ACK
let value = TLV8Encoder.encode(tlv);
const payload = {};
payload[TlvKeys.Value] = value;
payload[TlvKeys.ReturnResponse] = new Buffer([1]);
return {
address: this._address,
opcode: OpCodes.CharacteristicWrite,
cid: this._cid,
payload: payload,
insecure: true
};
}
handleResponse(response) {
const error = response[TLVType.Error];
if (error) {
this.log(error);
this._error = error;
return;
}
this._acknowledgeFragment = false;
const decodedResponse = this._decodeResponse(response);
if (decodedResponse.moreDataNeeded) {
this.log(`Device sent fragment. More data needed in response.`);
this._acknowledgeFragment = true;
return;
}
this._state++;
this.log(`Received pairing response for M${this._state}`);
switch (this._state) {
case 2:
return this.handleM2Response(decodedResponse.value);
case 4:
return this.handleM4Response(decodedResponse.value);
case 6:
return this.handleM6Response(decodedResponse.value);
}
}
_decodeResponse(response) {
const valueAsTlv = response[TlvKeys.Value];
let value = TLV8Decoder.decode(valueAsTlv);
const fragmentData = value[TLVType.FragmentData];
if (fragmentData) {
this.log(`Device is using fragment buffers for pairing.`);
this._acknowledgeFragment = true;
this._reassemblyBuffer = Buffer.concat([this._reassemblyBuffer, fragmentData]);
return {
moreDataNeeded: true
};
}
const fragmentLast = value[TLVType.FragmentLast];
if (fragmentLast) {
const reassembledData = Buffer.concat([this._reassemblyBuffer, fragmentLast]);
value = TLV8Decoder.decode(reassembledData);
this._reassemblyBuffer = Buffer.alloc(0);
}
return {
value: value
};
}
handleM2Response(response) {
this._salt = response[TLVType.Salt];
this._accessoryPublicKey = response[TLVType.PublicKey];
if (!this._salt) {
throw new Error('Missing pairing salt.');
}
if (!this._accessoryPublicKey) {
throw new Error('Missing accessory public key.');
}
}
handleM4Response(response) {
const accessoryProof = response[TLVType.Proof];
try {
this._srp.checkM2(accessoryProof);
}
catch (err) {
this.log(`Error while checking accessory proof: ${accessoryProof}`, err);
this._error = err;
}
}
handleM6Response(response) {
const encryptedData = response[TLVType.EncryptedData];
var messageData = Buffer.alloc(encryptedData.length - 16);
var authTagData = Buffer.alloc(16);
encryptedData.copy(messageData, 0, 0, encryptedData.length - 16);
encryptedData.copy(authTagData, 0, encryptedData.length - 16, encryptedData.length);
var plaintextBuffer = Buffer.alloc(messageData.length);
encryption.verifyAndDecrypt(this._encryptionKey, Buffer.from("PS-Msg06"), messageData, authTagData, null, plaintextBuffer);
const accessoryInfo = TLV8Decoder.decode(plaintextBuffer);
const accessoryPairingID = accessoryInfo[TLVType.Identifier];
const accessoryLTPK = accessoryInfo[TLVType.PublicKey];
const accessorySignature = accessoryInfo[TLVType.Signature];
var accessorySignSalt = Buffer.from("Pair-Setup-Accessory-Sign-Salt");
var accessorySignInfo = Buffer.from("Pair-Setup-Accessory-Sign-Info");
var outputKey = hkdf("sha512", accessorySignSalt, this._srpSharedSecret, accessorySignInfo, 32);
var material = Buffer.concat([outputKey, accessoryPairingID, accessoryLTPK]);
if (!ed25519.Verify(material, accessorySignature, accessoryLTPK)) {
this.log('Invalid accessory signature');
return;
}
this._result = {
rangerPairingID: this._rangerPairingID.toString(),
rangerLTSK: this._rangerLTSK.toString('hex'),
rangerLTPK: this._rangerLTPK.toString('hex'),
accessoryPairingID: accessoryPairingID.toString(),
accessoryLTPK: accessoryLTPK.toString('hex'),
};
this.log(`Pairing result:\n${JSON.stringify(this._result)}`);
}
getResult() {
if (this._error) {
this.log(`Pairing resulted in error ${this._error}.`);
throw this._error;
}
return this._result;
}
};
module.exports = PairSetup;