forked from neustar/node-mbed-dtls
-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.js
289 lines (239 loc) · 6.1 KB
/
socket.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
'use strict';
const stream = require('stream');
var mbed = require('bindings')('node_mbed_dtls.node');
const HANDSHAKE_TIMEOUT_MAX = 60000; // ms
const MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY = -0x7880;
const MBEDTLS_ERR_SSL_CLIENT_RECONNECT = -0x6780;
class DtlsSocket extends stream.Duplex {
constructor(server, address, port) {
super({ allowHalfOpen: false });
this.server = server;
this.dgramSocket = server.dgramSocket;
this.remoteAddress = address;
this.remotePort = port;
this._hadError = false;
this._sendClose = true;
const key = `${address}:${port}`;
this._handshakeLoop;
this._handshakeLoopTimeout = new Date().getTime();
try {
this.mbedSocket = new mbed.DtlsSocket(server.mbedServer, key,
this._sendEncrypted.bind(this),
this._handshakeComplete.bind(this),
this._error.bind(this),
this._renegotiate.bind(this));
// handshake control loop: it calls the mbedtls receiveData like a loop in order to:
// 1) increase dtls timeout counters for packet retransmission
// 2) close socket after handshake max timeout if something goes wrong
this._handshakeLoop = setImmediate(() => {
this.mbedSocket.receiveData("");
if (new Date().getTime() - this._handshakeLoopTimeout >= HANDSHAKE_TIMEOUT_MAX) {
this._end();
}
});
} catch (error) {
// Don't _error() here because that method assumues we've had
// an active socket at some point which is not the case here.
this.emit('error', 0, error.message);
if(this._handshakeLoop) {
clearImmediate(this._handshakeLoop);
}
}
}
get publicKey() {
return (this.mbedSocket && this.mbedSocket.publicKey) || Buffer.alloc(0);
}
get publicKeyPEM() {
return (this.mbedSocket && this.mbedSocket.publicKeyPEM) || Buffer.alloc(0);
}
get outCounter() {
return this.mbedSocket && this.mbedSocket.outCounter;
}
get session() {
return this.mbedSocket && this.mbedSocket.session;
}
get sendClose() {
return this._sendClose;
}
set sendClose(value) {
this._sendClose = value;
}
resumeSession(session) {
if (!session || !this.mbedSocket) {
return false;
}
const s = new mbed.SessionWrap();
s.restore(session);
const success = this.mbedSocket.resumeSession(s);
if (success) {
this.connected = true;
this.resumed = true;
}
if (this._handshakeLoop) {
clearImmediate(this._handshakeLoop);
}
return success;
}
_read() {
// @TODO implement way to stop/start reading?
// do nothing since chunk pushing is async
}
_write(chunk, encoding, callback) {
if (!this.mbedSocket) {
return callback(new Error('no mbed socket'));
}
this._sendCallback = callback;
try {
this.mbedSocket.send(chunk);
} catch (error) {
return callback(error);
}
}
_sendEncrypted(msg) {
// store the callback here because '_write' might be called
// again before the underlying socket finishes sending
const sendCb = this._sendCallback;
this._sendCallback = null;
const sendFinished = (err) => {
if (sendCb) {
sendCb(err);
}
if (this._clientEnd) {
this._finishEnd();
}
};
// make absolutely sure the socket will let us send
if (!this.dgramSocket) {
process.nextTick(() => {
sendFinished(new Error('no underlying socket'));
});
return;
}
this.emit('send', msg.length);
this.dgramSocket.send(msg, 0, msg.length, this.remotePort, this.remoteAddress, sendFinished);
}
_handshakeComplete() {
this.connected = true;
this.emit('secureConnect');
if (this._handshakeLoop) {
clearImmediate(this._handshakeLoop);
}
}
_error(code, msg) {
if (code === MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
this._end();
return;
}
if (code === MBEDTLS_ERR_SSL_CLIENT_RECONNECT) {
this.emit('reconnect', this);
process.nextTick(() => {
this.receive();
});
return;
}
this._hadError = true;
if (this._sendCallback) {
this._sendCallback(code);
this._sendCallback = null;
} else {
this.emit('error', code, msg);
}
this._end();
}
_renegotiate(sessionId) {
const done = this._renegotiateCallback.bind(this);
if (!this.server.emit('renegotiate', sessionId.toString('hex'), this, done)) {
process.nextTick(done);
}
}
_renegotiateCallback(err, data) {
let s;
if (!err && data) {
s = new mbed.SessionWrap();
err = s.restore(data);
}
if (err) {
this._end();
return;
}
this.mbedSocket.renegotiate(s || undefined);
this.resumed = true;
if (this._handshakeLoop) {
clearImmediate(this._handshakeLoop);
}
}
receive(msg) {
if (!this.mbedSocket) {
return false;
}
if (msg && msg.length < 4) {
return false;
}
this.emit('receive', (msg && msg.length) || 0);
let data;
try {
// We keep getting an 'unknown error' thrown from this call,
// but we cannot figure out where in the native code it is
// coming from.
data = this.mbedSocket.receiveData(msg);
} catch (error) {
// based on DTLS debug logs, this error is what mbed-tls should be giving us
// @TODO find a way to get this message from mbed-tls
this.server.emit('clientError', 'SSL - Verification of the message MAC failed', this);
this._hadError = true;
this._end();
}
if (data) {
this.push(data);
return true;
}
return false;
}
end() {
if (this._resetting) {
return;
}
this._clientEnd = true;
this._end();
}
reset() {
this._resetting = true;
this.emit('close', false);
this.removeAllListeners();
this._resetting = false;
this.resumed = false;
this.connected = false;
if (this._handshakeLoop) {
clearImmediate(this._handshakeLoop);
}
}
_end() {
if (this._ending) {
return;
}
this._ending = true;
super.end();
this.push(null);
let noSend = true;
try {
noSend = !this._sendClose || (this.connected && this.mbedSocket.close());
} catch (error) {
this.emit('error', 0, error.message);
}
this.emit('closing');
this.mbedSocket = null;
if (this._handshakeLoop) {
clearImmediate(this._handshakeLoop);
}
if (noSend || !this._clientEnd) {
this._finishEnd();
}
}
_finishEnd() {
this.dgramSocket = null;
this.server = null;
this.emit('close', this._hadError);
this.removeAllListeners();
}
}
module.exports = DtlsSocket;