mcp-ssh-manager 3.8.4 → 3.8.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/CHANGELOG.md CHANGED
@@ -5,6 +5,22 @@ 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.8.5] - 2026-08-28
9
+
10
+ ### Security
11
+
12
+ Three reported advisories, all the same class of bug, all confirmed present in 3.8.4 and fixed here. The v3.6.7 fix (CVE-2026-77383) introduced `shellQuote()` but applied it to `src/database-manager.js` only; the parallel builders for backups and monitoring were never covered.
13
+
14
+ - **RCE through every `ssh_backup_*` builder** (GHSA-qwwm-vrm9-4mw8, high). `src/backup-manager.js` concatenated `database`, `dbUser`, `dbPassword`, `dbHost`, `backupDir`, `paths` and `exclude` into shell strings with no escaping — 0 uses of `shellQuote` across 9 builders. Arbitrary command execution as the SSH user on every managed server.
15
+ - **RCE through `ssh_db_dump` and the MongoDB backup path** (GHSA-796j-h5q5-jx6p, critical). The follow-up `stat` command interpolated `outputFile` raw, after the dump itself had been fixed — the earlier patch stopped one line short.
16
+ - **RCE bypassing readonly/restricted mode** (GHSA-m793-whw6-f537, critical). `ssh_service_status` and `ssh_tail` are read-only, so they stay enabled on servers the operator locked down — and neither quoted its arguments nor consulted the policy layer. `buildServiceStatusCommand` interpolated the service name unquoted six times; `ssh_tail` built `tail -n ${lines} "${file}" | grep "${grep}"` with double quotes only, so a `"` breakout ran. **This defeated the exact control those modes exist to provide**, and the README had just started advertising them.
17
+
18
+ Fixes: `shellQuote()` extracted to `src/shell-quote.js` and applied across `backup-manager.js` (54 call sites), `health-monitor.js` and the remaining inline commands in `index.js`; a `safeInteger()` helper for numeric arguments that still land in command strings; `buildProcessInfoCommand` now validates its PID like `buildKillProcessCommand` always did; and `ssh_tail` and `ssh_service_status` now call the policy layer.
19
+
20
+ Guarded by `npm run test:backupinjection`: **340 builder × argument × payload combinations** driven through a real `/bin/sh` with a canary file, asserting no payload ever executes. Verified by mutation — removing any single quote-call is caught.
21
+
22
+ **Upgrade if you use `ssh_backup_*`, `ssh_db_dump`, `ssh_service_status` or `ssh_tail`, and especially if you rely on `readonly` or `restricted` mode.**
23
+
8
24
  ## [3.8.4] - 2026-08-28
9
25
 
