forked from neustar/node-mbed-dtls
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
402 lines (359 loc) · 12.3 KB
/
server.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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
'use strict';
const dgram = require('dgram');
const fs = require('fs');
const EventEmitter = require('events').EventEmitter;
const DtlsSocket = require('./socket');
const mbed = require('bindings')('node_mbed_dtls.node');
const ALERT_CONTENT_TYPE = 21;
const APPLICATION_DATA_CONTENT_TYPE = 23;
const IP_CHANGE_CONTENT_TYPE = 254;
const DUMB_PING_CONTENT_TYPE = 112;
class DtlsServer extends EventEmitter {
constructor(options) {
super();
this.options = options = Object.assign({
sendClose: true
}, options);
this.sockets = {};
this.dgramSocket = dgram.createSocket('udp4');
this._onMessage = this._onMessage.bind(this);
this.listening = false;
this.dgramSocket.on('message', this._onMessage);
this.dgramSocket.once('listening', () => {
this.listening = true;
this.emit('listening');
});
this.dgramSocket.once('error', err => {
this.emit('error', err);
this._closeSocket();
});
this.dgramSocket.once('close', () => {
this._socketClosed();
});
let key = Buffer.isBuffer(options.key) ? options.key : fs.readFileSync(options.key);
// likely a PEM encoded key, add null terminating byte
// 0x2d = '-'
if (key[0] === 0x2d && key[key.length - 1] !== 0) {
key = Buffer.concat([key, Buffer.from([0])]);
}
if (
options.identityPskCallback
&& typeof options.identityPskCallback !== 'function'
) {
throw new Error('identityPskCallback must be a callback, function(id): string');
}
this.mbedServer = new mbed.DtlsServer(
key,
options.identityPskCallback,
options.debug ?? 0
);
if (options.handshakeTimeoutMin) {
this.mbedServer.handshakeTimeoutMin = options.handshakeTimeoutMin;
}
if (options.handshakeTimeoutMax) {
this.mbedServer.handshakeTimeoutMax = options.handshakeTimeoutMax;
}
this.on('forceDeviceRehandshake', (rinfo, deviceId) => {
this._forceDeviceRehandshake(rinfo, deviceId);
})
}
listen(port, hostname, callback) {
this.dgramSocket.bind(port, hostname, callback);
}
close(callback) {
if (callback) {
this.once('close', callback);
}
this._closing = true;
this._closeSocket();
}
address() {
return this.dgramSocket.address();
}
getConnections(callback) {
const numConnections = Object.keys(this.sockets).filter(skey => {
return this.sockets[skey] && this.sockets[skey].connected;
}).length;
process.nextTick(() => callback(numConnections));
}
resumeSocket(rinfo, session) {
const key = `${rinfo.address}:${rinfo.port}`;
let client = this.sockets[key];
if (client) {
return false;
}
this.sockets[key] = client = this._createSocket(rinfo, true);
if (client.resumeSession(session)) {
this.emit('secureConnection', client, session);
return true;
}
return false;
}
_debug() {
if (this.options.debug) {
console.log(...arguments);
}
}
_handleIpChange(msg, key, rinfo, deviceId) {
const lookedUp = this.emit('lookupKey', deviceId, (err, oldRinfo) => {
if (!err && oldRinfo) {
if (rinfo.address === oldRinfo.address && rinfo.port === oldRinfo.port) {
// The IP and port have not changed.
// The device just thought they might have.
// The extra DTLS option has been stripped already,
// handle the message as normal using the client we already had.
this._debug(`handleIpChange: ignoring ip change because address did not change ip=${key}, deviceID=${deviceId}`);
this._onMessage(msg, rinfo, (client, received) => {
// 'received' is true or false based on whether the message is pushed into the stream
if (!received) {
this.emit('forceDeviceRehandshake', rinfo, deviceId);
}
});
return;
}
// The IP and/or port have changed
// Attempt to send to oldRinfo which will
// a) attempt session resumption (if the client with old address and port doesnt exist yet)
// b) attempt to send the message to the old address and port
this._onMessage(msg, oldRinfo, (client, received) =>
new Promise((resolve, reject) => {
const oldKey = `${oldRinfo.address}:${oldRinfo.port}`;
// if the message went through OK
if (received) {
this._debug(`handleIpChange: message successfully received, changing ip address fromip=${oldKey}, toip=${key}, deviceID=${deviceId}`);
// change IP
client.remoteAddress = rinfo.address;
client.remotePort = rinfo.port;
// move in lookup table
this.sockets[key] = client;
if (this.sockets[oldKey]) {
delete this.sockets[oldKey];
}
client.emit('ipChanged', oldRinfo, () => {
resolve(true);
}, err => {
if (err) {
this.emit('forceDeviceRehandshake', rinfo, deviceId);
reject(err);
}
reject();
});
} else {
this._debug(`handleIpChange: message not successfully received, NOT changing ip address fromip=${oldKey}, toip=${key}, deviceID=${deviceId}`);
this.emit('forceDeviceRehandshake', rinfo, deviceId);
}}
)
);
} else {
// In May 2019 some devices were stuck with bad sessions, never handshaking.
// https://app.clubhouse.io/particle/milestone/32301/manage-next-steps-associated-with-device-connectivity-issues-starting-may-2nd-2019
// This cloud-side solution was discovered by Eli Thomas which caused
// mbedTLS to fail a socket read and initiate a handshake.
this._debug(`Device in 'move session' lock state attempting to force it to re-handshake deviceID=${deviceId}`, key);
//Always EMIT this event instead of calling _forceDeviceRehandshake internally this allows the DS to device wether to send the packet or not to the device
this.emit('forceDeviceRehandshake', rinfo, deviceId);
}
});
return lookedUp;
}
_forceDeviceRehandshake(rinfo, deviceId){
this._debug(`Attempting force re-handshake by sending malformed hello request packet to ${deviceId} socket ${rinfo.port} ${rinfo.address}`);
// Construct the 'session killing' Avada Kedavra packet
const malformedHelloRequest = Buffer.from([
0x16, // Handshake message type 22
0xfe, 0xfd, // DTLS 1.2
0x00, 0x01, // Epoch
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Sequence number, works when set to anything, therefore chose 0x00
0x00, 0x10, // Data length, this has to be >= 16 (minumum) (deliberatly set to 0x10 (16) which is > the data length (2) that follows to force an mbed error on the device
0x00, // HandshakeType hello_request
0x00 // Handshake body, intentionally too short at a single byte
]);
// Sending the malformed hello request back over the raw UDP socket
this.dgramSocket.send(malformedHelloRequest, rinfo.port, rinfo.address);
}
/**
* This function attempts to resume a session for a client.
* If the session cannot be resumed, it ends the client and removes it from the sockets list.
* @param {Object} client - The client to attempt to resume the session for.
* @param {Buffer} msg - The message received from the client.
* @param {string} key - The key of the client in the sockets list.
* @param {Function} cb - A callback function to be called after attempting to resume the session.
*/
_attemptResume(client, msg, key, cb) {
const lcb = cb || (() => {});
this._debug('_attemptResume', key, lcb);
const called = this.emit('resumeSession', key, client, async (session) => {
this._debug('resumeSession (callback)', session, cb);
if (session) {
const resumed = client.resumeSession(session);
if (resumed) {
client.cork();
let received;
if (msg.length === 1 && msg[0] === DUMB_PING_CONTENT_TYPE) {
received = true;
} else {
received = client.receive(msg);
}
// callback before secureConnection so
// IP can be changed
if (cb) {
try {
await lcb(client, received);
} catch(err) {
this.emit('forceDeviceRehandshake', { address: client.remoteAddress, port: client.remotePort });
}
}
if (received) {
this.emit('secureConnection', client, session);
}
client.uncork();
return;
}
}
// client.receive(msg); // removed because it generates
// clientError: SSL - Processing of the ClientHello handshake message failed
// Socket error: -30976 sessionKey=127.0.0.1=61109
if (this.sockets[key]) {
this.sockets[key].end();
delete this.sockets[key];
}
if (cb) {
lcb(null, false);
} else {
this.emit('forceDeviceRehandshake', { address: client.remoteAddress, port: client.remotePort });
}
});
// if somebody was listening, session will attempt to be resumed
// do not process with receive until resume finishes
return called;
}
_onMessage(msg, rinfo, cb) {
const key = `${rinfo.address}:${rinfo.port}`;
this._debug('_onMessage', key, msg);
// special IP changed content type
if (msg.length > 0 && msg[0] === IP_CHANGE_CONTENT_TYPE) {
this._debug("IP_CHANGE_CONTENT_TYPE");
const idLen = msg[msg.length - 1];
const idStartIndex = msg.length - idLen - 1;
const deviceId = msg.slice(idStartIndex, idStartIndex + idLen).toString('hex').toLowerCase();
// handle special case of ip change (with tinydtls trackle lib 2.0)
if (msg[1] === DUMB_PING_CONTENT_TYPE) {
this._debug("type DUMB_PING_CONTENT_TYPE");
// return content type to DumbPing
msg = [DUMB_PING_CONTENT_TYPE];
} else {
this._debug("type APPLICATION_DATA_CONTENT_TYPE");
// slice off id and length, return content type to ApplicationData
msg = msg.slice(0, idStartIndex);
msg[0] = APPLICATION_DATA_CONTENT_TYPE;
}
this._debug(`received ip change ip=${key}, deviceID=${deviceId}`);
if (this._handleIpChange(msg, key, rinfo, deviceId)) {
return;
}
}
let client = this.sockets[key];
if (!client) {
this._debug("Unknown client, creating new one", key);
this.sockets[key] = client = this._createSocket(rinfo);
if ((msg.length > 0 && msg[0] === APPLICATION_DATA_CONTENT_TYPE) || (msg.length === 1 && msg[0] === DUMB_PING_CONTENT_TYPE)) {
if (this._attemptResume(client, msg, key, cb)) {
return;
}
}
}
if (msg.length > 0 && msg[0] === ALERT_CONTENT_TYPE) {
this._debug("ALERT_CONTENT_TYPE", key);
if(client) {
client.end();
delete this.sockets[key];
}
}
if (msg.length === 1 && msg[0] === DUMB_PING_CONTENT_TYPE) {
this._debug("DUMB_PING_CONTENT_TYPE");
client.emit("dumbPing");
if (cb) {
cb(client, true);
}
return;
}
if (cb) {
this._debug("Processing new message with a callback...". msg, cb);
// we cork because we want the callback to happen
// before the implications of the message do
client.cork();
const received = client.receive(msg);
cb(client, received);
client.uncork();
} else {
client.receive(msg);
}
}
_createSocket(rinfo) {
this._debug("_createSocket", rinfo);
const client = new DtlsSocket(this, rinfo.address, rinfo.port);
client.sendClose = this.options.sendClose;
this._attachToSocket(client);
return client;
}
_attachToSocket(client) {
const key = `${client.remoteAddress}:${client.remotePort}`
client.once('error', (code, err) => {
delete this.sockets[key];
if (!client.connected) {
this.emit('clientError', err, client);
}
});
client.once('close', () => {
this.emit('endSession', key);
delete this.sockets[key];
client = null;
if (this._closing && Object.keys(this.sockets).length === 0) {
this._closeSocket();
}
});
client.once('reconnect', socket => {
// treat like a brand-new connection
socket.reset();
this._attachToSocket(socket);
this.sockets[key] = socket;
});
client.once('secureConnect', () => {
this.emit('newSession', key, client.session);
this.emit('secureConnection', client);
});
this.emit('connection', client);
}
_endSockets() {
if (this.dgramSocket) {
this.dgramSocket.removeListener('message', this._onMessage);
}
this.dgramSocket = null;
const sockets = Object.keys(this.sockets);
sockets.forEach(skey => {
const s = this.sockets[skey];
if (s) {
s.end();
}
});
this.sockets = {};
}
_socketClosed() {
this.listening = false;
this._endSockets();
this.emit('close');
this.removeAllListeners();
}
_closeSocket() {
if (!this.listening) {
process.nextTick(() => {
this._socketClosed();
});
return;
}
if (this.dgramSocket) {
this.dgramSocket.close();
}
}
}
module.exports = DtlsServer;