-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtls.js
233 lines (197 loc) · 5.87 KB
/
tls.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
/**
* Simulate node's TLS wrapper using Forge
* borrowed from https://github.com/hiddentao/browsermail
* https://github.com/hiddentao/browsermail/blob/master/src/js/node-polyfills/tls.js
* and ported to nodejs api v0.11
*/
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var crypto = require('./crypto');
function noop() {}
var CLIENT_TO_SERVER = 1;
var SERVER_TO_CLIENT = 2;
var debug = util.debuglog ? (function () {
var log = util.debuglog('tls');
return function (msg, direction, contentType) {
switch (direction) {
case CLIENT_TO_SERVER:
direction = '{c -> S}: ';
break;
case SERVER_TO_CLIENT:
direction = '{S -> c}: ';
break;
default:
direction = '';
}
msg = ('enc' !== contentType ? msg : '(enc) ' + crypto.forge.util.bytesToHex(msg));
log(direction + msg);
}
})() : noop;
function TLSSocket(socket, options) {
if (!options) {options = socket;socket = null}
var self = this;
this._socket = socket || options.socket;
// To prevent assertion in afterConnect()
if (this._socket)
this._connecting = this._socket._connecting;
this.id = this._socket._handle.socketId;
this._tlsOptions = options;
this.authorizationError = null;
this.authorized = false;
this.writable = false;
var ctx = (options.credentials || crypto.createCredentials()).context;
// create TLS connection
this.ssl = crypto.forge.tls.createConnection({
server: typeof options.isServer === 'undefined' ? false : options.isServer,
verifyClient: options.requestCert ? options.rejectUnauthorized ? true : 'optional' : false,
error: onError.bind(this),
closed: onClosed.bind(this),
connected: onConnected.bind(this),
dataReady: onDataReady.bind(this),
tlsDataReady: onTlsDataReady.bind(this),
// getCertificate: ctx.getCert.bind(ctx), // FIXME
// getPrivateKey: ctx.getKey.bind(ctx), // FIXME
// getSignature: ctx.sign.bind(ctx), // FIXME
deflate: ctx.deflate && ctx.deflate.bind(ctx),
inflate: ctx.inflate && ctx.inflate.bind(ctx),
sessionCache: ctx.session.cache,
cipherSuites: ctx.cipherSuites,
virtualHost: ctx.virtualHost,
sessionId: ctx.session.id,
caStore: ctx.caStore || [],
verify: ctx.verify && ctx.verify.bind(ctx) ||
function(conn, verified, depth, certs) {
return true; // FIXME
},
});
this._socket.on('close', function(had_err) {
if(self.ssl.open && self.ssl.handshaking) {
self.emit('error', new Error('Connection closed during handshake.'));
}
self.ssl.close();
// call socket handler
self.emit('close', had_err);
});
// handle error on socket
this._socket.on('error', function(e) {
debug('Socket error: ' + (e.message || e));
// error
self.emit('error', e);
});
// handle receiving raw TLS data from socket
this._socket.on('data', function(data) {
var bytes = data.toString('binary');
debug(bytes, SERVER_TO_CLIENT, 'enc');
self.ssl.process(bytes);
});
if (!this._socket)
// handle doing handshake after connecting
this._socket.once('connect', this._init.bind(this, ctx));
else
this._init(ctx);
};
util.inherits(TLSSocket, EventEmitter);
exports.TLSSocket = TLSSocket;
TLSSocket.prototype._init = function(ctx) {
debug('Socket connected. Handshaking...');
this.ssl.handshake(ctx.session.id);
};
/**
* Determines if the socket is connected or not.
*
* @return true if connected, false if not.
*/
TLSSocket.prototype.isConnected = function() {
return this.ssl.isConnected;
};
/**
* Destroys this socket.
*/
TLSSocket.prototype.destroy = function() {
var socket = this._socket;
this._socket = null;
if (socket) socket.destroy();
};
/**
* Connects this socket.
*/
TLSSocket.prototype.connect = function(port, host) {
debug('Connecting to ' + host + ':' + port);
this._socket.connect(port, host);
};
/**
* Closes this socket.
*/
TLSSocket.prototype.close = function() {
debug('Closing connection');
this.ssl.close();
};
/**
* Close this socket.
* @type {Function}
*/
TLSSocket.prototype.end = TLSSocket.prototype.close;
/**
* Writes bytes to this socket.
*
* @param bytes the bytes (as a string) to write.
*
* @return true on success, false on failure.
*/
TLSSocket.prototype.write = function(bytes) {
debug(bytes, CLIENT_TO_SERVER);
return this.ssl.prepare(bytes);
};
TLSSocket.prototype.getCipher = function(bytes) {
debug(bytes, CLIENT_TO_SERVER, 'cipher');
return this.ssl.prepare(bytes);
};
TLSSocket.prototype._start = noop;
TLSSocket.prototype._releaseControl = noop;
TLSSocket.prototype.setSession = noop;
TLSSocket.prototype.setServername = noop;
function onConnected(conn) {
debug('Handshake successful');
// first handshake complete, call handler
if(conn.handshakes === 1) {
this.writable = true;
this.authorized = true;
this.emit('secureConnect');
}
}
function onTlsDataReady(conn) {
var bytes = conn.tlsData.getBytes();
debug(bytes, CLIENT_TO_SERVER, 'enc');
// send TLS data over socket
this._socket.write(bytes, 'binary', function(err) {
if (err) {
this.emit('error', err);
}
}.bind(this));
}
function onDataReady(conn) {
var received = conn.data.getBytes();
debug(received, SERVER_TO_CLIENT, 'plain');
// indicate application data is ready
this.emit('data', new Buffer(received, 'binary'));
}
function onClosed() {
debug('closed');
this.writable = false;
this.authorized = false;
this.destroy();
}
function onError(conn, e) {
debug('Error: ' + e.message || e);
// send error, close socket
this.authorizationError = e; // FIXME probably not right
this.emit('error', e);
this._socket.end();
}
exports.connect = function(options, onconnect) {
var socket = new TLSSocket(options);
if (onconnect) {
socket.on('secureConnect', onconnect);
}
return socket;
};