-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
248 lines (224 loc) · 6.65 KB
/
index.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
'use strict';
let http = require('http');
let https = require('https');
let tls = require('tls');
let net = require('net');
let url = require('url');
let path = require('path');
let os = require('os');
let randomBytes = require('crypto').randomBytes;
let co = require('co');
let compose = require('koa-compose');
let SSLGenerator = require('ssl-generator');
let debug = require('debug')('proxy:http');
let context = require('./lib/context');
let app = ProxyHTTP.prototype;
exports = module.exports = ProxyHTTP;
function ProxyHTTP(config) {
if (!(this instanceof ProxyHTTP)) return new ProxyHTTP(config);
this.config = config || {};
this.middleware = [];
this.context = Object.create(context);
this.sslGenerator = new SSLGenerator(config.ssl);
}
app.use = function (fn) {
this.middleware.push(fn);
return this;
};
app.listen = function(port, transparentPort) {
let self = this;
let server = http.createServer(this.callback());
server.on('connect', this.onConnect());
server.on('upgrade', this.onUpgrade());
if (transparentPort) {
self.transparentServer = net.createServer(function (socket) {
socket.on('data', function (data) {
socket.removeAllListeners('data');
let hostname = getSNI(data);
let callback = self.proxyToHttps({
httpVersion: '1.0',
connection: {
remoteAddress: socket.remoteAddress
}
}, socket, '', data);
self.sslGenerator.selfSigned(hostname, callback);
});
});
self.transparentServer.listen(transparentPort);
}
return server.listen(port);
};
app.callback = function (ip) {
let self = this;
let middleware = [respond].concat(this.middleware);
let fn = co.wrap(compose(middleware));
return function(req, res) {
debug('Received request');
req.type = (ip) ? 'https' : 'http';
req.ip = ip || req.connection.remoteAddress;
let ctx = self.createContext(req, res);
fn.call(ctx).catch(ctx.onerror);
};
};
app.onConnect = function () {
let self = this;
return function (req, socket, head) {
debug('Connect event');
let domain = req.url.split(':')[0];
debug("Retrieving SSL cert & key for ${domain}")
self.sslGenerator.selfSigned(domain, self.proxyToHttps(req, socket, head));
};
};
app.onUpgrade = function () {
return function (req, socket, head) {
let port = (req.connection.servername) ? 443 : 80;
let proto = (port == 80) ? net : tls;
let path = (req.url[0] == '/') ? req.url : url.parse(req.url).pathname;
let hostname = (req.url[0] == '/') ? req.headers.host : url.parse(req.url).hostname;
if (req.headers.upgrade === 'websocket') {
let client = proto.connect({
port: port,
hostname: hostname
}, function () {
client.write("GET ${path} HTTP/1.1\r\n");
Object.keys(req.headers).map(function (key) {
client.write("${key}: ${req.headers[key]}\r\n");
});
client.write('\r\n');
socket.on('data', function (chunk) { client.write(chunk); });
});
client.on('data', function (chunk) {
socket.write(chunk);
});
client.on('error', function (err) {
// TODO: handle error
throw err;
});
}
};
};
app.proxyToHttps = function (req, socket, head, initialData) {
let self = this;
return function createHttpsServer(err, certKey) {
debug('Create temporary HTTPS server');
if (err) {
// TODO: handle error
throw err;
}
let proxy = new net.Socket();
let version = req.httpVersion;
let server = https.createServer({
cert: certKey.cert,
key: certKey.key
});
let socketPath = path.resolve(os.tmpDir(), randomBytes(15).toString('hex'));
server.closed = false;
server.on('close', function() { server.closed = true; });
server.on('request', self.callback(req.connection.remoteAddress));
server.on('upgrade', self.onUpgrade());
server.once('request', function (req, res) {
debug('Proxy to HTTPS `request` event')
res.on('finish', function () {
if (!server.closed) {
server.close();
}
});
});
server.listen(socketPath, function () {
debug("temporary https server listening at ${socketPath}")
});
proxy.connect(server._pipeName, function () {
if (initialData !== undefined) {
proxy.write(initialData);
} else {
proxy.write(head);
socket.write("HTTP/${version} 200 Connection established\r\n\r\n");
}
});
// TODO: check if pipe works instead
// proxy.pipe(socket);
proxy.on('data', socket.write.bind(socket));
proxy.on('end', function () {
if (!server.closed) {
server.close();
}
socket.end();
});
proxy.on('error', function () {
// TODO: properly handle error
if (!server.closed) {
server.close();
}
socket.end();
});
socket.on('data', function (chunk) {
if (!proxy.destroyed) {
proxy.write(chunk);
}
});
socket.on('end', function () {
proxy.end();
});
socket.on('error', function () {
proxy.end();
});
};
};
app.createContext = function(req, res) {
let ctx = Object.create(this.context);
ctx.app = this;
ctx.req = req;
ctx.res = res;
ctx.onerror = ctx.onerror.bind(ctx);
return ctx;
};
function *respond(next) {
yield *next;
let self = this;
let req = this.req;
let res = this.res;
let type = this.req.type;
let protocol = (type === 'http') ? http : https;
let request = protocol.request({
host: req.headers.host,
port: (type === 'http') ? 80 : 443,
path: self.path,
headers: req.headers
}, function (response) {
response.pipe(res);
});
req.pipe(request);
request.end();
}
function getSNI (buffer) {
if (buffer.readInt8(0) !== 22) {
// not a TLS Handshake packet
return null;
}
// Session ID Length (static position)
var currentPos = 43;
// Skip session IDs
currentPos += 1 + buffer[currentPos];
// skip Cipher Suites
currentPos += 2 + buffer.readInt16BE(currentPos);
// skip compression methods
currentPos += 1 + buffer[currentPos];
// We are now at extensions!
currentPos += 2; // ignore extensions length
while (currentPos < buffer.length) {
if (buffer.readInt16BE(currentPos) === 0) {
// we have found an SNI
var sniLength = buffer.readInt16BE(currentPos + 2);
currentPos += 4;
if (buffer[currentPos] != 0) {
// the RFC says this is a reserved host type, not DNS
return null;
}
currentPos += 5;
return buffer.toString('utf8', currentPos, currentPos + sniLength - 5);
} else {
currentPos += 4 + buffer.readInt16BE(currentPos + 2);
}
}
return null;
};