mcp-ssh-manager 3.6.6 → 3.7.0

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/CHANGELOG.md CHANGED
@@ -5,6 +5,32 @@ All notable changes to MCP SSH Manager will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [3.7.0] - 2026-07-13
9
+
10
+ ### Added
11
+
12
+ - **Per-server SSH agent forwarding (`ForwardAgent`)** ([#53](https://github.com/bvisible/mcp-ssh-manager/pull/53) — requested by [@raphaelbahat](https://github.com/raphaelbahat) in [#52](https://github.com/bvisible/mcp-ssh-manager/issues/52))
13
+ - New opt-in option, `SSH_SERVER_<NAME>_FORWARD_AGENT=true` (`.env`) or `forward_agent = true` (TOML), enabling the equivalent of OpenSSH's `ForwardAgent yes` on a per-server basis. Processes on the remote host can then authenticate to other SSH hosts using the keys held in the operator's local `ssh-agent` (e.g. `git` over SSH), without copying any private key to the server.
14
+ - Requires a running local agent (`SSH_AUTH_SOCK`); the flag is ignored when no agent is present. `ForwardAgent` is set only alongside a valid agent, since `ssh2` throws otherwise. Because `ssh2`'s connection-level `agentForward` forwards on every exec/shell channel, no per-command change is needed.
15
+ - A `parseBool()` helper coerces the `.env` string value so `FORWARD_AGENT=false` is not treated as truthy; only `true`/`1`/`yes`/`on` enable it.
16
+ - **Defaults to `false`.** Documented in the README (*SSH Agent Forwarding*) and CLAUDE.md with the standard security warning (a root user on the remote host can use the forwarded agent for the life of the connection).
17
+ - Tests: `tests/test-agent-forward.js` verifies the `connect()` wiring across the on/off/absent/no-agent states; `tests/test-config-field-names.js` gains `forwardAgent` coverage including `.env` boolean coercion and a TOML export round-trip.
18
+
19
+ ## [3.6.7] - 2026-07-11
20
+
21
+ ### Security
22
+
23
+ - **Command injection in the database command builders** ([#51](https://github.com/bvisible/mcp-ssh-manager/pull/51) — responsibly disclosed by **Ugur Ozer, Aeon AI Risk Management** (http://airiskmanagement.ca), see [#48](https://github.com/bvisible/mcp-ssh-manager/issues/48))
24
+ - Every `ssh_db_*` tool argument — `database`, `table`, `collection`, output/input file paths, and the `user` / `host` / `port` / `password` connection fields — arrives from tool-call parameters and was interpolated straight into a **shell-evaluated** command string in `src/database-manager.js`. A crafted value (`$(…)`, backticks, `; cmd`, `| cmd`, `&& cmd`, bare `> file`) executed arbitrary commands on the configured SSH target, under the account the MCP server uses.
25
+ - The strongest path is **`ssh_db_list`**: it is classified read-only, so it stayed **allowed in the `readonly` and `restricted`** per-server security modes while still reaching an injectable builder — bypassing the boundary those modes promise.
26
+ - The v3.6.5 heredoc fix (#44) only hardened `ssh_db_query`'s query **text**; the `list` / `dump` / `import` / `restore` builders and the query builders' **connection flags** were untouched.
27
+ - **Fix:** a centralized `shellQuote()` (single-quote wrap + `'\''` escaping) now wraps **every** interpolated caller value across all 15 builders. The MySQL list-tables `database` became a shell-quoted positional argument instead of an interpolated `USE <db>` SQL clause, closing the SQL path too. Shell-quoting is transparent for legitimate values.
28
+
29
+ ### Added
30
+
31
+ - Security regression test `tests/test-database-injection.js` (`npm run test:dbinjection`, part of `npm test`): drives every builder × every caller-controlled parameter × an injection-payload battery (648 combinations) through a real `/bin/sh` with fake DB client binaries and asserts no payload ever executes; unit-tests `shellQuote()`; verifies benign values stay correctly quoted.
32
+ - `SECURITY.md` documenting the private vulnerability disclosure process (GitHub private vulnerability reporting + security email; resolves [#48](https://github.com/bvisible/mcp-ssh-manager/issues/48)).
33
+
8
34
  ## [3.6.6] - 2026-07-11
9
35
 
10
36
  ### Fixed
package/CLAUDE.md CHANGED
@@ -157,6 +157,7 @@ SSH_SERVER_[NAME]_SUDO_PASSWORD=pass # Optional for automated sudo
157
157
  SSH_SERVER_[NAME]_PLATFORM=windows # Optional: "linux" (default) or "windows"
158
158
  SSH_SERVER_[NAME]_PROXYJUMP=bastion # Optional: name of another server to use as jump host
159
159
  SSH_SERVER_[NAME]_PROXYCOMMAND=command # Optional: custom proxy command (ncat, ssh -W, etc.)
160
+ SSH_SERVER_[NAME]_FORWARD_AGENT=true # Optional: forward local ssh-agent to remote (needs SSH_AUTH_SOCK; security risk)
160
161
  ```
161
162
 
162
163
  ### TOML Format
@@ -173,6 +174,7 @@ sudo_password = "pass" # Optional for automated sudo
173
174
  platform = "windows" # Optional: "linux" (default) or "windows"
174
175
  proxy_jump = "bastion" # Optional: name of another server to use as jump host
175
176
  proxy_command = "command" # Optional: custom proxy command (ncat, ssh -W, etc.)
177
+ forward_agent = true # Optional: forward local ssh-agent to remote (needs SSH_AUTH_SOCK; security risk)
176
178
  ```
177
179
 
178
180
  ## Key Implementation Details
package/README.md CHANGED
@@ -6,7 +6,7 @@ A Model Context Protocol (MCP) server that enables **Claude Code** and **OpenAI
6
6
 
7
7
  [![npm version](https://img.shields.io/npm/v/mcp-ssh-manager.svg?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/mcp-ssh-manager)
8
8
  [![npm downloads](https://img.shields.io/npm/dt/mcp-ssh-manager.svg?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/mcp-ssh-manager)
9
- [![Version](https://img.shields.io/badge/Version-3.6.6-brightgreen?style=for-the-badge)](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v3.6.6)
9
+ [![Version](https://img.shields.io/badge/Version-3.7.0-brightgreen?style=for-the-badge)](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v3.7.0)
10
10
  [![Claude Code](https://img.shields.io/badge/Claude_Code-Compatible-5A67D8?style=for-the-badge&logo=anthropic)](https://claude.ai/code)
11
11
  [![OpenAI Codex](https://img.shields.io/badge/OpenAI_Codex-Compatible-00A67E?style=for-the-badge&logo=openai)](https://openai.com/codex)
12
12
  [![MCP](https://img.shields.io/badge/MCP-Server-orange?style=for-the-badge)](https://modelcontextprotocol.io)
@@ -20,21 +20,32 @@ A Model Context Protocol (MCP) server that enables **Claude Code** and **OpenAI
20
20
 
21
21
  ---
22
22
 
23
- ## 🎉 What's New in v3.6.6
23
+ ## 🎉 What's New in v3.7.0
24
24
 
25
- **Bugfix: per-server `SUDO_PASSWORD`, `DEFAULT_DIR` and `ssh_sync` key auth work again** (Released: July 11, 2026)
25
+ **🔗 Per-server SSH agent forwarding (`ForwardAgent`)** (Released: July 13, 2026)
26
26
 
27
- - **🔑 `ssh_execute_sudo` respects the configured `SSH_SERVER_<NAME>_SUDO_PASSWORD` again** ([#49](https://github.com/bvisible/mcp-ssh-manager/issues/49) — thanks [@egoan82](https://github.com/egoan82) for the excellent root-cause report) — since the v3.0.0 ConfigLoader refactor, resolved server configs expose **camelCase** fields (`sudoPassword`), but the handler still read the pre-3.0 snake_case name (`sudo_password`), which is always `undefined`. Non-interactive sudo therefore failed with `sudo: a terminal is required to authenticate` unless the password was passed explicitly on every call.
28
- - **📁 Same mismatch, same fix for `DEFAULT_DIR` and `ssh_sync` key auth** ([#50](https://github.com/bvisible/mcp-ssh-manager/pull/50)) — `ssh_execute`, `ssh_group_execute` and `ssh_execute_sudo` silently ignored the configured default directory (commands ran in `$HOME`), `ssh_list_servers` always reported an empty `defaultDir`, and `ssh_sync` never passed the configured SSH key to rsync (`-i` / `BatchMode=yes`).
29
- - **🧪 Regression-proofed** — a new test locks the ConfigLoader's output field names (from both `.env` and TOML) and statically forbids stale snake_case field access in `src/`.
30
- - **No configuration change required** — your `.env`/TOML keys are unchanged; existing configs simply start working again.
27
+ - **New opt-in `FORWARD_AGENT` / `forward_agent` option** ([#53](https://github.com/bvisible/mcp-ssh-manager/pull/53) — requested by [@raphaelbahat](https://github.com/raphaelbahat) in [#52](https://github.com/bvisible/mcp-ssh-manager/issues/52)) — enable the equivalent of OpenSSH's `ForwardAgent yes` per server, so processes on the remote host can authenticate to *other* SSH hosts using the keys in your **local** `ssh-agent` (e.g. `git clone` over SSH on a remote server using your local GitHub key), without copying any private key to the server.
28
+ - **Safe by construction** — requires a running local agent (`SSH_AUTH_SOCK`); the flag is ignored when no agent is present, so it never breaks a connection. Boolean parsing treats only `true`/`1`/`yes`/`on` as enabled — `FORWARD_AGENT=false` stays off.
29
+ - **⚠️ Defaults to `false`** — agent forwarding lets anyone with root on the remote host use your loaded keys for the life of the connection, so enable it only for servers you trust. See the new *SSH Agent Forwarding* section in the docs.
31
30
 
32
- [Read full changelog →](CHANGELOG.md#366---2026-07-11)
31
+ ```env
32
+ SSH_SERVER_MYSERVER_FORWARD_AGENT=true
33
+ ```
34
+
35
+ [Read full changelog →](CHANGELOG.md#370---2026-07-13)
33
36
 
34
37
  ---
35
38
 
36
39
  ## Previous Releases
37
40
 
41
+ ### v3.6.7 - Security: command injection fix in the database helpers (July 11, 2026)
42
+
43
+ - **🔒 Every `ssh_db_*` argument is now shell-quoted** ([#51](https://github.com/bvisible/mcp-ssh-manager/pull/51) — responsibly disclosed by **Ugur Ozer, Aeon AI Risk Management** (http://airiskmanagement.ca), see [#48](https://github.com/bvisible/mcp-ssh-manager/issues/48)) — caller-controlled values (`ssh_db_list` most notably, which stayed allowed in `readonly`/`restricted` modes) were interpolated into shell-evaluated strings, allowing arbitrary command execution on the SSH target. A centralized `shellQuote()` now wraps every value across all 15 builders, guarded by a 648-combination injection test. [Full changelog →](CHANGELOG.md#367---2026-07-11)
44
+
45
+ ### v3.6.6 - `SUDO_PASSWORD` / `DEFAULT_DIR` / `ssh_sync` key auth work again (July 11, 2026)
46
+
47
+ - **🔑 camelCase config field reads** ([#50](https://github.com/bvisible/mcp-ssh-manager/pull/50) — thanks [@egoan82](https://github.com/egoan82)) — since the v3.0.0 ConfigLoader refactor, `ssh_execute_sudo` ignored `SUDO_PASSWORD`, `DEFAULT_DIR` was ignored by `ssh_execute`/`ssh_group_execute`/`ssh_list_servers`, and `ssh_sync` never passed the configured SSH key to rsync. All aligned with the loader's camelCase fields, with a regression test locking the loader output shape. [Full changelog →](CHANGELOG.md#366---2026-07-11)
48
+
38
49
  ### v3.6.5 - `ssh_db_query` shell-injection security fix + real row_count (June 30, 2026)
39
50
 
40
51
  - **🔒 Queries are delivered on stdin via a single-quoted heredoc** ([#44](https://github.com/bvisible/mcp-ssh-manager/pull/44), [#45](https://github.com/bvisible/mcp-ssh-manager/pull/45) — thanks [@technophile77](https://github.com/technophile77)) — the remote shell no longer parses backticks/`$(…)` inside queries (which corrupted backtick identifiers **and** let the "SELECT-only" tool run arbitrary shell commands), and `row_count` now reflects each engine's real output instead of counting wrapper lines. [Full changelog →](CHANGELOG.md#365---2026-06-30)
@@ -668,6 +679,7 @@ SSH_SERVER_[NAME]_DESCRIPTION=Description # Optional
668
679
  SSH_SERVER_[NAME]_PLATFORM=windows # Optional: "linux" (default) or "windows"
669
680
  SSH_SERVER_[NAME]_PROXYJUMP=bastion # Optional: name of another server to use as jump host
670
681
  SSH_SERVER_[NAME]_PROXYCOMMAND=command # Optional: custom proxy command (ncat, ssh -W, etc.)
682
+ SSH_SERVER_[NAME]_FORWARD_AGENT=true # Optional: forward local ssh-agent to remote (needs SSH_AUTH_SOCK; security risk — see SSH Agent section)
671
683
 
672
684
  # Example: Linux server
673
685
  SSH_SERVER_PRODUCTION_HOST=prod.example.com
@@ -798,6 +810,25 @@ passphrase = "your_passphrase"
798
810
 
799
811
  > **Note:** SSH Agent is preferred over storing passphrases in config files for better security.
800
812
 
813
+ ### 🔗 SSH Agent Forwarding
814
+
815
+ Enable per-server agent forwarding (the equivalent of OpenSSH's `ForwardAgent yes`) so processes on the remote host can authenticate to *other* SSH hosts using the keys in your **local** `ssh-agent` — e.g. `git clone` over SSH on a remote server using your local GitHub key, without copying any private key to the server.
816
+
817
+ It is **opt-in per server** and defaults to `false`. It requires a running local agent (`SSH_AUTH_SOCK` present); when the agent is unavailable the flag is simply ignored.
818
+
819
+ `.env` format:
820
+ ```env
821
+ SSH_SERVER_MYSERVER_FORWARD_AGENT=true
822
+ ```
823
+
824
+ TOML format:
825
+ ```toml
826
+ [ssh_servers.myserver]
827
+ forward_agent = true
828
+ ```
829
+
830
+ > ⚠️ **Security warning:** agent forwarding lets any process that can read the forwarded agent socket on the remote host — including anyone with **root** there — use your loaded keys to impersonate you against other hosts *for the life of the connection*. Only enable it for servers you trust, mirroring the same caution `ssh_config(5)` advises for `ForwardAgent`.
831
+
801
832
  ## 📚 Advanced Usage
802
833
 
803
834
  ### ProxyJump / Bastion Host
package/SECURITY.md ADDED
@@ -0,0 +1,55 @@
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ Only the latest published `mcp-ssh-manager` release on npm receives security fixes.
6
+ Please upgrade to the newest version before reporting an issue.
7
+
8
+ | Version | Supported |
9
+ | ------- | --------- |
10
+ | latest | ✅ |
11
+ | older | ❌ |
12
+
13
+ ## Reporting a Vulnerability
14
+
15
+ **Please do not report security vulnerabilities through public GitHub issues,
16
+ discussions, or pull requests.**
17
+
18
+ Report privately through either channel:
19
+
20
+ - **GitHub Private Vulnerability Reporting** (preferred) — open the
21
+ [**Security** tab](https://github.com/bvisible/mcp-ssh-manager/security/advisories)
22
+ of this repository and click **Report a vulnerability**. This keeps the report,
23
+ discussion, and any resulting advisory private until a fix is released.
24
+ - **Email** — <security@bvisible.ch> (or <jeremy@bvisible.ch>).
25
+
26
+ Please include, as far as you can:
27
+
28
+ - the affected version and the affected tool(s) or source area,
29
+ - a description of the vulnerability and its impact,
30
+ - a minimal proof of concept or reproduction steps, and
31
+ - any suggested remediation.
32
+
33
+ To keep proof-of-concept work safe, validate against **local package source and
34
+ your own owned test boundary** — do not exercise third-party hosts or
35
+ maintainer infrastructure.
36
+
37
+ ## Disclosure Process
38
+
39
+ - We aim to acknowledge a report within **72 hours**.
40
+ - We will confirm the issue, determine affected versions, and prepare a fix,
41
+ keeping you informed along the way.
42
+ - Fixes are released as a new npm version accompanied by a
43
+ [GitHub Security Advisory](https://github.com/bvisible/mcp-ssh-manager/security/advisories)
44
+ (with a CVE where warranted).
45
+ - We are happy to **credit reporters** in the advisory and release notes.
46
+ Let us know the name/handle you would like used, or if you prefer to remain anonymous.
47
+
48
+ ## Scope Notes
49
+
50
+ `mcp-ssh-manager` executes commands on remote hosts on behalf of an AI assistant.
51
+ Reports are especially valuable when a tool documented as read-only or safe
52
+ (for example `ssh_db_list`, `ssh_db_query`, or any tool permitted under the
53
+ `readonly` / `restricted` per-server security modes) can be made to execute
54
+ arbitrary commands, escalate privileges, or exfiltrate data on the configured
55
+ SSH target.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-ssh-manager",
3
- "version": "3.6.6",
3
+ "version": "3.7.0",
4
4
  "description": "MCP SSH Manager: Model Context Protocol server for SSH remote server management. Control SSH connections from Claude Code and OpenAI Codex - execute commands, transfer files, database operations, backups, health monitoring, and DevOps automation. NEW: Tool activation system reduces context usage by 92%",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -13,7 +13,7 @@
13
13
  "setup": "npm install && pip install -r tools/requirements.txt",
14
14
  "configure": "python tools/server-manager.py",
15
15
  "test-connection": "python tools/test-connection.py",
16
- "test": "npm run test:profiles && npm run test:aliases && npm run test:hooks && npm run test:tools && npm run test:policy && npm run test:ping && npm run test:config && npm run test:fieldnames && npm run test:lifecycle && npm run test:sync && npm run test:dbquoting && npm run test:dbrowcount",
16
+ "test": "npm run test:profiles && npm run test:aliases && npm run test:hooks && npm run test:tools && npm run test:policy && npm run test:ping && npm run test:config && npm run test:fieldnames && npm run test:agentforward && npm run test:lifecycle && npm run test:sync && npm run test:dbquoting && npm run test:dbinjection && npm run test:dbrowcount",
17
17
  "test:profiles": "node tests/test-profiles.js",
18
18
  "test:aliases": "node tests/test-command-aliases.js",
19
19
  "test:hooks": "node tests/test-hooks.js",
@@ -22,9 +22,11 @@
22
22
  "test:ping": "node tests/test-ssh-ping.js",
23
23
  "test:config": "node tests/test-server-config-manager.js",
24
24
  "test:fieldnames": "node tests/test-config-field-names.js",
25
+ "test:agentforward": "node tests/test-agent-forward.js",
25
26
  "test:lifecycle": "node tests/test-lifecycle.js",
26
27
  "test:sync": "node tests/test-sync-stats.js",
27
28
  "test:dbquoting": "node tests/test-database-query-quoting.js",
29
+ "test:dbinjection": "node tests/test-database-injection.js",
28
30
  "test:dbrowcount": "node tests/test-database-row-count.js",
29
31
  "test:all": "npm test && ./scripts/validate.sh",
30
32
  "validate": "./scripts/validate.sh",
@@ -32,6 +32,16 @@ function normalizeMode(raw, serverName) {
32
32
  return normalized;
33
33
  }
34
34
 
35
+ // Parse a boolean-ish config value. Accepts native booleans (TOML) and the
36
+ // strings "true"/"1"/"yes"/"on" (case-insensitive) from .env, where every value
37
+ // is a string. Everything else — "false", "0", "", undefined — is false, so an
38
+ // opt-in flag never turns on by accident.
39
+ function parseBool(raw) {
40
+ if (raw === true) return true;
41
+ if (typeof raw !== 'string') return false;
42
+ return ['true', '1', 'yes', 'on'].includes(raw.trim().toLowerCase());
43
+ }
44
+
35
45
  export class ConfigLoader {
36
46
  constructor() {
37
47
  this.servers = new Map();
@@ -138,6 +148,7 @@ export class ConfigLoader {
138
148
  platform: serverConfig.platform ? serverConfig.platform.toLowerCase() : undefined,
139
149
  proxyJump: serverConfig.proxy_jump,
140
150
  proxyCommand: serverConfig.proxy_command || serverConfig.proxycommand,
151
+ forwardAgent: parseBool(serverConfig.forward_agent),
141
152
  mode,
142
153
  allowPatterns: tomlAllow,
143
154
  denyPatterns: tomlDeny,
@@ -208,6 +219,7 @@ export class ConfigLoader {
208
219
  platform: (env[`SSH_SERVER_${match[1]}_PLATFORM`] || '').toLowerCase() || undefined,
209
220
  proxyJump: env[`SSH_SERVER_${match[1]}_PROXYJUMP`],
210
221
  proxyCommand: env[`SSH_SERVER_${match[1]}_PROXYCOMMAND`],
222
+ forwardAgent: parseBool(env[`SSH_SERVER_${match[1]}_FORWARD_AGENT`]),
211
223
  mode,
212
224
  allowPatterns: envAllow,
213
225
  denyPatterns: envDeny,
@@ -266,6 +278,8 @@ export class ConfigLoader {
266
278
  if (server.platform) serverConfig.platform = server.platform;
267
279
  if (server.proxyJump) serverConfig.proxy_jump = server.proxyJump;
268
280
  if (server.proxyCommand) serverConfig.proxy_command = server.proxyCommand;
281
+ // Only emit when opted in, so generated TOML stays clean by default.
282
+ if (server.forwardAgent) serverConfig.forward_agent = true;
269
283
  // Only emit security fields if they diverge from defaults — keeps generated
270
284
  // TOML files clean for users who never opted in.
271
285
  if (server.mode && server.mode !== 'unrestricted') serverConfig.mode = server.mode;
@@ -10,6 +10,28 @@ export const DB_TYPES = {
10
10
  MONGODB: 'mongodb'
11
11
  };
12
12
 
13
+ // A single quote character as a constant, so shellQuote()'s escaping stays
14
+ // readable under the repo's single-quote lint style.
15
+ const SQ = '\'';
16
+
17
+ /**
18
+ * Quote a value for safe inclusion as a single POSIX shell word.
19
+ *
20
+ * Wraps the value in single quotes and escapes any embedded single quote as
21
+ * '\'' so the remote shell treats it literally — it never interprets $(...),
22
+ * backticks, $VAR, ;, |, &, redirects, spaces, or newlines inside the value.
23
+ * EVERY caller-controlled value interpolated into a database command string
24
+ * MUST go through this: the database/table/collection names, file paths, and
25
+ * connection fields all arrive from tool arguments (issue #48 — command
26
+ * injection via ssh_db_list / ssh_db_dump / ssh_db_import builder arguments).
27
+ * Numbers are coerced to string; null/undefined become an empty quoted word.
28
+ */
29
+ export function shellQuote(value) {
30
+ if (value === null || value === undefined) return SQ + SQ;
31
+ // Replace every ' with '\'' (close quote, escaped quote, reopen), then wrap.
32
+ return SQ + String(value).replace(/'/g, SQ + '\\' + SQ + SQ) + SQ;
33
+ }
34
+
13
35
  /**
14
36
  * Build MySQL dump command
15
37
  */
@@ -27,22 +49,22 @@ export function buildMySQLDumpCommand(options) {
27
49
 
28
50
  let command = 'mysqldump';
29
51
 
30
- if (user) command += ` -u${user}`;
31
- if (password) command += ` -p'${password}'`;
32
- if (host) command += ` -h ${host}`;
33
- if (port) command += ` -P ${port}`;
52
+ if (user) command += ` -u${shellQuote(user)}`;
53
+ if (password) command += ` -p${shellQuote(password)}`;
54
+ if (host) command += ` -h ${shellQuote(host)}`;
55
+ if (port) command += ` -P ${shellQuote(port)}`;
34
56
 
35
57
  command += ' --single-transaction --routines --triggers';
36
- command += ` ${database}`;
58
+ command += ` ${shellQuote(database)}`;
37
59
 
38
60
  if (tables && Array.isArray(tables)) {
39
- command += ` ${tables.join(' ')}`;
61
+ command += ` ${tables.map(shellQuote).join(' ')}`;
40
62
  }
41
63
 
42
64
  if (compress) {
43
- command += ` | gzip > "${outputFile}"`;
65
+ command += ` | gzip > ${shellQuote(outputFile)}`;
44
66
  } else {
45
- command += ` > "${outputFile}"`;
67
+ command += ` > ${shellQuote(outputFile)}`;
46
68
  }
47
69
 
48
70
  return command;
@@ -65,27 +87,27 @@ export function buildPostgreSQLDumpCommand(options) {
65
87
 
66
88
  let command = '';
67
89
  if (password) {
68
- command = `PGPASSWORD='${password}' `;
90
+ command = `PGPASSWORD=${shellQuote(password)} `;
69
91
  }
70
92
 
71
93
  command += 'pg_dump';
72
- if (user) command += ` -U ${user}`;
73
- if (host) command += ` -h ${host}`;
74
- if (port) command += ` -p ${port}`;
94
+ if (user) command += ` -U ${shellQuote(user)}`;
95
+ if (host) command += ` -h ${shellQuote(host)}`;
96
+ if (port) command += ` -p ${shellQuote(port)}`;
75
97
  command += ' --format=custom --clean --if-exists';
76
98
 
77
99
  if (tables && Array.isArray(tables)) {
78
100
  for (const table of tables) {
79
- command += ` -t ${table}`;
101
+ command += ` -t ${shellQuote(table)}`;
80
102
  }
81
103
  }
82
104
 
83
- command += ` ${database}`;
105
+ command += ` ${shellQuote(database)}`;
84
106
 
85
107
  if (compress) {
86
- command += ` | gzip > "${outputFile}"`;
108
+ command += ` | gzip > ${shellQuote(outputFile)}`;
87
109
  } else {
88
- command += ` > "${outputFile}"`;
110
+ command += ` > ${shellQuote(outputFile)}`;
89
111
  }
90
112
 
91
113
  return command;
@@ -107,23 +129,23 @@ export function buildMongoDBDumpCommand(options) {
107
129
  } = options;
108
130
 
109
131
  let command = 'mongodump';
110
- if (host) command += ` --host ${host}`;
111
- if (port) command += ` --port ${port}`;
112
- if (user) command += ` --username ${user}`;
113
- if (password) command += ` --password '${password}'`;
114
- if (database) command += ` --db ${database}`;
132
+ if (host) command += ` --host ${shellQuote(host)}`;
133
+ if (port) command += ` --port ${shellQuote(port)}`;
134
+ if (user) command += ` --username ${shellQuote(user)}`;
135
+ if (password) command += ` --password ${shellQuote(password)}`;
136
+ if (database) command += ` --db ${shellQuote(database)}`;
115
137
 
116
138
  if (collections && Array.isArray(collections)) {
117
139
  for (const collection of collections) {
118
- command += ` --collection ${collection}`;
140
+ command += ` --collection ${shellQuote(collection)}`;
119
141
  }
120
142
  }
121
143
 
122
- command += ` --out "${outputDir}"`;
144
+ command += ` --out ${shellQuote(outputDir)}`;
123
145
 
124
146
  if (compress) {
125
- command += ` && tar -czf "${outputDir}.tar.gz" -C "$(dirname ${outputDir})" "$(basename ${outputDir})"`;
126
- command += ` && rm -rf "${outputDir}"`;
147
+ command += ` && tar -czf ${shellQuote(outputDir + '.tar.gz')} -C "$(dirname ${shellQuote(outputDir)})" "$(basename ${shellQuote(outputDir)})"`;
148
+ command += ` && rm -rf ${shellQuote(outputDir)}`;
127
149
  }
128
150
 
129
151
  return command;
@@ -145,17 +167,17 @@ export function buildMySQLImportCommand(options) {
145
167
  let command = '';
146
168
 
147
169
  if (inputFile.endsWith('.gz')) {
148
- command = `gunzip -c "${inputFile}" | `;
170
+ command = `gunzip -c ${shellQuote(inputFile)} | `;
149
171
  } else {
150
- command = `cat "${inputFile}" | `;
172
+ command = `cat ${shellQuote(inputFile)} | `;
151
173
  }
152
174
 
153
175
  command += 'mysql';
154
- if (user) command += ` -u${user}`;
155
- if (password) command += ` -p'${password}'`;
156
- if (host) command += ` -h ${host}`;
157
- if (port) command += ` -P ${port}`;
158
- command += ` ${database}`;
176
+ if (user) command += ` -u${shellQuote(user)}`;
177
+ if (password) command += ` -p${shellQuote(password)}`;
178
+ if (host) command += ` -h ${shellQuote(host)}`;
179
+ if (port) command += ` -P ${shellQuote(port)}`;
180
+ command += ` ${shellQuote(database)}`;
159
181
 
160
182
  return command;
161
183
  }
@@ -175,20 +197,20 @@ export function buildPostgreSQLImportCommand(options) {
175
197
 
176
198
  let command = '';
177
199
  if (password) {
178
- command = `PGPASSWORD='${password}' `;
200
+ command = `PGPASSWORD=${shellQuote(password)} `;
179
201
  }
180
202
 
181
203
  command += 'pg_restore';
182
- if (user) command += ` -U ${user}`;
183
- if (host) command += ` -h ${host}`;
184
- if (port) command += ` -p ${port}`;
204
+ if (user) command += ` -U ${shellQuote(user)}`;
205
+ if (host) command += ` -h ${shellQuote(host)}`;
206
+ if (port) command += ` -p ${shellQuote(port)}`;
185
207
  command += ' --clean --if-exists';
186
- command += ` -d ${database}`;
208
+ command += ` -d ${shellQuote(database)}`;
187
209
 
188
210
  if (inputFile.endsWith('.gz')) {
189
- command = `gunzip -c "${inputFile}" | ${command}`;
211
+ command = `gunzip -c ${shellQuote(inputFile)} | ${command}`;
190
212
  } else {
191
- command += ` "${inputFile}"`;
213
+ command += ` ${shellQuote(inputFile)}`;
192
214
  }
193
215
 
194
216
  return command;
@@ -211,23 +233,23 @@ export function buildMongoDBRestoreCommand(options) {
211
233
 
212
234
  if (inputPath.endsWith('.tar.gz')) {
213
235
  const extractDir = inputPath.replace('.tar.gz', '');
214
- command = `tar -xzf "${inputPath}" -C "$(dirname ${inputPath})" && `;
236
+ command = `tar -xzf ${shellQuote(inputPath)} -C "$(dirname ${shellQuote(inputPath)})" && `;
215
237
  command += 'mongorestore';
216
238
  if (drop) command += ' --drop';
217
- if (host) command += ` --host ${host}`;
218
- if (port) command += ` --port ${port}`;
219
- if (user) command += ` --username ${user}`;
220
- if (password) command += ` --password '${password}'`;
221
- command += ` "${extractDir}"`;
222
- command += ` && rm -rf "${extractDir}"`;
239
+ if (host) command += ` --host ${shellQuote(host)}`;
240
+ if (port) command += ` --port ${shellQuote(port)}`;
241
+ if (user) command += ` --username ${shellQuote(user)}`;
242
+ if (password) command += ` --password ${shellQuote(password)}`;
243
+ command += ` ${shellQuote(extractDir)}`;
244
+ command += ` && rm -rf ${shellQuote(extractDir)}`;
223
245
  } else {
224
246
  command = 'mongorestore';
225
247
  if (drop) command += ' --drop';
226
- if (host) command += ` --host ${host}`;
227
- if (port) command += ` --port ${port}`;
228
- if (user) command += ` --username ${user}`;
229
- if (password) command += ` --password '${password}'`;
230
- command += ` "${inputPath}"`;
248
+ if (host) command += ` --host ${shellQuote(host)}`;
249
+ if (port) command += ` --port ${shellQuote(port)}`;
250
+ if (user) command += ` --username ${shellQuote(user)}`;
251
+ if (password) command += ` --password ${shellQuote(password)}`;
252
+ command += ` ${shellQuote(inputPath)}`;
231
253
  }
232
254
 
233
255
  return command;
@@ -240,10 +262,10 @@ export function buildMySQLListDatabasesCommand(options) {
240
262
  const { user, password, host = 'localhost', port = 3306 } = options;
241
263
 
242
264
  let command = 'mysql';
243
- if (user) command += ` -u${user}`;
244
- if (password) command += ` -p'${password}'`;
245
- if (host) command += ` -h ${host}`;
246
- if (port) command += ` -P ${port}`;
265
+ if (user) command += ` -u${shellQuote(user)}`;
266
+ if (password) command += ` -p${shellQuote(password)}`;
267
+ if (host) command += ` -h ${shellQuote(host)}`;
268
+ if (port) command += ` -P ${shellQuote(port)}`;
247
269
  command += ' -e "SHOW DATABASES;" | tail -n +2';
248
270
 
249
271
  return command;
@@ -256,11 +278,14 @@ export function buildMySQLListTablesCommand(options) {
256
278
  const { database, user, password, host = 'localhost', port = 3306 } = options;
257
279
 
258
280
  let command = 'mysql';
259
- if (user) command += ` -u${user}`;
260
- if (password) command += ` -p'${password}'`;
261
- if (host) command += ` -h ${host}`;
262
- if (port) command += ` -P ${port}`;
263
- command += ` -e "USE ${database}; SHOW TABLES;" | tail -n +2`;
281
+ if (user) command += ` -u${shellQuote(user)}`;
282
+ if (password) command += ` -p${shellQuote(password)}`;
283
+ if (host) command += ` -h ${shellQuote(host)}`;
284
+ if (port) command += ` -P ${shellQuote(port)}`;
285
+ // Pass the database as a shell-quoted positional argument instead of
286
+ // interpolating it into the -e SQL, so the name can inject neither the
287
+ // shell nor the SQL (a crafted USE clause).
288
+ command += ` ${shellQuote(database)} -e "SHOW TABLES;" | tail -n +2`;
264
289
 
265
290
  return command;
266
291
  }
@@ -273,13 +298,13 @@ export function buildPostgreSQLListDatabasesCommand(options) {
273
298
 
274
299
  let command = '';
275
300
  if (password) {
276
- command = `PGPASSWORD='${password}' `;
301
+ command = `PGPASSWORD=${shellQuote(password)} `;
277
302
  }
278
303
 
279
304
  command += 'psql';
280
- if (user) command += ` -U ${user}`;
281
- if (host) command += ` -h ${host}`;
282
- if (port) command += ` -p ${port}`;
305
+ if (user) command += ` -U ${shellQuote(user)}`;
306
+ if (host) command += ` -h ${shellQuote(host)}`;
307
+ if (port) command += ` -p ${shellQuote(port)}`;
283
308
  command += ' -t -c "SELECT datname FROM pg_database WHERE datistemplate = false;" | sed \'/^$/d\' | sed \'s/^[ \\t]*//\'';
284
309
 
285
310
  return command;
@@ -293,14 +318,14 @@ export function buildPostgreSQLListTablesCommand(options) {
293
318
 
294
319
  let command = '';
295
320
  if (password) {
296
- command = `PGPASSWORD='${password}' `;
321
+ command = `PGPASSWORD=${shellQuote(password)} `;
297
322
  }
298
323
 
299
324
  command += 'psql';
300
- if (user) command += ` -U ${user}`;
301
- if (host) command += ` -h ${host}`;
302
- if (port) command += ` -p ${port}`;
303
- command += ` -d ${database}`;
325
+ if (user) command += ` -U ${shellQuote(user)}`;
326
+ if (host) command += ` -h ${shellQuote(host)}`;
327
+ if (port) command += ` -p ${shellQuote(port)}`;
328
+ command += ` -d ${shellQuote(database)}`;
304
329
  command += ' -t -c "SELECT tablename FROM pg_tables WHERE schemaname = \'public\';" | sed \'/^$/d\' | sed \'s/^[ \\t]*//\'';
305
330
 
306
331
  return command;
@@ -313,10 +338,10 @@ export function buildMongoDBListDatabasesCommand(options) {
313
338
  const { user, password, host = 'localhost', port = 27017 } = options;
314
339
 
315
340
  let command = 'mongo';
316
- if (host) command += ` --host ${host}`;
317
- if (port) command += ` --port ${port}`;
318
- if (user) command += ` --username ${user}`;
319
- if (password) command += ` --password '${password}'`;
341
+ if (host) command += ` --host ${shellQuote(host)}`;
342
+ if (port) command += ` --port ${shellQuote(port)}`;
343
+ if (user) command += ` --username ${shellQuote(user)}`;
344
+ if (password) command += ` --password ${shellQuote(password)}`;
320
345
  command += ' --quiet --eval "db.adminCommand(\'listDatabases\').databases.forEach(function(d){print(d.name)})"';
321
346
 
322
347
  return command;
@@ -329,11 +354,11 @@ export function buildMongoDBListCollectionsCommand(options) {
329
354
  const { database, user, password, host = 'localhost', port = 27017 } = options;
330
355
 
331
356
  let command = 'mongo';
332
- if (host) command += ` --host ${host}`;
333
- if (port) command += ` --port ${port}`;
334
- if (user) command += ` --username ${user}`;
335
- if (password) command += ` --password '${password}'`;
336
- command += ` ${database}`;
357
+ if (host) command += ` --host ${shellQuote(host)}`;
358
+ if (port) command += ` --port ${shellQuote(port)}`;
359
+ if (user) command += ` --username ${shellQuote(user)}`;
360
+ if (password) command += ` --password ${shellQuote(password)}`;
361
+ command += ` ${shellQuote(database)}`;
337
362
  command += ' --quiet --eval "db.getCollectionNames().forEach(function(c){print(c)})"';
338
363
 
339
364
  return command;
@@ -386,11 +411,11 @@ export function buildMySQLQueryCommand(options) {
386
411
  }
387
412
 
388
413
  let command = 'mysql';
389
- if (user) command += ` -u${user}`;
390
- if (password) command += ` -p'${password}'`;
391
- if (host) command += ` -h ${host}`;
392
- if (port) command += ` -P ${port}`;
393
- command += ` ${database}`;
414
+ if (user) command += ` -u${shellQuote(user)}`;
415
+ if (password) command += ` -p${shellQuote(password)}`;
416
+ if (host) command += ` -h ${shellQuote(host)}`;
417
+ if (port) command += ` -P ${shellQuote(port)}`;
418
+ command += ` ${shellQuote(database)}`;
394
419
 
395
420
  // Feed the SQL via stdin (quoted heredoc) so the remote shell never parses it —
396
421
  // backtick-quoted identifiers and `$` survive intact, and query text cannot inject
@@ -419,14 +444,14 @@ export function buildPostgreSQLQueryCommand(options) {
419
444
 
420
445
  let command = '';
421
446
  if (password) {
422
- command = `PGPASSWORD='${password}' `;
447
+ command = `PGPASSWORD=${shellQuote(password)} `;
423
448
  }
424
449
 
425
450
  command += 'psql';
426
- if (user) command += ` -U ${user}`;
427
- if (host) command += ` -h ${host}`;
428
- if (port) command += ` -p ${port}`;
429
- command += ` -d ${database}`;
451
+ if (user) command += ` -U ${shellQuote(user)}`;
452
+ if (host) command += ` -h ${shellQuote(host)}`;
453
+ if (port) command += ` -p ${shellQuote(port)}`;
454
+ command += ` -d ${shellQuote(database)}`;
430
455
  // Feed SQL via stdin (quoted heredoc) instead of `-c "${query}"` so the remote shell
431
456
  // never parses it. See buildHeredoc and issue #44.
432
457
  command += buildHeredoc(query);
@@ -441,11 +466,11 @@ export function buildMongoDBQueryCommand(options) {
441
466
  const { database, collection, query, user, password, host = 'localhost', port = 27017 } = options;
442
467
 
443
468
  let command = 'mongo';
444
- if (host) command += ` --host ${host}`;
445
- if (port) command += ` --port ${port}`;
446
- if (user) command += ` --username ${user}`;
447
- if (password) command += ` --password '${password}'`;
448
- command += ` ${database}`;
469
+ if (host) command += ` --host ${shellQuote(host)}`;
470
+ if (port) command += ` --port ${shellQuote(port)}`;
471
+ if (user) command += ` --username ${shellQuote(user)}`;
472
+ if (password) command += ` --password ${shellQuote(password)}`;
473
+ command += ` ${shellQuote(database)}`;
449
474
  // Feed the JS script via stdin (quoted heredoc) instead of `--eval "..."` so the
450
475
  // remote shell never expands backticks/`$` in the query. mongo still evaluates the
451
476
  // script as JavaScript (expected). See buildHeredoc and issue #44.
@@ -152,6 +152,13 @@ class SSHManager {
152
152
  // Use ssh-agent if available (handles passphrase-protected keys transparently)
153
153
  if (process.env.SSH_AUTH_SOCK) {
154
154
  connConfig.agent = process.env.SSH_AUTH_SOCK;
155
+ // Opt-in per-server agent forwarding. ssh2 requires `agent` to be set,
156
+ // so we only enable it inside this block — otherwise ssh2 throws at
157
+ // connect. With allowAgentFwd on, every exec/shell channel forwards the
158
+ // agent automatically, so no per-command change is needed.
159
+ if (this.config.forwardAgent) {
160
+ connConfig.agentForward = true;
161
+ }
155
162
  }
156
163
 
157
164
  // Add authentication (support both keyPath and keypath for compatibility)