ssh-client-wrapper 3.4.3 → 3.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -204,6 +204,23 @@ Checks if a connection to the remote host can be established.
204
204
 
205
205
  * Returns: `Promise<boolean>` - Resolves with `true` on success.
206
206
 
207
+ ### Connection failures
208
+
209
+ If the login can not be done, the promise is rejected with an `Error` as soon as `ssh` gives up. `err.code` tells the cause, and `err.output` has what `ssh` said (the last 4096 characters). `host`, `user` and `port` tell which login failed.
210
+
211
+ | `err.code` | cause |
212
+ |---|---|
213
+ | `AUTH_FAILED` | the login is refused (`message` is `Permission denied`) |
214
+ | `CONNECTION_REFUSED` | nothing listens on the port |
215
+ | `HOST_UNREACHABLE` | no route to the host, or the network is unreachable |
216
+ | `HOST_NOT_FOUND` | the host name can not be resolved |
217
+ | `CONNECT_TIMEOUT` | the connection timed out (see `ConnectTimeout`) |
218
+ | `HOSTKEY_FAILED` | the host key verification failed |
219
+ | `BAD_PORT` | invalid port number |
220
+ | `CONTROL_SOCKET_FAILED` | the socket of the master connection can not be created |
221
+ | `TIMEEXPIRE` | `ssh` did not finish within `timeout` |
222
+ | `SSH_FAILED` | any other failure; `message` is the last line which `ssh` said |
223
+
207
224
  ### Wrong password
208
225
 
209
226
  If the login is refused, the promise is rejected with an `Error` whose `message` is `Permission denied` and whose `code` is `AUTH_FAILED`. `host`, `user` and `port` tell which login failed.
package/lib/fork.js CHANGED
@@ -68,6 +68,19 @@ export function sshLoginCallback(output, ptyProcess, pw, ph, logger = debugSendP
68
68
  });
69
69
  }
70
70
 
71
+ /**
72
+ * end the shell of a master pty. The shell has no other purpose than to start the master ssh.
73
+ * Typing "exit" is not enough, ssh which is still running in the foreground would read it.
74
+ * kill() without a signal sends SIGHUP, which the shell sometimes survives while ssh is ending.
75
+ * A left shell keeps the Node.js process alive.
76
+ * Signals are not supported on win32, where kill() closes the pseudo console.
77
+ * @param {object} pty - pty object returned by node-pty spawn()
78
+ * @param {string} [platform] - platform name
79
+ */
80
+ export function endMasterShell(pty, platform = process.platform) {
81
+ pty.kill(platform === "win32" ? undefined : "SIGKILL");
82
+ }
83
+
71
84
  /**
72
85
  * create pty for master ssh session and store to hostInfo.masterPty
73
86
  */
