-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
224 lines (182 loc) · 7.19 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
'use strict';
var inherit = require('inherit'),
q = require('q'),
childProcess = require('child_process'),
util = require('util'),
EventEmitter = require('events').EventEmitter,
debug = require('debug')('ssh-tun'),
ActivityWatcher = require('./activity-watcher');
var DEFAULTS = {
MAX_RETRIES: 5,
CONNECT_TIMEOUT: 10000,
SSH_PORT: 22
};
var Tunnel = inherit(EventEmitter, {
/**
* Constuctor
* @param {object} opts tunnel options
* @param {string} opts.host remote host address
* @param {object} opts.ports remote host ports range
* @param {number} opts.localport local port number
* @param {string} [opts.user] remote host user
* @param {string} [opts.sshPort=22] host port to create tunnel
* @param {number} [opts.maxRetries=5] max attempts to create tunnel
* @param {number} [opts.connectTimeout=10000] ssh connect timeout
* @param {boolean} [opts.strictHostKeyChecking=true] verify host authenticity
* @param {string} [opts.identity] private key for public key authentication
* @param {boolean} [opts.compression] use compression
* @param {number} [opts.inactivityTimeout] inactivity timeout (including keep-alive pings, may degrade performance)
* @param {number} [opts.enableDeprecatedSshRsa] add deprecated ssh-rsa to the key algorithms list
*/
__constructor: function (opts) {
EventEmitter.call(this);
this.host = opts.host;
this.port = this._generateRandomPort(opts.ports);
this._sshPort = opts.sshPort || DEFAULTS.SSH_PORT;
this.user = opts.user;
this.proxyHost = util.format('%s:%d', this.host, this.port);
this.proxyUrl = this.proxyHost; // deprecated, use proxyHost
this.connected = false;
this._localPort = opts.localport;
this._connectTimeout = opts.connectTimeout || DEFAULTS.CONNECT_TIMEOUT;
this._tunnel = null;
this._tunnelDeferred = q.defer();
this._closeDeferred = q.defer();
this._strictHostKeyChecking = opts.strictHostKeyChecking === undefined ? true : opts.strictHostKeyChecking;
this._compression = opts.compression;
this._identity = opts.identity;
this._enableDeprecatedSshRsa = opts.enableDeprecatedSshRsa;
this._activityWatcher = opts.inactivityTimeout > 0 ?
new ActivityWatcher(opts.inactivityTimeout, this.close.bind(this, 'inactivity timeout')) : null;
},
/**
* Tries to open ssh connection to remote server
* @returns {Promise}
*/
open: function () {
var _this = this;
console.info('INFO: creating tunnel to %s', this.proxyHost);
var cmd = this._buildSSHArgs();
debug('running ssh: ssh', cmd.join(' '));
this._tunnel = childProcess.spawn('ssh', cmd);
this._tunnel.stderr.on('data', this._onData.bind(this));
this._tunnel.on('exit', function (code, signal) {
_this.emit('exit', code, signal);
});
this._tunnel.on('close', function (code, signal) {
_this.emit('close', code, signal);
return _this._closeTunnel(code);
});
this._tunnel.on('error', function () {
return _this._rejectTunnel();
});
return _this._tunnelDeferred.promise.timeout(this._connectTimeout);
},
/**
* Closes connection. If no connection established does nothing
* @returns {Promise}
*/
close: function (reason) {
reason = reason || 'intentional close';
if (!this._tunnel) {
return q();
}
var _this = this;
debug('closing tunnel: ' + reason);
this._tunnel.kill('SIGTERM');
return this._closeDeferred.promise.timeout(3000).fail(function () {
debug('killing tunnel due to termination timeout, original reason: ' + reason);
_this._tunnel.kill('SIGKILL');
return _this._closeTunnel(-1);
});
},
_onData: function (data) {
if (debug.enabled) {
debug('data:', data.toString());
}
if (this._activityWatcher) {
this._activityWatcher.update();
}
if (this.connected) {
return;
}
if (/success/.test(data)) {
if (!this._shouldBeVerbose()) {
this._tunnel.stderr.removeAllListeners('data');
}
return this._resolveTunnel();
}
if (/failed/.test(data)) {
return this._rejectTunnel();
}
},
_resolveTunnel: function () {
console.info('INFO: Tunnel created to %s', this.proxyHost);
if (this._activityWatcher) {
debug('start activity watcher');
this._activityWatcher.start();
}
this.connected = true;
this._tunnelDeferred.resolve();
},
_rejectTunnel: function () {
var message = util.format('ERROR: failed to create tunnel to %s.', this.proxyHost),
error = new Error(message);
console.info(message);
this._tunnelDeferred.reject(error);
},
_closeTunnel: function (exitCode) {
console.info('INFO: Tunnel to %s closed. Exit code: %d', this.proxyHost, exitCode);
this.connected = false;
this._closeDeferred.resolve();
},
_buildSSHArgs: function () {
return [
util.format('-R %d:localhost:%d', this.port, this._localPort),
'-N',
// heartbeat messages existence is logged to debug3 (penSSH_7.9p1, LibreSSL 2.7.3, macOC Catalina)
this._shouldBeVerbose() ? '-vvv' : '-v',
this._strictHostKeyChecking === false ? '-o StrictHostKeyChecking=no' : '',
this._enableDeprecatedSshRsa && ['-o HostKeyAlgorithms=+ssh-rsa', '-o PubkeyAcceptedKeyTypes=+ssh-rsa'],
this._compression !== undefined ?
util.format('-o Compression=%s', this._compression ? 'yes' : 'no')
: '',
this._identity ? util.format('-i %s', this._identity) : '',
util.format('-p %d', this._sshPort),
(this.user ? this.user + '@' : '') + this.host
].filter(Boolean).flat();
},
_shouldBeVerbose: function () {
return debug.enabled || this._activityWatcher;
},
_generateRandomPort: function (ports) {
var min = ports.min,
max = ports.max;
return Math.floor(Math.random() * (max - min + 1)) + min;
}
});
/**
* Tries to open tunnel several times
* @param {object} opts opts which will be passed to created tunnel
* @param {number} retries amount of retries to open tunnel
* @returns {Promise}
*/
Tunnel.openWithRetries = function (opts, retries) {
retries = retries || DEFAULTS.MAX_RETRIES;
function retry_(retriesLeft) {
if (!retriesLeft) {
return q.reject(util.format('ERROR: failed to create tunnel after %d attempts', retries));
}
var tunnel = new Tunnel(opts);
return tunnel.open()
.then(function () {
return q.resolve(tunnel);
})
.fail(function () {
return tunnel.close()
.then(retry_.bind(null, retriesLeft - 1));
});
}
return retry_(retries);
};
module.exports = Tunnel;