This repository was archived by the owner on Aug 26, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathConnection.ts
More file actions
239 lines (216 loc) · 7.12 KB
/
Connection.ts
File metadata and controls
239 lines (216 loc) · 7.12 KB
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
/*
* Copyright 2018 Stocard GmbH.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Client } from 'ssh2'
import * as net from 'net'
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import * as readline from 'readline'
import * as debug from 'debug'
interface Options {
username?: string
password?: string
privateKey?: string | Buffer
agentForward? : boolean
bastionHost?: string
passphrase?: string
endPort?: number
endHost: string
agentSocket?: string,
skipAutoPrivateKey?: boolean
noReadline?: boolean
readyTimeout?: number
}
interface ForwardingOptions {
fromPort: number
toPort: number
toHost?: string
}
class SSHConnection {
private debug
private server
private connections: Client[] = []
private isWindows = process.platform === 'win32'
constructor(private options: Options) {
this.debug = debug('ssh')
if (!options.username) {
this.options.username = process.env['SSH_USERNAME'] || process.env['USER']
}
if (!options.endPort) {
this.options.endPort = 22
}
if (!options.privateKey && !options.agentForward && !options.skipAutoPrivateKey) {
const defaultFilePath = path.join(os.homedir(), '.ssh', 'id_rsa')
if (fs.existsSync(defaultFilePath)) {
this.options.privateKey = fs.readFileSync(defaultFilePath)
}
}
}
public async shutdown() {
this.debug('Shutdown connections')
for (const connection of this.connections) {
connection.removeAllListeners()
connection.end()
}
return new Promise<void>((resolve) => {
if (this.server) {
this.server.close(resolve)
}
return resolve()
})
}
public async tty() {
const connection = await this.establish()
this.debug('Opening tty')
await this.shell(connection)
}
public async executeCommand(command) {
const connection = await this.establish()
this.debug('Executing command "%s"', command)
await this.shell(connection, command)
}
private async shell(connection: Client, command?: string) {
return new Promise((resolve, reject) => {
connection.shell((err, stream) => {
if (err) {
return reject(err)
}
stream.on('close', async () => {
stream.end()
process.stdin.unpipe(stream)
process.stdin.destroy()
connection.end()
await this.shutdown()
return resolve()
}).stderr.on('data', (data) => {
return reject(data)
})
stream.pipe(process.stdout)
if (command) {
stream.end(`${command}\nexit\n`)
} else {
process.stdin.pipe(stream)
}
})
})
}
private async establish() {
let connection: Client
if (this.options.bastionHost) {
connection = await this.connectViaBastion(this.options.bastionHost)
} else {
connection = await this.connect(this.options.endHost)
}
return connection
}
private async connectViaBastion(bastionHost: string) {
this.debug('Connecting to bastion host "%s"', bastionHost)
const connectionToBastion = await this.connect(bastionHost)
return new Promise<Client>((resolve, reject) => {
connectionToBastion.forwardOut('127.0.0.1', 22, this.options.endHost, this.options.endPort || 22, async (err, stream) => {
if (err) {
return reject(err)
}
const connection = await this.connect(this.options.endHost, stream)
return resolve(connection)
})
})
}
private async connect(host: string, stream?: NodeJS.ReadableStream): Promise<Client> {
this.debug('Connecting to "%s"', host)
const connection = new Client()
return new Promise<Client>(async (resolve, reject) => {
const options = {
host,
port: this.options.endPort,
username: this.options.username,
password: this.options.password,
privateKey: this.options.privateKey
}
if (this.options.readyTimeout) {
options['readyTimeout'] = this.options.readyTimeout
}
if (this.options.agentForward) {
options['agentForward'] = true
// see https://github.com/mscdex/ssh2#client for agents on Windows
// guaranteed to give the ssh agent sock if the agent is running (posix)
let agentDefault = process.env['SSH_AUTH_SOCK']
if (this.isWindows) {
// null or undefined
if (agentDefault == null) {
agentDefault = 'pageant'
}
}
const agentSock = this.options.agentSocket ? this.options.agentSocket : agentDefault
if (agentSock == null) {
throw new Error('SSH Agent Socket is not provided, or is not set in the SSH_AUTH_SOCK env variable')
}
options['agent'] = agentSock
}
if (stream) {
options['sock'] = stream
}
// PPK private keys can be encrypted, but won't contain the word 'encrypted'
// in fact they always contain a `encryption` header, so we can't do a simple check
options['passphrase'] = this.options.passphrase
const looksEncrypted: boolean = this.options.privateKey ? this.options.privateKey.toString().toLowerCase().includes('encrypted') : false
if (looksEncrypted && !options['passphrase'] && !this.options.noReadline) {
options['passphrase'] = await this.getPassphrase()
}
connection.on('ready', () => {
this.connections.push(connection)
return resolve(connection)
})
connection.on('error', (error) => {
reject(error)
})
try {
connection.connect(options)
} catch (error) {
reject(error)
}
})
}
private async getPassphrase() {
return new Promise((resolve) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
rl.question('Please type in the passphrase for your private key: ', (answer) => {
return resolve(answer)
})
})
}
async forward(options: ForwardingOptions) {
const connection = await this.establish()
return new Promise((resolve, reject) => {
this.server = net.createServer((socket) => {
this.debug('Forwarding connection from "localhost:%d" to "%s:%d"', options.fromPort, options.toHost, options.toPort)
connection.forwardOut('localhost', options.fromPort, options.toHost || 'localhost', options.toPort, (error, stream) => {
if (error) {
return reject(error)
}
socket.pipe(stream)
stream.pipe(socket)
})
}).listen(options.fromPort, 'localhost', () => {
return resolve()
})
})
}
}
export { SSHConnection, Options }