10
26
  ### Security
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.8.4-brightgreen?style=for-the-badge)](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v3.8.4)
9
+ [![Version](https://img.shields.io/badge/Version-3.8.5-brightgreen?style=for-the-badge)](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v3.8.5)
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)
@@ -23,16 +23,19 @@ A Model Context Protocol (MCP) server that enables **Claude Code** and **OpenAI
23
23
 
24
24
  ---
25
25
 
26
- ## 🎉 What's New in v3.8.4
26
+ ## 🎉 What's New in v3.8.5
27
27
 
28
- **🔒 The logger stops writing secrets in clear text, and static analysis now runs on every commit** (Released: August 28, 2026)
28
+ **🔒 Security release — three command-injection advisories fixed, one of which defeated `readonly` mode** (Released: August 28, 2026)
29
29
 
30
- - **🔒 Security: secrets are redacted inside the logger.** It writes to two places outside your control — `~/.ssh-manager.log` and stderr, which your MCP host captures — so a single call site handing it a whole server config would have persisted a production password on disk. Redaction now happens structurally: any `password` / `passphrase` / `secret` / `token` / `credential` / private key / API key field becomes `[redacted]`, at any depth, in arrays, whatever the casing. No call site can leak one.
31
- - **🔍 CodeQL runs on every push and pull request.** For a server that turns model output into shell commands on production hosts, "we read it carefully" is not an answer. It found every fix in this release on its first run — **`src/` now has zero open findings**.
32
- - **🛡️ Every GitHub action pinned to a commit SHA**, including one that tracked a moving branch inside a workflow with read access to the whole repository. Closes 17 of the 22 OpenSSF Scorecard findings.
33
- - **🐛 `examples/backup-workflow.js` never parsed** — a cron `*/6` inside a block comment closed it early — and called a function that does not exist. It was documentation, not a JavaScript API, and it shipped in the npm tarball. It is now `examples/backup-workflow.md`. `scripts/validate.sh` checks all 49 tracked `.js` files instead of 2, which is how that hid for months.
30
+ **Upgrade if you use `ssh_backup_*`, `ssh_db_dump`, `ssh_service_status` or `ssh_tail` — and especially if you rely on the `readonly` / `restricted` security modes.**
34
31
 
35
- [Read full changelog →](CHANGELOG.md#384---2026-08-28)
32
+ - **🔴 RCE bypassing `readonly` / `restricted`** (GHSA-m793-whw6-f537) — `ssh_service_status` and `ssh_tail` are read-only, so they stay enabled on servers you locked down, and neither quoted its arguments nor consulted the policy layer. A service name like `nginx; id > /tmp/pwned` executed. This defeated the exact control those modes exist to provide.
33
+ - **🔴 RCE through `ssh_db_dump`** (GHSA-796j-h5q5-jx6p) — the `stat` command run after the dump interpolated the output path raw. The v3.6.7 patch had stopped one line short.
34
+ - **🟠 RCE through every `ssh_backup_*` tool** (GHSA-qwwm-vrm9-4mw8) — `backup-manager.js` had **zero** shell escaping across its 9 builders, while `database-manager.js` had 95. The v3.6.7 fix was never extended to it.
35
+
36
+ The quoting helper now lives in one module (`src/shell-quote.js`) so "did this builder quote its inputs?" has a single answer, and a new test drives **340 builder × argument × payload combinations** through a real shell to prove none of them execute.
37
+
38
+ [Read full changelog →](CHANGELOG.md#385---2026-08-28)
36
39
 
37
40
  ---
38
41
 
@@ -75,7 +78,11 @@ Alongside that:
75
78
  ## Previous Releases
76
79
 
77
80
  <details>
78
- <summary><b>📜 Release history — v3.8.3 down to v1.0.0</b> (click to expand)</summary>
81
+ <summary><b>📜 Release history — v3.8.4 down to v1.0.0</b> (click to expand)</summary>
82
+
83
+ ### v3.8.4 - Secrets stop reaching the log, CodeQL on every commit (August 28, 2026)
84
+
85
+ - **🔒 The logger no longer writes secrets in clear text** — it writes to `~/.ssh-manager.log` and stderr (which your MCP host captures), so one call site handing it a server config would have persisted a production password. Redaction now happens inside the logger. Also: CodeQL on every push, every action pinned by SHA, and a broken example that never parsed. [Full changelog →](CHANGELOG.md#384---2026-08-28)
79
86
 
80
87
  ### v3.8.2 / v3.8.3 - Sudo password leak fixed, MCP Registry, signed releases (August 28, 2026)
81
88
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-ssh-manager",
3
- "version": "3.8.4",
3
+ "version": "3.8.5",
4
4
  "mcpName": "io.github.bvisible/mcp-ssh-manager",
5
5
  "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%",
6
6
  "main": "src/index.js",
@@ -14,7 +14,7 @@
14
14
  "setup": "npm install && pip install -r tools/requirements.txt",
15
15
  "configure": "python tools/server-manager.py",
16
16
  "test-connection": "python tools/test-connection.py",
17
- "test": "npm run test:lockfile && npm run test:sudostdin && npm run test:redaction && 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:groups && npm run test:agentforward && npm run test:lifecycle && npm run test:tunnel && npm run test:sync && npm run test:sync-path && npm run test:dbquoting && npm run test:dbinjection && npm run test:dbrowcount",
17
+ "test": "npm run test:lockfile && npm run test:sudostdin && npm run test:redaction && 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:groups && npm run test:agentforward && npm run test:lifecycle && npm run test:tunnel && npm run test:sync && npm run test:sync-path && npm run test:dbquoting && npm run test:dbinjection && npm run test:backupinjection && npm run test:dbrowcount",
18
18
  "test:lockfile": "node tests/test-lockfile.js",
19
19
  "test:sudostdin": "node tests/test-sudo-stdin.js",
20
20
  "test:redaction": "node tests/test-logger-redaction.js",
@@ -34,6 +34,7 @@
34
34
  "test:sync-path": "node tests/test-rsync-path.js",
35
35
  "test:dbquoting": "node tests/test-database-query-quoting.js",
36
36
  "test:dbinjection": "node tests/test-database-injection.js",
37
+ "test:backupinjection": "node tests/test-backup-monitor-injection.js",
37
38
  "test:dbrowcount": "node tests/test-database-row-count.js",
38
39
  "test:all": "npm test && npm run typecheck && ./scripts/validate.sh",
39
40
  "validate": "./scripts/validate.sh",
@@ -16,17 +16,23 @@ if ! command -v node &> /dev/null; then
16
16
  exit 1
17
17
  fi
18
18
 
19
- # Install pre-commit
19
+ # Versions are pinned on purpose. An unpinned install in a setup script hands
20
+ # every contributor whatever version is current that day, and the tools below
21
+ # gate commits — a silent major bump changes what passes.
20
22
  echo "📦 Installing pre-commit..."
21
- pip install pre-commit
23
+ pip install 'pre-commit==4.0.1'
22
24
 
23
- # Install Node.js dev dependencies
24
- echo "📦 Installing Node.js linting tools..."
25
- npm install --save-dev eslint prettier
25
+ # eslint and prettier are already devDependencies, at versions the CI gates
26
+ # depend on. `npm install --save-dev eslint prettier` would re-resolve both to
27
+ # their latest majors (ESLint 10 over the pinned ^8.56.0) and rewrite
28
+ # package.json in the contributor's working tree. npm ci installs exactly what
29
+ # package-lock.json pins.
30
+ echo "📦 Installing Node.js dev dependencies from the lockfile..."
31
+ npm ci
26
32
 
27
33
  # Install Python linting tools
28
34
  echo "📦 Installing Python linting tools..."
29
- pip install black flake8 isort
35
+ pip install 'black==24.10.0' 'flake8==7.1.1' 'isort==5.13.2'
30
36
 
31
37
  # Install pre-commit hooks
32
38
  echo "🔗 Installing git hooks..."
@@ -34,7 +40,10 @@ pre-commit install
34
40
 
35
41
  # Create secrets baseline
36
42
  echo "🔐 Creating secrets baseline..."
37
- pip install detect-secrets
43
+ # Pinned: an unpinned install in a setup script gives every developer whatever
44
+ # version is current that day, and this one writes the secrets baseline the
45
+ # pre-commit hooks then trust.
46
+ pip install 'detect-secrets==1.5.0'
38
47
  detect-secrets scan > .secrets.baseline
39
48
 
40
49
  # Run hooks on all files (optional first run)
package/server.json CHANGED
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/bvisible/mcp-ssh-manager",
7
7
  "source": "github"
8
8
  },
9
- "version": "3.8.4",
9
+ "version": "3.8.5",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "mcp-ssh-manager",
14
- "version": "3.8.4",
14
+ "version": "3.8.5",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },
@@ -7,6 +7,7 @@
7
7
  import path from 'path';
8
8
  import crypto from 'crypto';
9
9
  import { logger } from './logger.js';
10
+ import { shellQuote, safeInteger } from './shell-quote.js';
10
11
 
11
12
  // Backup types
12
13
  export const BACKUP_TYPES = {
@@ -61,23 +62,23 @@ export function buildMySQLDumpCommand(options) {
61
62
  let command = 'mysqldump';
62
63
 
63
64
  // Connection parameters
64
- if (user) command += ` -u${user}`;
65
- if (password) command += ` -p'${password}'`;
66
- if (host) command += ` -h ${host}`;
67
- if (port) command += ` -P ${port}`;
65
+ if (user) command += ` -u${shellQuote(user)}`;
66
+ if (password) command += ` -p${shellQuote(password)}`;
67
+ if (host) command += ` -h ${shellQuote(host)}`;
68
+ if (port) command += ` -P ${safeInteger(port, 3306)}`;
68
69
 
69
70
  // Dump options
70
71
  if (singleTransaction) command += ' --single-transaction';
71
72
  command += ' --routines --triggers';
72
73
 
73
74
  // Database name
74
- command += ` ${database}`;
75
+ command += ` ${shellQuote(database)}`;
75
76
 
76
77
  // Output handling
77
78
  if (compress) {
78
- command += ` | gzip > "${outputFile}"`;
79
+ command += ` | gzip > ${shellQuote(outputFile)}`;
79
80
  } else {
80
- command += ` > "${outputFile}"`;
81
+ command += ` > ${shellQuote(outputFile)}`;
81
82
  }
82
83
 
83
84
  return command;
@@ -100,27 +101,27 @@ export function buildPostgreSQLDumpCommand(options) {
100
101
  // PostgreSQL uses PGPASSWORD environment variable
101
102
  let command = '';
102
103
  if (password) {
103
- command = `PGPASSWORD='${password}' `;
104
+ command = `PGPASSWORD=${shellQuote(password)} `;
104
105
  }
105
106
 
106
107
  command += 'pg_dump';
107
108
 
108
109
  // Connection parameters
109
- if (user) command += ` -U ${user}`;
110
- if (host) command += ` -h ${host}`;
111
- if (port) command += ` -p ${port}`;
110
+ if (user) command += ` -U ${shellQuote(user)}`;
111
+ if (host) command += ` -h ${shellQuote(host)}`;
112
+ if (port) command += ` -p ${safeInteger(port, 5432)}`;
112
113
 
113
114
  // Dump options
114
115
  command += ' --format=custom --clean --if-exists';
115
116
 
116
117
  // Database name
117
- command += ` ${database}`;
118
+ command += ` ${shellQuote(database)}`;
118
119
 
119
120
  // Output handling
120
121
  if (compress) {
121
- command += ` | gzip > "${outputFile}"`;
122
+ command += ` | gzip > ${shellQuote(outputFile)}`;
122
123
  } else {
123
- command += ` > "${outputFile}"`;
124
+ command += ` > ${shellQuote(outputFile)}`;
124
125
  }
125
126
 
126
127
  return command;
@@ -143,22 +144,24 @@ export function buildMongoDBDumpCommand(options) {
143
144
  let command = 'mongodump';
144
145
 
145
146
  // Connection parameters
146
- if (host) command += ` --host ${host}`;
147
- if (port) command += ` --port ${port}`;
148
- if (user) command += ` --username ${user}`;
149
- if (password) command += ` --password '${password}'`;
147
+ if (host) command += ` --host ${shellQuote(host)}`;
148
+ if (port) command += ` --port ${safeInteger(port, 27017)}`;
149
+ if (user) command += ` --username ${shellQuote(user)}`;
150
+ if (password) command += ` --password ${shellQuote(password)}`;
150
151
 
151
152
  // Database selection
152
- if (database) command += ` --db ${database}`;
153
+ if (database) command += ` --db ${shellQuote(database)}`;
153
154
 
154
155
  // Output directory
155
- command += ` --out "${outputDir}"`;
156
+ command += ` --out ${shellQuote(outputDir)}`;
156
157
 
157
158
  // Compress the output directory
158
159
  if (compress) {
159
160
  const archiveName = `${outputDir}.tar.gz`;
160
- command += ` && tar -czf "${archiveName}" -C "$(dirname ${outputDir})" "$(basename ${outputDir})"`;
161
- command += ` && rm -rf "${outputDir}"`;
161
+ // dirname/basename receive the quoted value, so the substitution itself
162
+ // cannot be steered by the caller.
163
+ command += ` && tar -czf ${shellQuote(archiveName)} -C "$(dirname ${shellQuote(outputDir)})" "$(basename ${shellQuote(outputDir)})"`;
164
+ command += ` && rm -rf ${shellQuote(outputDir)}`;
162
165
  }
163
166
 
164
167
  return command;
@@ -189,15 +192,15 @@ export function buildFilesBackupCommand(options) {
189
192
  }
190
193
 
191
194
  // Output file
192
- command += ` "${outputFile}"`;
195
+ command += ` ${shellQuote(outputFile)}`;
193
196
 
194
197
  // Exclude patterns
195
198
  for (const pattern of exclude) {
196
- command += ` --exclude="${pattern}"`;
199
+ command += ` --exclude=${shellQuote(pattern)}`;
197
200
  }
198
201
 
199
202
  // Paths to backup
200
- command += ` ${paths.map(p => `"${p}"`).join(' ')}`;
203
+ command += ` ${paths.map(p => shellQuote(p)).join(' ')}`;
201
204
 
202
205
  return command;
203
206
  }
@@ -236,19 +239,19 @@ function buildMySQLRestoreCommand(backupFile, options) {
236
239
 
237
240
  // Decompress if needed
238
241
  if (backupFile.endsWith('.gz')) {
239
- command = `gunzip -c "${backupFile}" | `;
242
+ command = `gunzip -c ${shellQuote(backupFile)} | `;
240
243
  } else {
241
- command = `cat "${backupFile}" | `;
244
+ command = `cat ${shellQuote(backupFile)} | `;
242
245
  }
243
246
 
244
247
  command += 'mysql';
245
248
 
246
249
  // Connection parameters
247
- if (user) command += ` -u${user}`;
248
- if (password) command += ` -p'${password}'`;
249
- if (host) command += ` -h ${host}`;
250
- if (port) command += ` -P ${port}`;
251
- if (database) command += ` ${database}`;
250
+ if (user) command += ` -u${shellQuote(user)}`;
251
+ if (password) command += ` -p${shellQuote(password)}`;
252
+ if (host) command += ` -h ${shellQuote(host)}`;
253
+ if (port) command += ` -P ${safeInteger(port, 3306)}`;
254
+ if (database) command += ` ${shellQuote(database)}`;
252
255
 
253
256
  return command;
254
257
  }
@@ -267,25 +270,25 @@ function buildPostgreSQLRestoreCommand(backupFile, options) {
267
270
 
268
271
  let command = '';
269
272
  if (password) {
270
- command = `PGPASSWORD='${password}' `;
273
+ command = `PGPASSWORD=${shellQuote(password)} `;
271
274
  }
272
275
 
273
276
  command += 'pg_restore';
274
277
 
275
278
  // Connection parameters
276
- if (user) command += ` -U ${user}`;
277
- if (host) command += ` -h ${host}`;
278
- if (port) command += ` -p ${port}`;
279
- if (database) command += ` -d ${database}`;
279
+ if (user) command += ` -U ${shellQuote(user)}`;
280
+ if (host) command += ` -h ${shellQuote(host)}`;
281
+ if (port) command += ` -p ${safeInteger(port, 5432)}`;
282
+ if (database) command += ` -d ${shellQuote(database)}`;
280
283
 
281
284
  // Restore options
282
285
  command += ' --clean --if-exists';
283
286
 
284
287
  // Handle compressed files
285
288
  if (backupFile.endsWith('.gz')) {
286
- command = `gunzip -c "${backupFile}" | ${command}`;
289
+ command = `gunzip -c ${shellQuote(backupFile)} | ${command}`;
287
290
  } else {
288
- command += ` "${backupFile}"`;
291
+ command += ` ${shellQuote(backupFile)}`;
289
292
  }
290
293
 
291
294
  return command;
@@ -308,25 +311,25 @@ function buildMongoDBRestoreCommand(backupFile, options) {
308
311
  // Extract if compressed
309
312
  if (backupFile.endsWith('.tar.gz')) {
310
313
  const extractDir = backupFile.replace('.tar.gz', '');
311
- command = `tar -xzf "${backupFile}" -C "$(dirname ${backupFile})" && `;
314
+ command = `tar -xzf ${shellQuote(backupFile)} -C "$(dirname ${shellQuote(backupFile)})" && `;
312
315
  command += 'mongorestore';
313
316
 
314
317
  if (drop) command += ' --drop';
315
- if (host) command += ` --host ${host}`;
316
- if (port) command += ` --port ${port}`;
317
- if (user) command += ` --username ${user}`;
318
- if (password) command += ` --password '${password}'`;
318
+ if (host) command += ` --host ${shellQuote(host)}`;
319
+ if (port) command += ` --port ${safeInteger(port, 27017)}`;
320
+ if (user) command += ` --username ${shellQuote(user)}`;
321
+ if (password) command += ` --password ${shellQuote(password)}`;
319
322
 
320
- command += ` "${extractDir}"`;
321
- command += ` && rm -rf "${extractDir}"`;
323
+ command += ` ${shellQuote(extractDir)}`;
324
+ command += ` && rm -rf ${shellQuote(extractDir)}`;
322
325
  } else {
323
326
  command = 'mongorestore';
324
327
  if (drop) command += ' --drop';
325
- if (host) command += ` --host ${host}`;
326
- if (port) command += ` --port ${port}`;
327
- if (user) command += ` --username ${user}`;
328
- if (password) command += ` --password '${password}'`;
329
- command += ` "${backupFile}"`;
328
+ if (host) command += ` --host ${shellQuote(host)}`;
329
+ if (port) command += ` --port ${safeInteger(port, 27017)}`;
330
+ if (user) command += ` --username ${shellQuote(user)}`;
331
+ if (password) command += ` --password ${shellQuote(password)}`;
332
+ command += ` ${shellQuote(backupFile)}`;
330
333
  }
331
334
 
332
335
  return command;
@@ -347,8 +350,8 @@ function buildFilesRestoreCommand(backupFile, options) {
347
350
  command += ' -xf';
348
351
  }
349
352
 
350
- command += ` "${backupFile}"`;
351
- command += ` -C "${targetPath}"`;
353
+ command += ` ${shellQuote(backupFile)}`;
354
+ command += ` -C ${shellQuote(targetPath)}`;
352
355
 
353
356
  return command;
354
357
  }
@@ -377,19 +380,20 @@ export function createBackupMetadata(backupId, type, options = {}) {
377
380
  */
378
381
  export function buildSaveMetadataCommand(metadata, metadataPath) {
379
382
  const jsonData = JSON.stringify(metadata, null, 2);
380
- // Escape single quotes in JSON for shell
381
- const escapedJson = jsonData.replace(/'/g, '\'\\\'\'');
382
- return `echo '${escapedJson}' > "${metadataPath}"`;
383
+ // The metadata carries caller-supplied fields (database name, paths...), so
384
+ // both the payload and the destination go through shellQuote rather than
385
+ // hand-rolled escaping.
386
+ return `echo ${shellQuote(jsonData)} > ${shellQuote(metadataPath)}`;
383
387
  }
384
388
 
385
389
  /**
386
390
  * Build command to list backups from remote server
387
391
  */
388
392
  export function buildListBackupsCommand(backupDir = DEFAULT_BACKUP_DIR, type = null) {
389
- let command = `find "${backupDir}" -name "*.meta.json" -type f`;
393
+ let command = `find ${shellQuote(backupDir)} -name '*.meta.json' -type f`;
390
394
 
391
395
  if (type) {
392
- command += ` | grep "${type}_"`;
396
+ command += ` | grep ${shellQuote(`${type}_`)}`;
393
397
  }
394
398
 
395
399
  // Read and parse each metadata file
@@ -427,14 +431,17 @@ export function parseBackupsList(output) {
427
431
  */
428
432
  export function buildCleanupCommand(backupDir = DEFAULT_BACKUP_DIR, retentionDays = 7) {
429
433
  // Find backup files older than retention period and delete them
430
- return `find "${backupDir}" -name "*_*_*" -type f -mtime +${retentionDays} -delete`;
434
+ return `find ${shellQuote(backupDir)} -name '*_*_*' -type f -mtime +${safeInteger(retentionDays, 7)} -delete`;
431
435
  }
432
436
 
433
437
  /**
434
438
  * Build cron schedule command
435
439
  */
436
440
  export function buildCronScheduleCommand(schedule, backupCommand, cronComment) {
437
- // Add cron job with comment
441
+ // A crontab line is data here, not a command to evaluate: the whole line goes
442
+ // through shellQuote so a schedule or comment carrying quotes cannot break
443
+ // out of the echo and run something else. backupCommand is built by the
444
+ // builders above, which quote their own arguments.
438
445
  const cronLine = `${schedule} ${backupCommand} # ${cronComment}`;
439
- return `(crontab -l 2>/dev/null; echo '${cronLine}') | crontab -`;
446
+ return `(crontab -l 2>/dev/null; echo ${shellQuote(cronLine)}) | crontab -`;
440
447
  }
@@ -12,25 +12,8 @@ export const DB_TYPES = {
12
12
 
13
13
  // A single quote character as a constant, so shellQuote()'s escaping stays
14
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
- }
15
+ import { shellQuote } from './shell-quote.js';
16
+ export { shellQuote };
34
17
 
35
18
  /**
36
19
  * Build MySQL dump command
@@ -4,6 +4,7 @@
4
4
  */
5
5
 
6
6
  import { logger } from './logger.js';
7
+ import { shellQuote, safeInteger } from './shell-quote.js';
7
8
 
8
9
  // Health status levels
9
10
  export const HEALTH_STATUS = {
@@ -169,17 +170,21 @@ function determineOverallHealth(cpu, memory, disks) {
169
170
  * Build command to check service status (systemd or sysv)
170
171
  */
171
172
  export function buildServiceStatusCommand(serviceName) {
173
+ // serviceName is a tool argument: resolveServiceName returns non-aliases
174
+ // unchanged, so it reaches the shell as-is. Quoting every occurrence is what
175
+ // stops `nginx; id > /tmp/pwned` from executing (GHSA-m793-whw6-f537).
176
+ const name = shellQuote(serviceName);
172
177
  // Try systemd first, fallback to sysv
173
178
  return `
174
179
  if command -v systemctl >/dev/null 2>&1; then
175
- systemctl is-active ${serviceName} 2>/dev/null >/dev/null && echo "ACTIVE" || echo "INACTIVE"
176
- systemctl is-enabled ${serviceName} 2>/dev/null >/dev/null && echo "ENABLED" || echo "DISABLED"
177
- systemctl status ${serviceName} 2>/dev/null | grep "Main PID" | awk '{print $3}' | cut -d'(' -f1
178
- systemctl status ${serviceName} 2>/dev/null | grep "Active:" | sed 's/.*Active: //' | awk '{print $1,$2,$3}'
180
+ systemctl is-active ${name} 2>/dev/null >/dev/null && echo "ACTIVE" || echo "INACTIVE"
181
+ systemctl is-enabled ${name} 2>/dev/null >/dev/null && echo "ENABLED" || echo "DISABLED"
182
+ systemctl status ${name} 2>/dev/null | grep "Main PID" | awk '{print $3}' | cut -d'(' -f1
183
+ systemctl status ${name} 2>/dev/null | grep "Active:" | sed 's/.*Active: //' | awk '{print $1,$2,$3}'
179
184
  elif command -v service >/dev/null 2>&1; then
180
- service ${serviceName} status >/dev/null 2>&1 && echo "ACTIVE" || echo "INACTIVE"
185
+ service ${name} status >/dev/null 2>&1 && echo "ACTIVE" || echo "INACTIVE"
181
186
  echo "UNKNOWN"
182
- pgrep -f ${serviceName} | head -1 || echo ""
187
+ pgrep -f ${name} | head -1 || echo ""
183
188
  echo "sysv"
184
189
  else
185
190
  echo "UNKNOWN"
@@ -218,10 +223,10 @@ export function buildProcessListCommand(options = {}) {
218
223
  } = options;
219
224
 
220
225
  let sortFlag = sortBy === 'memory' ? '-m' : '-c'; // -c for CPU, -m for memory
221
- let command = `ps aux --sort=${sortFlag === '-c' ? '-pcpu' : '-pmem'} | head -n ${limit + 1}`;
226
+ let command = `ps aux --sort=${sortFlag === '-c' ? '-pcpu' : '-pmem'} | head -n ${safeInteger(limit, 20) + 1}`;
222
227
 
223
228
  if (filter) {
224
- command += ` | grep -i "${filter}"`;
229
+ command += ` | grep -i ${shellQuote(filter)}`;
225
230
  }
226
231
 
227
232
  // Format output as JSON-like structure
@@ -270,6 +275,11 @@ export function buildKillProcessCommand(pid, signal = 'TERM') {
270
275
  * Build command to get process info
271
276
  */
272
277
  export function buildProcessInfoCommand(pid) {
278
+ // Same guard as buildKillProcessCommand: a PID is a number, and anything else
279
+ // has no business reaching the shell.
280
+ if (!Number.isInteger(pid) || pid <= 0) {
281
+ throw new Error(`Invalid PID: ${pid}`);
282
+ }
273
283
  return `ps -p ${pid} -o user,pid,pcpu,pmem,vsz,rss,stat,start,time,cmd --no-headers | awk '{printf "{\\"user\\":\\"%s\\",\\"pid\\":%s,\\"cpu\\":%.1f,\\"mem\\":%.1f,\\"vsz\\":%s,\\"rss\\":%s,\\"stat\\":\\"%s\\",\\"start\\":\\"%s\\",\\"time\\":\\"%s\\",\\"command\\":\\"%s\\"}", $1,$2,$3,$4,$5,$6,$7,$8,$9,substr($0,index($0,$10))}'`;
274
284
  }
275
285
 
@@ -296,15 +306,14 @@ export function createAlertConfig(thresholds) {
296
306
  */
297
307
  export function buildSaveAlertConfigCommand(config, configPath = '/etc/ssh-manager-alerts.json') {
298
308
  const jsonData = JSON.stringify(config, null, 2);
299
- const escapedJson = jsonData.replace(/'/g, '\'\\\'\'');
300
- return `echo '${escapedJson}' > "${configPath}"`;
309
+ return `echo ${shellQuote(jsonData)} > ${shellQuote(configPath)}`;
301
310
  }
302
311
 
303
312
  /**
304
313
  * Build command to load alert config
305
314
  */
306
315
  export function buildLoadAlertConfigCommand(configPath = '/etc/ssh-manager-alerts.json') {
307
- return `cat "${configPath}" 2>/dev/null || echo '{}'`;
316
+ return `cat ${shellQuote(configPath)} 2>/dev/null || echo '{}'`;
308
317
  }
309
318
 
310
319
  /**
package/src/index.js CHANGED
@@ -143,6 +143,7 @@ import {
143
143
  } from './database-manager.js';
144
144
  import { loadToolConfig, isToolEnabled } from './tool-config-manager.js';
145
145
  import { evaluatePolicy } from './policy.js';
146
+ import { shellQuote, safeInteger } from './shell-quote.js';
146
147
  import { auditLog } from './audit.js';
147
148
 
148
149
  const __filename = fileURLToPath(import.meta.url);
@@ -1257,19 +1258,28 @@ registerToolConditional(
1257
1258
  }
1258
1259
  },
1259
1260
  async ({ server: serverName, file, lines = 10, follow = true, grep }) => {
1261
+ // ssh_tail is read-only and therefore stays enabled in readonly/restricted
1262
+ // mode, which is exactly why it must consult the policy layer: without this
1263
+ // it was a way to run commands on a server the operator locked down
1264
+ // (GHSA-m793-whw6-f537).
1265
+ const denied = await applyServerPolicy(serverName, 'ssh_tail', { file, lines, follow, grep });
1266
+ if (denied) return denied;
1267
+
1260
1268
  try {
1261
1269
  const ssh = await getConnection(serverName);
1262
1270
 
1263
- // Build tail command
1264
- let command = `tail -n ${lines}`;
1271
+ // Build tail command. Every caller-controlled value is quoted: `file` and
1272
+ // `grep` sat inside double quotes, where $(...), backticks and a `"`
1273
+ // breakout all executed.
1274
+ let command = `tail -n ${safeInteger(lines, 10)}`;
1265
1275
  if (follow) {
1266
1276
  command += ' -f';
1267
1277
  }
1268
- command += ` "${file}"`;
1278
+ command += ` ${shellQuote(file)}`;
1269
1279
 
1270
1280
  // Add grep filter if specified
1271
1281
  if (grep) {
1272
- command += ` | grep "${grep}"`;
1282
+ command += ` | grep ${shellQuote(grep)}`;
1273
1283
  }
1274
1284
 
1275
1285
  logger.info(`Starting tail on ${serverName}`, {
@@ -3541,7 +3551,7 @@ registerToolConditional(
3541
3551
  }
3542
3552
 
3543
3553
  // Get backup file size
3544
- const sizeResult = await ssh.execCommand(`stat -f%z "${backupFile}" 2>/dev/null || stat -c%s "${backupFile}" 2>/dev/null`);
3554
+ const sizeResult = await ssh.execCommand(`stat -f%z ${shellQuote(backupFile)} 2>/dev/null || stat -c%s ${shellQuote(backupFile)} 2>/dev/null`);
3545
3555
  const size = parseInt(sizeResult.stdout.trim()) || 0;
3546
3556
 
3547
3557
  // Create and save metadata
@@ -4049,6 +4059,11 @@ registerToolConditional(
4049
4059
  }
4050
4060
  },
4051
4061
  async ({ server: serverName, services }) => {
4062
+ // Read-only tools stay enabled under readonly/restricted, so they are the
4063
+ // ones that most need the policy check (GHSA-m793-whw6-f537).
4064
+ const denied = await applyServerPolicy(serverName, 'ssh_service_status', { services });
4065
+ if (denied) return denied;
4066
+
4052
4067
  try {
4053
4068
  const ssh = await getConnection(serverName);
4054
4069
 
@@ -4527,7 +4542,7 @@ registerToolConditional(
4527
4542
  }
4528
4543
 
4529
4544
  // Get file size
4530
- const sizeCommand = `stat -f%z "${outputFile}" 2>/dev/null || stat -c%s "${outputFile}" 2>/dev/null`;
4545
+ const sizeCommand = `stat -f%z ${shellQuote(outputFile)} 2>/dev/null || stat -c%s ${shellQuote(outputFile)} 2>/dev/null`;
4531
4546
  const sizeResult = await ssh.execCommand(sizeCommand);
4532
4547
  const size = parseSize(sizeResult.stdout);
4533
4548
 
package/src/logger.js CHANGED
@@ -11,6 +11,12 @@ const __filename = fileURLToPath(import.meta.url);
11
11
  const __dirname = path.dirname(__filename);
12
12
 
13
13
  // Log levels
14
+ /**
15
+ * Log level constants. Exported as part of the package's public surface so a
16
+ * consumer can map SSH_LOG_LEVEL values; nothing inside the repository imports
17
+ * it, hence the @public tag telling knip this export is deliberate.
18
+ * @public
19
+ */
14
20
  export const LOG_LEVELS = {
15
21
  DEBUG: 0,
16
22
  INFO: 1,
@@ -0,0 +1,46 @@
1
+ // Single POSIX shell-word quoting, shared by every builder that hands a string
2
+ // to a remote shell.
3
+ //
4
+ // It lived in database-manager.js after the v3.6.7 fix (CVE-2026-77383), and
5
+ // that is exactly why the same class of bug survived elsewhere: backup-manager,
6
+ // health-monitor and several inline commands in index.js never imported it and
7
+ // kept interpolating caller-controlled values raw. Keeping it in one module
8
+ // makes "did this builder quote its inputs?" a question with one answer.
9
+
10
+ const SQ = '\'';
11
+
12
+ /**
13
+ * Quote a value for safe inclusion as a single POSIX shell word.
14
+ *
15
+ * Wraps the value in single quotes and escapes any embedded single quote as
16
+ * '\'' so the remote shell treats it literally — it never interprets $(...),
17
+ * backticks, $VAR, ;, |, &, redirects, spaces, or newlines inside the value.
18
+ * EVERY caller-controlled value interpolated into a command string MUST go
19
+ * through this. Numbers are coerced to string; null/undefined become an empty
20
+ * quoted word.
21
+ *
22
+ * @param {any} value - Value to quote
23
+ * @returns {string} The value as one safely quoted shell word
24
+ */
25
+ export function shellQuote(value) {
26
+ if (value === null || value === undefined) return SQ + SQ;
27
+ // Replace every ' with '\'' (close quote, escaped quote, reopen), then wrap.
28
+ return SQ + String(value).replace(/'/g, SQ + '\\' + SQ + SQ) + SQ;
29
+ }
30
+
31
+ /**
32
+ * Coerce a value to a safe non-negative integer for use in a command.
33
+ *
34
+ * Numeric tool arguments (line counts, ports, retention days) are declared as
35
+ * z.number() but still land inside command strings, where a non-finite or
36
+ * fractional value would serialise into something the shell reads oddly.
37
+ *
38
+ * @param {any} value - Value to coerce
39
+ * @param {number} fallback - Value used when the input is not a finite number
40
+ * @returns {number} A non-negative integer
41
+ */
42
+ export function safeInteger(value, fallback) {
43
+ const n = Number(value);
44
+ if (!Number.isFinite(n)) return fallback;
45
+ return Math.max(0, Math.trunc(n));
46
+ }