mcp-ssh-manager 3.8.4 → 3.8.6
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 +96 -0
- package/README.md +18 -10
- package/cli/lib/menu.sh +2 -2
- package/docs/ALIASES_AND_HOOKS.md +54 -25
- package/docs/SECURITY_MODES.md +33 -3
- package/package.json +6 -3
- package/profiles/default.json +6 -4
- package/scripts/setup-hooks.sh +16 -7
- package/server.json +2 -2
- package/src/backup-manager.js +92 -62
- package/src/command-aliases.js +9 -6
- package/src/config-paths.js +12 -0
- package/src/database-manager.js +202 -40
- package/src/deploy-helper.js +15 -7
- package/src/health-monitor.js +20 -11
- package/src/hooks-system.js +298 -57
- package/src/index.js +59 -27
- package/src/logger.js +49 -17
- package/src/policy.js +46 -25
- package/src/profile-loader.js +18 -12
- package/src/server-aliases.js +9 -6
- package/src/shell-quote.js +54 -0
- package/src/shell-segments.js +189 -0
- package/src/ssh-key-manager.js +123 -76
- package/src/ssh-manager.js +17 -41
- package/src/user-state.js +60 -0
- package/.hooks-config.json +0 -131
package/src/index.js
CHANGED
|
@@ -99,7 +99,8 @@ import {
|
|
|
99
99
|
buildListBackupsCommand,
|
|
100
100
|
parseBackupsList,
|
|
101
101
|
buildCleanupCommand,
|
|
102
|
-
buildCronScheduleCommand
|
|
102
|
+
buildCronScheduleCommand,
|
|
103
|
+
isCronSchedule
|
|
103
104
|
} from './backup-manager.js';
|
|
104
105
|
import {
|
|
105
106
|
HEALTH_STATUS,
|
|
@@ -143,6 +144,7 @@ import {
|
|
|
143
144
|
} from './database-manager.js';
|
|
144
145
|
import { loadToolConfig, isToolEnabled } from './tool-config-manager.js';
|
|
145
146
|
import { evaluatePolicy } from './policy.js';
|
|
147
|
+
import { shellQuote, shellPath, safeInteger } from './shell-quote.js';
|
|
146
148
|
import { auditLog } from './audit.js';
|
|
147
149
|
|
|
148
150
|
const __filename = fileURLToPath(import.meta.url);
|
|
@@ -718,9 +720,9 @@ registerToolConditional(
|
|
|
718
720
|
if (workingDir) {
|
|
719
721
|
if (platform === 'windows') {
|
|
720
722
|
const escapedDir = workingDir.replace(/'/g, '\'\'');
|
|
721
|
-
fullCommand = `Set-Location '${escapedDir}'; ${expandedCommand}`;
|
|
723
|
+
fullCommand = `Set-Location -LiteralPath '${escapedDir}'; ${expandedCommand}`;
|
|
722
724
|
} else {
|
|
723
|
-
fullCommand = `cd ${workingDir} && ${expandedCommand}`;
|
|
725
|
+
fullCommand = `cd -- ${shellPath(workingDir)} && ${expandedCommand}`;
|
|
724
726
|
}
|
|
725
727
|
} else {
|
|
726
728
|
fullCommand = expandedCommand;
|
|
@@ -1257,19 +1259,28 @@ registerToolConditional(
|
|
|
1257
1259
|
}
|
|
1258
1260
|
},
|
|
1259
1261
|
async ({ server: serverName, file, lines = 10, follow = true, grep }) => {
|
|
1262
|
+
// ssh_tail is read-only and therefore stays enabled in readonly/restricted
|
|
1263
|
+
// mode, which is exactly why it must consult the policy layer: without this
|
|
1264
|
+
// it was a way to run commands on a server the operator locked down
|
|
1265
|
+
// (GHSA-m793-whw6-f537).
|
|
1266
|
+
const denied = await applyServerPolicy(serverName, 'ssh_tail', { file, lines, follow, grep });
|
|
1267
|
+
if (denied) return denied;
|
|
1268
|
+
|
|
1260
1269
|
try {
|
|
1261
1270
|
const ssh = await getConnection(serverName);
|
|
1262
1271
|
|
|
1263
|
-
// Build tail command
|
|
1264
|
-
|
|
1272
|
+
// Build tail command. Every caller-controlled value is quoted: `file` and
|
|
1273
|
+
// `grep` sat inside double quotes, where $(...), backticks and a `"`
|
|
1274
|
+
// breakout all executed.
|
|
1275
|
+
let command = `tail -n ${safeInteger(lines, 10)}`;
|
|
1265
1276
|
if (follow) {
|
|
1266
1277
|
command += ' -f';
|
|
1267
1278
|
}
|
|
1268
|
-
command += `
|
|
1279
|
+
command += ` ${shellQuote(file)}`;
|
|
1269
1280
|
|
|
1270
1281
|
// Add grep filter if specified
|
|
1271
1282
|
if (grep) {
|
|
1272
|
-
command += ` | grep
|
|
1283
|
+
command += ` | grep ${shellQuote(grep)}`;
|
|
1273
1284
|
}
|
|
1274
1285
|
|
|
1275
1286
|
logger.info(`Starting tail on ${serverName}`, {
|
|
@@ -1946,9 +1957,9 @@ registerToolConditional(
|
|
|
1946
1957
|
if (platform === 'windows') {
|
|
1947
1958
|
// Single-quote escaping: replace ' with '' (PowerShell convention)
|
|
1948
1959
|
const escapedDir = workingDir.replace(/'/g, '\'\'');
|
|
1949
|
-
fullCommand = `Set-Location '${escapedDir}'; ${command}`;
|
|
1960
|
+
fullCommand = `Set-Location -LiteralPath '${escapedDir}'; ${command}`;
|
|
1950
1961
|
} else {
|
|
1951
|
-
fullCommand = `cd ${workingDir} && ${command}`;
|
|
1962
|
+
fullCommand = `cd -- ${shellPath(workingDir)} && ${command}`;
|
|
1952
1963
|
}
|
|
1953
1964
|
} else {
|
|
1954
1965
|
fullCommand = command;
|
|
@@ -2282,7 +2293,7 @@ registerToolConditional(
|
|
|
2282
2293
|
const deployServers = await loadServerConfig();
|
|
2283
2294
|
const deployServerConfig = deployServers[server.toLowerCase()];
|
|
2284
2295
|
for (const step of strategy.steps) {
|
|
2285
|
-
const command = step.command.replace('{{tempFile}}', tempFile);
|
|
2296
|
+
const command = step.command.replace('{{tempFile}}', () => shellQuote(tempFile));
|
|
2286
2297
|
|
|
2287
2298
|
// step.stdin carries the sudo password for steps that need it, so it
|
|
2288
2299
|
// never reaches the remote command line (issue #34).
|
|
@@ -2393,16 +2404,16 @@ registerToolConditional(
|
|
|
2393
2404
|
if (cwd) {
|
|
2394
2405
|
if (platform === 'windows') {
|
|
2395
2406
|
const escapedDir = cwd.replace(/'/g, '\'\'');
|
|
2396
|
-
fullCommand = `Set-Location '${escapedDir}'; ${fullCommand}`;
|
|
2407
|
+
fullCommand = `Set-Location -LiteralPath '${escapedDir}'; ${fullCommand}`;
|
|
2397
2408
|
} else {
|
|
2398
|
-
fullCommand = `cd ${cwd} && ${fullCommand}`;
|
|
2409
|
+
fullCommand = `cd -- ${shellPath(cwd)} && ${fullCommand}`;
|
|
2399
2410
|
}
|
|
2400
2411
|
} else if (serverConfig?.defaultDir) {
|
|
2401
2412
|
if (platform === 'windows') {
|
|
2402
2413
|
const escapedDir = serverConfig.defaultDir.replace(/'/g, '\'\'');
|
|
2403
|
-
fullCommand = `Set-Location '${escapedDir}'; ${fullCommand}`;
|
|
2414
|
+
fullCommand = `Set-Location -LiteralPath '${escapedDir}'; ${fullCommand}`;
|
|
2404
2415
|
} else {
|
|
2405
|
-
fullCommand = `cd ${serverConfig.defaultDir} && ${fullCommand}`;
|
|
2416
|
+
fullCommand = `cd -- ${shellPath(serverConfig.defaultDir)} && ${fullCommand}`;
|
|
2406
2417
|
}
|
|
2407
2418
|
}
|
|
2408
2419
|
|
|
@@ -3541,7 +3552,7 @@ registerToolConditional(
|
|
|
3541
3552
|
}
|
|
3542
3553
|
|
|
3543
3554
|
// Get backup file size
|
|
3544
|
-
const sizeResult = await ssh.execCommand(`stat -f%z
|
|
3555
|
+
const sizeResult = await ssh.execCommand(`stat -f%z ${shellQuote(backupFile)} 2>/dev/null || stat -c%s ${shellQuote(backupFile)} 2>/dev/null`);
|
|
3545
3556
|
const size = parseInt(sizeResult.stdout.trim()) || 0;
|
|
3546
3557
|
|
|
3547
3558
|
// Create and save metadata
|
|
@@ -3840,6 +3851,16 @@ registerToolConditional(
|
|
|
3840
3851
|
if (denied) return denied;
|
|
3841
3852
|
|
|
3842
3853
|
try {
|
|
3854
|
+
// The name becomes a file name, a cron comment and a find pattern, and
|
|
3855
|
+
// the schedule the first fields of a crontab line, where anything past
|
|
3856
|
+
// the fifth field is the command cron runs and a line break starts a
|
|
3857
|
+
// new job. Both are checked before anything reaches the server.
|
|
3858
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name)) {
|
|
3859
|
+
throw new Error('Backup name may only contain letters, digits, ".", "_" and "-"');
|
|
3860
|
+
}
|
|
3861
|
+
if (!isCronSchedule(schedule)) {
|
|
3862
|
+
throw new Error('Schedule must be five cron fields (e.g. "0 2 * * *") or a macro such as @daily');
|
|
3863
|
+
}
|
|
3843
3864
|
const ssh = await getConnection(serverName);
|
|
3844
3865
|
|
|
3845
3866
|
// Build backup script path
|
|
@@ -3861,29 +3882,31 @@ registerToolConditional(
|
|
|
3861
3882
|
scriptContent += `BACKUP_FILE="${backupFile}"\n\n`;
|
|
3862
3883
|
scriptContent += 'mkdir -p "$BACKUP_DIR"\n\n';
|
|
3863
3884
|
|
|
3864
|
-
// Add backup command based on type
|
|
3885
|
+
// Add backup command based on type. The script runs later from cron, so
|
|
3886
|
+
// a value spliced in raw here would run every night, not once.
|
|
3865
3887
|
switch (type) {
|
|
3866
3888
|
case BACKUP_TYPES.MYSQL:
|
|
3867
|
-
scriptContent += `mysqldump --single-transaction --routines --triggers ${database} | gzip > "$BACKUP_FILE"\n`;
|
|
3889
|
+
scriptContent += `mysqldump --single-transaction --routines --triggers ${shellQuote(database)} | gzip > "$BACKUP_FILE"\n`;
|
|
3868
3890
|
break;
|
|
3869
3891
|
case BACKUP_TYPES.POSTGRESQL:
|
|
3870
|
-
scriptContent += `pg_dump --format=custom --clean --if-exists ${database} | gzip > "$BACKUP_FILE"\n`;
|
|
3892
|
+
scriptContent += `pg_dump --format=custom --clean --if-exists ${shellQuote(database)} | gzip > "$BACKUP_FILE"\n`;
|
|
3871
3893
|
break;
|
|
3872
3894
|
case BACKUP_TYPES.MONGODB:
|
|
3873
|
-
scriptContent += `mongodump --db ${database} --out /tmp/mongo_\${RANDOM} && tar -czf "$BACKUP_FILE" -C /tmp mongo_*\n`;
|
|
3895
|
+
scriptContent += `mongodump --db ${shellQuote(database)} --out /tmp/mongo_\${RANDOM} && tar -czf "$BACKUP_FILE" -C /tmp mongo_*\n`;
|
|
3874
3896
|
break;
|
|
3875
3897
|
case BACKUP_TYPES.FILES:
|
|
3876
|
-
scriptContent += `tar -czf "$BACKUP_FILE" ${paths.join(' ')}\n`;
|
|
3898
|
+
scriptContent += `tar -czf "$BACKUP_FILE" ${(paths || []).map(shellQuote).join(' ')}\n`;
|
|
3877
3899
|
break;
|
|
3878
3900
|
}
|
|
3879
3901
|
|
|
3880
3902
|
// Add cleanup command
|
|
3881
3903
|
scriptContent += '\n# Cleanup old backups\n';
|
|
3882
|
-
scriptContent += `find "$BACKUP_DIR" -name "*_${name}_*" -type f -mtime +${retention} -delete\n`;
|
|
3904
|
+
scriptContent += `find "$BACKUP_DIR" -name "*_${name}_*" -type f -mtime +${safeInteger(retention, 7)} -delete\n`;
|
|
3883
3905
|
|
|
3884
|
-
// Save script to remote server
|
|
3885
|
-
|
|
3886
|
-
|
|
3906
|
+
// Save script to remote server. printf, not echo: dash's echo rewrites
|
|
3907
|
+
// backslashes, which would alter a quoted path inside the script.
|
|
3908
|
+
const quotedPath = shellQuote(scriptPath);
|
|
3909
|
+
await ssh.execCommand(`printf '%s' ${shellQuote(scriptContent)} > ${quotedPath} && chmod +x ${quotedPath}`);
|
|
3887
3910
|
|
|
3888
3911
|
// Add to crontab
|
|
3889
3912
|
const cronComment = `ssh-manager-backup-${name}`;
|
|
@@ -4049,6 +4072,11 @@ registerToolConditional(
|
|
|
4049
4072
|
}
|
|
4050
4073
|
},
|
|
4051
4074
|
async ({ server: serverName, services }) => {
|
|
4075
|
+
// Read-only tools stay enabled under readonly/restricted, so they are the
|
|
4076
|
+
// ones that most need the policy check (GHSA-m793-whw6-f537).
|
|
4077
|
+
const denied = await applyServerPolicy(serverName, 'ssh_service_status', { services });
|
|
4078
|
+
if (denied) return denied;
|
|
4079
|
+
|
|
4052
4080
|
try {
|
|
4053
4081
|
const ssh = await getConnection(serverName);
|
|
4054
4082
|
|
|
@@ -4527,7 +4555,7 @@ registerToolConditional(
|
|
|
4527
4555
|
}
|
|
4528
4556
|
|
|
4529
4557
|
// Get file size
|
|
4530
|
-
const sizeCommand = `stat -f%z
|
|
4558
|
+
const sizeCommand = `stat -f%z ${shellQuote(outputFile)} 2>/dev/null || stat -c%s ${shellQuote(outputFile)} 2>/dev/null`;
|
|
4531
4559
|
const sizeResult = await ssh.execCommand(sizeCommand);
|
|
4532
4560
|
const size = parseSize(sizeResult.stdout);
|
|
4533
4561
|
|
|
@@ -4809,7 +4837,7 @@ registerToolConditional(
|
|
|
4809
4837
|
registerToolConditional(
|
|
4810
4838
|
'ssh_db_query',
|
|
4811
4839
|
{
|
|
4812
|
-
description: 'Runs a read-only query against a remote database. For mysql and postgresql it is strictly limited to SELECT: the query must begin with SELECT and any insert, update, delete, drop, create, alter, truncate, grant, revoke, or exec keyword
|
|
4840
|
+
description: 'Runs a read-only query against a remote database. For mysql and postgresql it is strictly limited to one SELECT statement: the query must begin with SELECT, and INTO, file functions, and any insert, update, delete, drop, create, alter, truncate, grant, revoke, or exec keyword are rejected before execution; it then runs inside a read-only transaction, so the database itself refuses any write. For mongodb it runs a find() and requires the collection parameter; the query must be a filter document (JSON or mongo shell syntax such as ObjectId("…")), and $where, $function and $accumulator are refused. Returns the raw command output as text.',
|
|
4813
4841
|
inputSchema: {
|
|
4814
4842
|
server: z.string().describe('Server name'),
|
|
4815
4843
|
type: z.enum(['mysql', 'postgresql', 'mongodb'])
|
|
@@ -4871,7 +4899,11 @@ registerToolConditional(
|
|
|
4871
4899
|
// Execute query
|
|
4872
4900
|
const result = await ssh.execCommand(queryCommand);
|
|
4873
4901
|
|
|
4874
|
-
|
|
4902
|
+
// The MySQL JSON output is piped through awk, whose exit status hides the
|
|
4903
|
+
// client's: a write refused by the read-only transaction (ERROR 1792) or
|
|
4904
|
+
// a syntax error would otherwise come back as an empty result.
|
|
4905
|
+
const clientError = type === DB_TYPES.MYSQL && /^ERROR \d+/m.test(result.stderr || '');
|
|
4906
|
+
if (result.code !== 0 || clientError) {
|
|
4875
4907
|
throw new Error(`Query failed: ${result.stderr || result.stdout}`);
|
|
4876
4908
|
}
|
|
4877
4909
|
|
package/src/logger.js
CHANGED
|
@@ -5,12 +5,15 @@
|
|
|
5
5
|
|
|
6
6
|
import fs from 'fs';
|
|
7
7
|
import path from 'path';
|
|
8
|
-
import {
|
|
9
|
-
|
|
10
|
-
const __filename = fileURLToPath(import.meta.url);
|
|
11
|
-
const __dirname = path.dirname(__filename);
|
|
8
|
+
import { managerHome } from './config-paths.js';
|
|
12
9
|
|
|
13
10
|
// Log levels
|
|
11
|
+
/**
|
|
12
|
+
* Log level constants. Exported as part of the package's public surface so a
|
|
13
|
+
* consumer can map SSH_LOG_LEVEL values; nothing inside the repository imports
|
|
14
|
+
* it, hence the @public tag telling knip this export is deliberate.
|
|
15
|
+
* @public
|
|
16
|
+
*/
|
|
14
17
|
export const LOG_LEVELS = {
|
|
15
18
|
DEBUG: 0,
|
|
16
19
|
INFO: 1,
|
|
@@ -72,23 +75,49 @@ class Logger {
|
|
|
72
75
|
// Enable verbose mode from environment
|
|
73
76
|
this.verbose = process.env.SSH_VERBOSE === 'true';
|
|
74
77
|
|
|
75
|
-
// Log file path
|
|
76
|
-
this.logFile = process.env.SSH_LOG_FILE || path.join(__dirname, '..', '.ssh-manager.log');
|
|
77
|
-
|
|
78
|
-
// Command history file
|
|
79
|
-
this.historyFile = path.join(__dirname, '..', '.ssh-command-history.json');
|
|
80
|
-
|
|
81
78
|
// Initialize command history
|
|
82
79
|
this.commandHistory = this.loadCommandHistory();
|
|
83
80
|
}
|
|
84
81
|
|
|
82
|
+
/**
|
|
83
|
+
* Where the log goes. SSH_LOG_FILE wins; otherwise ssh-manager.log in the
|
|
84
|
+
* manager home, beside the .env. Up to 3.8.5 the default was inside the
|
|
85
|
+
* installed package: lost on upgrade, readable by every local user, and a
|
|
86
|
+
* write into the install directory (issue #87). The home is never created
|
|
87
|
+
* just for a log, so a user who keeps no settings there gets stderr only,
|
|
88
|
+
* and starting the server leaves a pristine home pristine.
|
|
89
|
+
* @returns {string|null}
|
|
90
|
+
*/
|
|
91
|
+
get logFile() {
|
|
92
|
+
return process.env.SSH_LOG_FILE || this.homeFile('ssh-manager.log');
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The command history behind ssh_history, under the same rule. Overridable
|
|
97
|
+
* for the same reason the log is: a host that runs the engine from somewhere
|
|
98
|
+
* it must not write — inside a signed application bundle, where one added
|
|
99
|
+
* file breaks the seal and macOS then refuses to launch it — has to be able
|
|
100
|
+
* to say where these go.
|
|
101
|
+
* @returns {string|null}
|
|
102
|
+
*/
|
|
103
|
+
get historyFile() {
|
|
104
|
+
return process.env.SSH_HISTORY_FILE || this.homeFile('command-history.json');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** @param {string} name */
|
|
108
|
+
homeFile(name) {
|
|
109
|
+
const home = managerHome();
|
|
110
|
+
return fs.existsSync(home) ? path.join(home, name) : null;
|
|
111
|
+
}
|
|
112
|
+
|
|
85
113
|
/**
|
|
86
114
|
* Load command history from file
|
|
87
115
|
*/
|
|
88
116
|
loadCommandHistory() {
|
|
89
117
|
try {
|
|
90
|
-
|
|
91
|
-
|
|
118
|
+
const file = this.historyFile;
|
|
119
|
+
if (file && fs.existsSync(file)) {
|
|
120
|
+
const data = fs.readFileSync(file, 'utf8');
|
|
92
121
|
return JSON.parse(data);
|
|
93
122
|
}
|
|
94
123
|
} catch (error) {
|
|
@@ -118,7 +147,8 @@ class Logger {
|
|
|
118
147
|
}
|
|
119
148
|
|
|
120
149
|
try {
|
|
121
|
-
|
|
150
|
+
const file = this.historyFile;
|
|
151
|
+
if (file) fs.writeFileSync(file, JSON.stringify(this.commandHistory, null, 2), { mode: 0o600 });
|
|
122
152
|
} catch (error) {
|
|
123
153
|
// Ignore write errors
|
|
124
154
|
}
|
|
@@ -168,9 +198,11 @@ class Logger {
|
|
|
168
198
|
// Output to stderr for proper MCP logging
|
|
169
199
|
console.error(formatted.console);
|
|
170
200
|
|
|
171
|
-
// Also write to file
|
|
201
|
+
// Also write to file, readable by its owner only: it records the commands
|
|
202
|
+
// run on remote servers.
|
|
172
203
|
try {
|
|
173
|
-
|
|
204
|
+
const file = this.logFile;
|
|
205
|
+
if (file) fs.appendFileSync(file, formatted.file + '\n', { mode: 0o600 });
|
|
174
206
|
} catch (error) {
|
|
175
207
|
// Ignore file write errors
|
|
176
208
|
}
|
|
@@ -292,8 +324,8 @@ class Logger {
|
|
|
292
324
|
clear() {
|
|
293
325
|
this.commandHistory = [];
|
|
294
326
|
try {
|
|
295
|
-
fs.writeFileSync(this.historyFile, '[]');
|
|
296
|
-
fs.writeFileSync(this.logFile, '');
|
|
327
|
+
if (this.historyFile) fs.writeFileSync(this.historyFile, '[]', { mode: 0o600 });
|
|
328
|
+
if (this.logFile) fs.writeFileSync(this.logFile, '', { mode: 0o600 });
|
|
297
329
|
this.info('Logs and history cleared');
|
|
298
330
|
} catch (error) {
|
|
299
331
|
this.error('Failed to clear logs', { error: error.message });
|
package/src/policy.js
CHANGED
|
@@ -6,14 +6,19 @@
|
|
|
6
6
|
* - "readonly": blocks mutating tools entirely; for ssh_execute / ssh_execute_sudo /
|
|
7
7
|
* ssh_execute_group / ssh_session_send, blocks commands matching the
|
|
8
8
|
* built-in destructive denylist below.
|
|
9
|
-
* - "restricted": command
|
|
10
|
-
*
|
|
9
|
+
* - "restricted": every command on the line (each part of a list or pipeline)
|
|
10
|
+
* must match at least one ALLOW_PATTERNS regex, and neither the
|
|
11
|
+
* line nor any of its commands may match a DENY_PATTERNS regex.
|
|
12
|
+
* DENY wins over ALLOW. Command substitution and redirections
|
|
13
|
+
* that write a file are refused: they run or change things the
|
|
14
|
+
* patterns never see.
|
|
11
15
|
*
|
|
12
16
|
* Returns { allowed: boolean, reason?: string } — never throws. Callers translate
|
|
13
17
|
* a refusal into an MCP-level error response.
|
|
14
18
|
*/
|
|
15
19
|
|
|
16
20
|
import { logger } from './logger.js';
|
|
21
|
+
import { splitShellCommand } from './shell-segments.js';
|
|
17
22
|
|
|
18
23
|
const MODE_UNRESTRICTED = 'unrestricted';
|
|
19
24
|
const MODE_READONLY = 'readonly';
|
|
@@ -170,12 +175,17 @@ export function evaluatePolicy(serverConfig, toolName, command) {
|
|
|
170
175
|
};
|
|
171
176
|
}
|
|
172
177
|
if (COMMAND_BEARING_TOOLS.has(toolName) && typeof command === 'string') {
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
178
|
+
// The whole line, then each command in it, including those inside $(…)
|
|
179
|
+
// and backticks: `echo $(rm -rf x)` has no space before its `rm`.
|
|
180
|
+
const { segments, substitutions } = splitShellCommand(command);
|
|
181
|
+
for (const text of [command, ...segments, ...substitutions]) {
|
|
182
|
+
for (const re of READONLY_DENY_REGEX) {
|
|
183
|
+
if (re.test(text)) {
|
|
184
|
+
return {
|
|
185
|
+
allowed: false,
|
|
186
|
+
reason: `Command refused on server "${serverConfig.name}" (mode: readonly): matches built-in destructive pattern ${re}.`,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
179
189
|
}
|
|
180
190
|
}
|
|
181
191
|
}
|
|
@@ -206,32 +216,43 @@ export function evaluatePolicy(serverConfig, toolName, command) {
|
|
|
206
216
|
};
|
|
207
217
|
}
|
|
208
218
|
|
|
219
|
+
const refuse = why => ({
|
|
220
|
+
allowed: false,
|
|
221
|
+
reason: `Command refused on server "${serverConfig.name}" (mode: restricted): ${why}.`,
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
// Each pattern is tested against every command on the line, not the line
|
|
225
|
+
// as a whole: tested against the line, `^docker ps` only checked how it
|
|
226
|
+
// started, and `docker ps; id` passed (GHSA-rfxw-26h6-7w42).
|
|
227
|
+
const { segments, substitutions, writes, problem } = splitShellCommand(command);
|
|
228
|
+
|
|
209
229
|
for (const re of deny) {
|
|
210
|
-
|
|
211
|
-
return {
|
|
212
|
-
allowed: false,
|
|
213
|
-
reason: `Command refused on server "${serverConfig.name}" (mode: restricted): matches DENY pattern ${re}.`,
|
|
214
|
-
};
|
|
230
|
+
for (const text of [command, ...segments]) {
|
|
231
|
+
if (re.test(text)) return refuse(`matches DENY pattern ${re}`);
|
|
215
232
|
}
|
|
216
233
|
}
|
|
217
234
|
|
|
218
235
|
if (allow.length === 0) {
|
|
219
|
-
return
|
|
220
|
-
allowed: false,
|
|
221
|
-
reason: `Command refused on server "${serverConfig.name}" (mode: restricted): no ALLOW_PATTERNS configured — restricted mode requires an explicit allowlist.`,
|
|
222
|
-
};
|
|
236
|
+
return refuse('no ALLOW_PATTERNS configured — restricted mode requires an explicit allowlist');
|
|
223
237
|
}
|
|
224
238
|
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
}
|
|
239
|
+
if (problem) return refuse(`the command could not be checked (${problem})`);
|
|
240
|
+
if (substitutions.length) {
|
|
241
|
+
return refuse('command substitution ($(…), backticks, <(…)) runs commands the allowlist cannot check');
|
|
229
242
|
}
|
|
243
|
+
if (writes.length) {
|
|
244
|
+
return refuse(`redirecting output to "${writes[0]}" writes a file, which restricted mode does not allow`);
|
|
245
|
+
}
|
|
246
|
+
if (!segments.length) return refuse('empty command');
|
|
230
247
|
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
248
|
+
for (const segment of segments) {
|
|
249
|
+
if (!allow.some(re => re.test(segment))) {
|
|
250
|
+
return refuse(segments.length > 1
|
|
251
|
+
? `"${segment}" does not match any ALLOW_PATTERNS (every command in a list or pipeline must)`
|
|
252
|
+
: 'does not match any ALLOW_PATTERNS');
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return { allowed: true };
|
|
235
256
|
}
|
|
236
257
|
|
|
237
258
|
// Unknown mode — fail-closed with a clear message rather than silently allowing.
|
package/src/profile-loader.js
CHANGED
|
@@ -6,12 +6,20 @@
|
|
|
6
6
|
import fs from 'fs';
|
|
7
7
|
import path from 'path';
|
|
8
8
|
import { fileURLToPath } from 'url';
|
|
9
|
+
import { readUserState, writeUserState } from './user-state.js';
|
|
9
10
|
|
|
10
11
|
const __filename = fileURLToPath(import.meta.url);
|
|
11
12
|
const __dirname = path.dirname(__filename);
|
|
12
13
|
|
|
13
14
|
const PROFILES_DIR = path.join(__dirname, '..', 'profiles');
|
|
14
|
-
|
|
15
|
+
// The active profile is remembered in the manager home; the package copy is
|
|
16
|
+
// read only as a fallback for a source checkout (see user-state.js, issue #87).
|
|
17
|
+
const PROFILE_STATE_NAME = 'profile';
|
|
18
|
+
const LEGACY_PROFILE_CONFIG_FILE = path.join(__dirname, '..', '.ssh-manager-profile');
|
|
19
|
+
|
|
20
|
+
// A profile name becomes a file name under profiles/: nothing that could
|
|
21
|
+
// climb out of that directory and load some other JSON file as hooks.
|
|
22
|
+
const PROFILE_NAME = /^[A-Za-z0-9_-]+$/;
|
|
15
23
|
|
|
16
24
|
/**
|
|
17
25
|
* Get the active profile name
|
|
@@ -23,15 +31,13 @@ export function getActiveProfileName() {
|
|
|
23
31
|
}
|
|
24
32
|
|
|
25
33
|
// 2. Check configuration file
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
return profileName;
|
|
31
|
-
}
|
|
32
|
-
} catch (error) {
|
|
33
|
-
console.error(`Error reading profile config: ${error.message}`);
|
|
34
|
+
try {
|
|
35
|
+
const profileName = readUserState(PROFILE_STATE_NAME, LEGACY_PROFILE_CONFIG_FILE)?.text.trim();
|
|
36
|
+
if (profileName) {
|
|
37
|
+
return profileName;
|
|
34
38
|
}
|
|
39
|
+
} catch (error) {
|
|
40
|
+
console.error(`Error reading profile config: ${error.message}`);
|
|
35
41
|
}
|
|
36
42
|
|
|
37
43
|
// 3. Default to 'default' profile
|
|
@@ -46,7 +52,7 @@ export function loadProfile(profileName = null) {
|
|
|
46
52
|
const profilePath = path.join(PROFILES_DIR, `${name}.json`);
|
|
47
53
|
|
|
48
54
|
try {
|
|
49
|
-
if (fs.existsSync(profilePath)) {
|
|
55
|
+
if (PROFILE_NAME.test(name) && fs.existsSync(profilePath)) {
|
|
50
56
|
const profileData = fs.readFileSync(profilePath, 'utf8');
|
|
51
57
|
const profile = JSON.parse(profileData);
|
|
52
58
|
|
|
@@ -127,12 +133,12 @@ export function setActiveProfile(profileName) {
|
|
|
127
133
|
try {
|
|
128
134
|
// Verify profile exists
|
|
129
135
|
const profilePath = path.join(PROFILES_DIR, `${profileName}.json`);
|
|
130
|
-
if (!fs.existsSync(profilePath)) {
|
|
136
|
+
if (!PROFILE_NAME.test(String(profileName)) || !fs.existsSync(profilePath)) {
|
|
131
137
|
throw new Error(`Profile '${profileName}' does not exist`);
|
|
132
138
|
}
|
|
133
139
|
|
|
134
140
|
// Write to config file
|
|
135
|
-
|
|
141
|
+
writeUserState(PROFILE_STATE_NAME, `${profileName}\n`);
|
|
136
142
|
return true;
|
|
137
143
|
} catch (error) {
|
|
138
144
|
console.error(`Error setting active profile: ${error.message}`);
|
package/src/server-aliases.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
1
|
import path from 'path';
|
|
3
2
|
import { fileURLToPath } from 'url';
|
|
3
|
+
import { readUserState, writeUserState } from './user-state.js';
|
|
4
4
|
|
|
5
5
|
const __filename = fileURLToPath(import.meta.url);
|
|
6
6
|
const __dirname = path.dirname(__filename);
|
|
@@ -10,16 +10,19 @@ const __dirname = path.dirname(__filename);
|
|
|
10
10
|
* Allows using aliases like "prod" instead of full server names
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
// Kept in the manager home; the package copy is read only as a fallback for a
|
|
14
|
+
// source checkout (see user-state.js, issue #87).
|
|
15
|
+
const ALIASES_NAME = 'server-aliases.json';
|
|
16
|
+
const LEGACY_ALIASES_FILE = path.join(__dirname, '..', '.server-aliases.json');
|
|
14
17
|
|
|
15
18
|
/**
|
|
16
19
|
* Load server aliases from configuration file
|
|
17
20
|
*/
|
|
18
21
|
function loadAliases() {
|
|
19
22
|
try {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
return JSON.parse(
|
|
23
|
+
const state = readUserState(ALIASES_NAME, LEGACY_ALIASES_FILE);
|
|
24
|
+
if (state) {
|
|
25
|
+
return JSON.parse(state.text);
|
|
23
26
|
}
|
|
24
27
|
} catch (error) {
|
|
25
28
|
console.error(`Warning: Could not load aliases: ${error.message}`);
|
|
@@ -32,7 +35,7 @@ function loadAliases() {
|
|
|
32
35
|
*/
|
|
33
36
|
function saveAliases(aliases) {
|
|
34
37
|
try {
|
|
35
|
-
|
|
38
|
+
writeUserState(ALIASES_NAME, JSON.stringify(aliases, null, 2));
|
|
36
39
|
return true;
|
|
37
40
|
} catch (error) {
|
|
38
41
|
console.error(`Error saving aliases: ${error.message}`);
|
|
@@ -0,0 +1,54 @@
|
|
|
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
|
+
/** Quote a POSIX path while preserving the documented ~/ home shorthand. */
|
|
32
|
+
export function shellPath(value) {
|
|
33
|
+
const text = String(value);
|
|
34
|
+
if (text === '~') return '"$HOME"';
|
|
35
|
+
if (text.startsWith('~/')) return `"$HOME"/${shellQuote(text.slice(2))}`;
|
|
36
|
+
return shellQuote(text);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Coerce a value to a safe non-negative integer for use in a command.
|
|
41
|
+
*
|
|
42
|
+
* Numeric tool arguments (line counts, ports, retention days) are declared as
|
|
43
|
+
* z.number() but still land inside command strings, where a non-finite or
|
|
44
|
+
* fractional value would serialise into something the shell reads oddly.
|
|
45
|
+
*
|
|
46
|
+
* @param {any} value - Value to coerce
|
|
47
|
+
* @param {number} fallback - Value used when the input is not a finite number
|
|
48
|
+
* @returns {number} A non-negative integer
|
|
49
|
+
*/
|
|
50
|
+
export function safeInteger(value, fallback) {
|
|
51
|
+
const n = Number(value);
|
|
52
|
+
if (!Number.isFinite(n)) return fallback;
|
|
53
|
+
return Math.max(0, Math.trunc(n));
|
|
54
|
+
}
|