@@ -76,7 +89,7 @@ export function createMasterPty(hostInfo) {
76
89
 
77
90
  if (hostInfo.masterPty) {
78
91
  debug(`kill existing master pty for ${hostInfo.host}`);
79
- hostInfo.masterPty.kill();
92
+ endMasterShell(hostInfo.masterPty);
80
93
  }
81
94
  const ptyProcess = spawn(nodePtyOpt.shell, [], nodePtyOpt);
82
95
  ptyProcess.onExit(()=>{
@@ -0,0 +1,87 @@
1
+ import { stripTerminalSequences } from "./util.js";
2
+
3
+ const MAX_OUTPUT = 4096;
4
+ const FAIL_PREFIX = "SCWFAIL";
5
+
6
+ //messages of ssh after which there is nothing to wait for. The first match wins.
7
+ const knownFailures = [
8
+ { re: /Permission denied \(/, code: "AUTH_FAILED", message: "Permission denied", fatal: true },
9
+ { re: /Could not resolve hostname/, code: "HOST_NOT_FOUND", message: "Could not resolve hostname", fatal: true },
10
+ { re: /Bad port/, code: "BAD_PORT", message: "Bad port", fatal: true },
11
+ { re: /(?:Operation|Connection) timed out/, code: "CONNECT_TIMEOUT", message: "Operation timed out", fatal: true },
12
+ { re: /muxserver_listen: link mux listener .* Bad file descriptor/, code: "CONTROL_SOCKET_FAILED", message: "Control socket creation failed", fatal: true },
13
+ { re: /ssh: connect to host .*: Connection refused/, code: "CONNECTION_REFUSED" },
14
+ { re: /ssh: connect to host .*: (?:No route to host|Network is unreachable)/, code: "HOST_UNREACHABLE" },
15
+ { re: /Host key verification failed/, code: "HOSTKEY_FAILED", message: "Host key verification failed" }
16
+ ];
17
+
18
+ /**
19
+ * check if the output of ssh tells that the connection can not be made any more
20
+ * @param {string} output - output of ssh
21
+ * @returns {boolean} - true if ssh has failed
22
+ */
23
+ export const isFatalOutput = (output)=>{
24
+ return knownFailures.some((e)=>{
25
+ return e.fatal && e.re.test(output);
26
+ });
27
+ };
28
+
29
+ /**
30
+ * make an error object which tells why ssh failed
31
+ * @param {string} output - output of ssh
32
+ * @param {object} hostInfo - hostinfo object
33
+ * @returns {Error} - error with code, host, user, port and output (the tail of the output of ssh)
34
+ */
35
+ export const makeSshError = (output, hostInfo)=>{
36
+ const lines = stripTerminalSequences(output).split(/[\r\n]+/)
37
+ .map((e)=>{
38
+ return e.trim();
39
+ })
40
+ .filter(Boolean);
41
+ const text = lines.join("\n");
42
+ const known = knownFailures.find((e)=>{
43
+ return e.re.test(text);
44
+ });
45
+ const matched = known && lines.find((e)=>{
46
+ return known.re.test(e);
47
+ });
48
+ const err = new Error(known?.message ?? matched ?? lines.at(-1) ?? "ssh connection failed");
49
+ err.code = known?.code ?? "SSH_FAILED";
50
+ err.host = hostInfo.host;
51
+ err.user = hostInfo.user;
52
+ err.port = hostInfo.port;
53
+ err.output = output.slice(-MAX_OUTPUT);
54
+ return err;
55
+ };
56
+
57
+ /**
58
+ * make the command line which is typed into the shell of the master pty
59
+ * the shell prints the mark only if ssh fails. The mark is written with "" in it,
60
+ * so that the line which the terminal echoes back does not contain the mark itself.
61
+ * "||" is understood by sh, bash, zsh, fish and csh.
62
+ * @param {string} cmd - ssh command
63
+ * @param {Array} args - arguments of ssh
64
+ * @param {string} words - string which the remote host echoes if the login succeeds
65
+ * @param {string} failId - string which makes the mark unique. It must differ from words
66
+ * @returns {object} - { line: command line, failMark: string which is printed if ssh fails }
67
+ */
68
+ export const makeMasterCommand = (cmd, args, words, failId)=>{
69
+ return {
70
+ line: `${cmd} ${args.join(" ")} echo ${words} || echo ${FAIL_PREFIX}""-${failId}\n`,
71
+ failMark: `${FAIL_PREFIX}-${failId}`
72
+ };
73
+ };
74
+
75
+ /**
76
+ * cut the output of ssh out of the output of the master pty
77
+ * @param {string} output - output of the master pty
78
+ * @param {string} failMark - failMark returned by makeMasterCommand
79
+ * @returns {string} - output without the echoed command line, the mark and what follows it
80
+ */
81
+ export const extractSshOutput = (output, failMark)=>{
82
+ const end = output.indexOf(failMark);
83
+ const head = end < 0 ? output : output.slice(0, end);
84
+ const typed = failMark.replace(FAIL_PREFIX, `${FAIL_PREFIX}""`);
85
+ const start = head.lastIndexOf(typed);
86
+ return start < 0 ? head : head.slice(start + typed.length).replace(/^\r*\n/, "");
87
+ };
package/lib/sshExec.js CHANGED
@@ -2,8 +2,9 @@ import crypto from "crypto";
2
2
  import { setTimeout as setTimeoutPromise } from "timers/promises";
3
3
  import Debug from "debug";
4
4
  import { sendPty, sshCmd, getSshOption, getNoStdinOption, isControlMasterEnabled, sanityCheck, watchDogTimer, rePwPrompt, rePhPrompt } from "./util.js";
5
- import { fork, createMasterPty, sshLoginCallback } from "./fork.js";
5
+ import { fork, createMasterPty, endMasterShell, sshLoginCallback } from "./fork.js";
6
6
  import { shouldUseAgent, ensureAgentForHost } from "./agent.js";
7
+ import { makeSshError, makeMasterCommand, extractSshOutput, isFatalOutput } from "./sshError.js";
7
8
 
8
9
  const debug = Debug("sshClientWrapper:debug:sshExec");
9
10
  const debugVerbose = Debug("sshClientWrapper:verbose:sshExec");
@@ -118,9 +119,9 @@ export async function canConnect(hostInfo, timeout) {
118
119
  */
119
120
  async function existsMaster(hostInfo, argTimeout) {
120
121
  debugVerbose("existsMaster called");
121
- const args = getSshOption(hostInfo);
122
- args.push(...getNoStdinOption());
123
- args.push("-Ocheck");
122
+ //-O must be in front of the host name: after a word which is not an option (e.g. in sshOpt),
123
+ //ssh would take it as a part of the remote command
124
+ const args = ["-Ocheck", ...getSshOption(hostInfo), ...getNoStdinOption()];
124
125
 
125
126
  let output = "";
126
127
  const cb = (e)=>{
@@ -140,10 +141,12 @@ async function existsMaster(hostInfo, argTimeout) {
140
141
  debug("check master session failed", err);
141
142
  throw err;
142
143
  }
144
+ //only the exit code 0 tells that the master answered. The reason of 255 does not matter here:
145
+ //if ssh can not work at all, the following connection tells why
146
+ debug("no master session:", output);
147
+ return false;
143
148
  }
144
-
145
- //"Connection refused" means that the socket is left but nobody listens (the master was killed, or it is exiting)
146
- return !/Control socket connect.*: (No such file or directory|Connection refused)/.test(output);
149
+ return true;
147
150
  }
148
151
 
149
152
  /**
@@ -168,26 +171,25 @@ async function verifyConnection(hostInfo, timeout) {
168
171
  try {
169
172
  await fork(hostInfo, sshCmd, args, timeout, cb);
170
173
  } catch (e) {
171
- const err = new Error(e.message);
172
- err.host = hostInfo.host;
173
- err.user = hostInfo.user;
174
- err.port = hostInfo.port;
175
- err.output = output;
176
174
  if (e.code === "TIMEEXPIRE") {
175
+ const err = makeSshError(output, hostInfo);
177
176
  err.message = `can not connect within ${timeout} sec`;
178
- } else if (/Permission denied \(/.test(output)) {
179
- err.message = "Permission denied";
180
- err.code = "AUTH_FAILED";
181
- } else if (/Could not resolve hostname/.test(output)) {
182
- err.message = "Could not resolve hostname";
183
- } else if (/Bad port/.test(output)) {
184
- err.message = "Bad port";
185
- } else if (/Operation|Connection timed out/.test(output)) {
186
- err.message = "Operation timed out";
187
- } else {
177
+ err.code = "TIMEEXPIRE";
178
+ throw err;
179
+ }
180
+ //an error which is neither the exit of ssh nor made from its output (e.g. thrown by a password callback) is passed as it is
181
+ if (e.rt === undefined && !e.retryable) {
188
182
  e.output = output;
189
183
  throw e;
190
184
  }
185
+ const err = makeSshError(output, hostInfo);
186
+ if (e.retryable) {
187
+ //fork() has stopped ssh by itself (kex_exchange_identification)
188
+ err.message = e.message;
189
+ err.retryable = true;
190
+ } else {
191
+ err.rt = e.rt;
192
+ }
191
193
  throw err;
192
194
  }
193
195
  debug(`connected to ${hostInfo.host}`);
@@ -229,57 +231,57 @@ export async function connect(hostInfo, timeout = 60) {
229
231
 
230
232
  debug(`create master pty for ${hostInfo.host}`);
231
233
  createMasterPty(hostInfo, debugSendMasterPty);
234
+ //this connection deals only with its own pty. hostInfo.masterPty can be released or replaced at any time
235
+ const pty = hostInfo.masterPty;
236
+ //the output which arrives after the result of the connection is known must be ignored
237
+ let over = false;
232
238
 
233
239
  debug(`create master ssh session to ${hostInfo.host}`);
234
240
  const words = crypto.randomUUID();
235
241
  const re = new RegExp(`^${words}`);
242
+ const { line, failMark } = makeMasterCommand(sshCmd, getSshOption(hostInfo), words, crypto.randomUUID());
236
243
 
237
244
  let ac = null;
238
- let output = null;
245
+ let output = "";
239
246
  const p = new Promise((resolve, reject)=>{
247
+ const failure = ()=>{
248
+ return makeSshError(extractSshOutput(output, failMark), hostInfo);
249
+ };
240
250
  ac = watchDogTimer(timeout, "make connection", ()=>{
241
- sendPty(hostInfo.masterPty, "\n", debugSendMasterPty, 137);
242
- sendPty(hostInfo.masterPty, "exit\n", debugSendMasterPty, 138);
243
-
244
- const err = new Error(`can not connect within ${timeout} sec`);
245
- err.host = hostInfo.host;
246
- err.user = hostInfo.user;
247
- err.port = hostInfo.port;
248
- err.output = output;
251
+ const err = failure();
252
+ err.message = `can not connect within ${timeout} sec`;
253
+ err.code = "TIMEEXPIRE";
249
254
  reject(err);
250
255
  });
251
256
 
252
257
  let done = false;
253
- hostInfo.masterPty.onData((data)=>{
254
- if (done) {
258
+ pty.onData((data)=>{
259
+ if (done || over) {
255
260
  //safeguard
256
261
  return;
257
262
  }
258
- output = data.toString();
259
- debugVerbose(output);
263
+ const chunk = data.toString();
264
+ output = `${output}${chunk}`.slice(-65536);
265
+ debugVerbose(chunk);
260
266
 
261
- if (re.test(output)) {
267
+ if (re.test(chunk)) {
262
268
  debug("test done. call exit on remotehost");
263
269
  done = true;
264
270
  resolve();
265
- } else if (/Permission denied \(/.test(output)) {
266
- const err = new Error("Permission denied");
267
- err.code = "AUTH_FAILED";
268
- err.host = hostInfo.host;
269
- err.user = hostInfo.user;
270
- err.port = hostInfo.port;
271
- reject(err);
272
- } else if (/Could not resolve hostname/.test(output)) {
273
- reject(new Error("Could not resolve hostname"));
274
- } else if (/Bad port/.test(output)) {
275
- reject(new Error("Bad port"));
276
- } else if (/Operation|Connection timed out/.test(output)) {
277
- reject(new Error("Operation timed out"));
278
- } else if (/muxserver_listen: link mux listener .* Bad file descriptor/.test(output)) {
279
- reject(new Error("Control socket creation failed"));
271
+ } else if (isFatalOutput(chunk)) {
272
+ reject(failure());
273
+ } else if (output.includes(failMark)) {
274
+ done = true;
275
+ //let the handler below reject first if it knows better (e.g. the host key has been changed)
276
+ setImmediate(()=>{
277
+ reject(failure());
278
+ });
280
279
  }
281
280
  });
282
- hostInfo.masterPty.onData((data)=>{
281
+ pty.onData((data)=>{
282
+ if (over) {
283
+ return;
284
+ }
283
285
  const output = data.toString();
284
286
 
285
287
  if (shouldUseAgent(hostInfo) && (rePwPrompt.test(output) || rePhPrompt.test(output))) {
@@ -297,32 +299,29 @@ export async function connect(hostInfo, timeout = 60) {
297
299
  return;
298
300
  }
299
301
  }
300
- sshLoginCallback(output, hostInfo.masterPty, hostInfo.password, hostInfo.passphrase, debugSendMasterPty)
302
+ sshLoginCallback(output, pty, hostInfo.password, hostInfo.passphrase, debugSendMasterPty)
301
303
  .catch(reject);
302
304
  });
303
- hostInfo.masterPty.onExit((e)=>{
305
+ pty.onExit((e)=>{
304
306
  debug("master pty exit", e);
305
307
  resolve(e);
306
308
  });
307
309
  });
308
310
 
309
- const args = getSshOption(hostInfo);
310
- args.push(`echo ${words}`);
311
- const cmd = `${sshCmd} ${args.join(" ")}\n`;
312
- sendPty(hostInfo.masterPty, cmd, debugSendMasterPty, 190);
313
-
314
311
  try {
312
+ await sendPty(pty, line, debugSendMasterPty, 190);
315
313
  await p;
316
314
  debug(`connected to ${hostInfo.host}`);
317
315
  } catch (e) {
318
316
  //the pty of a failed connection must not be left behind. It keeps the process alive.
319
317
  debug(`failed to connect to ${hostInfo.host}, kill master pty`);
320
- if (hostInfo.masterPty) {
321
- hostInfo.masterPty.kill();
318
+ endMasterShell(pty);
319
+ if (hostInfo.masterPty === pty) {
322
320
  hostInfo.masterPty = null;
323
321
  }
324
322
  throw e;
325
323
  } finally {
324
+ over = true;
326
325
  if (ac !== null) {
327
326
  ac.abort();
328
327
  }
@@ -344,9 +343,8 @@ export async function disconnect(hostInfo) {
344
343
 
345
344
  try {
346
345
  if (await existsMaster(hostInfo)) {
347
- const args = getSshOption(hostInfo);
348
- args.push(...getNoStdinOption());
349
- args.push("-Oexit");
346
+ //-O in front of the host name, for the same reason as in existsMaster()
347
+ const args = ["-Oexit", ...getSshOption(hostInfo), ...getNoStdinOption()];
350
348
 
351
349
  let output = "";
352
350
  const cb = (e)=>{
@@ -370,7 +368,7 @@ export async function disconnect(hostInfo) {
370
368
  //the pty must be released even if the master is already gone. It keeps the process alive.
371
369
  if (hostInfo.masterPty) {
372
370
  debug("exit masterPty");
373
- sendPty(hostInfo.masterPty, "exit \n", debugSendMasterPty, 228);
371
+ endMasterShell(hostInfo.masterPty);
374
372
  hostInfo.masterPty = null;
375
373
  }
376
374
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ssh-client-wrapper",
3
- "version": "3.4.3",
3
+ "version": "3.4.5",
4
4
  "description": "wrapper library for open ssh client and rsync",
5
5
  "keywords": [
6
6
  "ssh",