mcp-ssh-manager 3.8.5 → 3.8.7
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 +116 -0
- package/README.md +36 -11
- 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 +9 -5
- package/profiles/default.json +6 -4
- package/server.json +2 -2
- package/skills/ssh-manager/SKILL.md +80 -0
- package/src/backup-manager.js +70 -1
- package/src/command-aliases.js +9 -6
- package/src/config-loader.js +5 -0
- package/src/config-paths.js +12 -0
- package/src/database-manager.js +200 -21
- package/src/deploy-helper.js +15 -7
- package/src/hooks-system.js +298 -57
- package/src/index.js +59 -27
- package/src/logger.js +43 -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 +8 -0
- package/src/shell-segments.js +189 -0
- package/src/ssh-key-manager.js +123 -76
- package/src/ssh-manager.js +25 -41
- package/src/user-state.js +60 -0
- package/.hooks-config.json +0 -131
package/src/index.js
CHANGED
|
@@ -89,6 +89,9 @@ import {
|
|
|
89
89
|
generateBackupId,
|
|
90
90
|
getBackupMetadataPath,
|
|
91
91
|
getBackupFilePath,
|
|
92
|
+
assertSafeBackupId,
|
|
93
|
+
buildReadMetadataCommand,
|
|
94
|
+
buildEnsureBackupDirCommand,
|
|
92
95
|
buildMySQLDumpCommand,
|
|
93
96
|
buildPostgreSQLDumpCommand,
|
|
94
97
|
buildMongoDBDumpCommand,
|
|
@@ -99,7 +102,8 @@ import {
|
|
|
99
102
|
buildListBackupsCommand,
|
|
100
103
|
parseBackupsList,
|
|
101
104
|
buildCleanupCommand,
|
|
102
|
-
buildCronScheduleCommand
|
|
105
|
+
buildCronScheduleCommand,
|
|
106
|
+
isCronSchedule
|
|
103
107
|
} from './backup-manager.js';
|
|
104
108
|
import {
|
|
105
109
|
HEALTH_STATUS,
|
|
@@ -143,7 +147,7 @@ import {
|
|
|
143
147
|
} from './database-manager.js';
|
|
144
148
|
import { loadToolConfig, isToolEnabled } from './tool-config-manager.js';
|
|
145
149
|
import { evaluatePolicy } from './policy.js';
|
|
146
|
-
import { shellQuote, safeInteger } from './shell-quote.js';
|
|
150
|
+
import { shellQuote, shellPath, safeInteger } from './shell-quote.js';
|
|
147
151
|
import { auditLog } from './audit.js';
|
|
148
152
|
|
|
149
153
|
const __filename = fileURLToPath(import.meta.url);
|
|
@@ -267,7 +271,13 @@ async function loadServerConfig() {
|
|
|
267
271
|
async function getServerConfig(serverName) {
|
|
268
272
|
if (!serverName) return null;
|
|
269
273
|
const servers = await loadServerConfig();
|
|
270
|
-
|
|
274
|
+
// The same resolution getConnection() applies: aliases, case, a unique part
|
|
275
|
+
// of a name, a host match. This used to be an exact-key lookup, so "p" or a
|
|
276
|
+
// freshly added alias found no configuration here — no policy, unrestricted —
|
|
277
|
+
// while the connection resolved it to the readonly "prod" and ran the command
|
|
278
|
+
// there (GHSA-mq9f-5385-rjf4). An ambiguous name throws here as it does there.
|
|
279
|
+
const name = resolveServerName(String(serverName), servers);
|
|
280
|
+
return (name && servers[String(name).toLowerCase()]) || null;
|
|
271
281
|
}
|
|
272
282
|
|
|
273
283
|
// Apply policy + audit a denial in one shot. Returns null when allowed; returns
|
|
@@ -719,9 +729,9 @@ registerToolConditional(
|
|
|
719
729
|
if (workingDir) {
|
|
720
730
|
if (platform === 'windows') {
|
|
721
731
|
const escapedDir = workingDir.replace(/'/g, '\'\'');
|
|
722
|
-
fullCommand = `Set-Location '${escapedDir}'; ${expandedCommand}`;
|
|
732
|
+
fullCommand = `Set-Location -LiteralPath '${escapedDir}'; ${expandedCommand}`;
|
|
723
733
|
} else {
|
|
724
|
-
fullCommand = `cd ${workingDir} && ${expandedCommand}`;
|
|
734
|
+
fullCommand = `cd -- ${shellPath(workingDir)} && ${expandedCommand}`;
|
|
725
735
|
}
|
|
726
736
|
} else {
|
|
727
737
|
fullCommand = expandedCommand;
|
|
@@ -1644,7 +1654,11 @@ registerToolConditional(
|
|
|
1644
1654
|
async ({ server: serverName, name }) => {
|
|
1645
1655
|
try {
|
|
1646
1656
|
const ssh = await getConnection(serverName);
|
|
1647
|
-
|
|
1657
|
+
// The session keeps the server's own name, not what the caller typed: a
|
|
1658
|
+
// partial name or an alias resolved now must not resolve to another
|
|
1659
|
+
// server, or to none, for every command sent later (GHSA-mq9f-5385-rjf4).
|
|
1660
|
+
const canonical = resolveServerName(serverName, await loadServerConfig()) || serverName;
|
|
1661
|
+
const session = await createSession(canonical, ssh);
|
|
1648
1662
|
|
|
1649
1663
|
const sessionName = name || `Session on ${serverName}`;
|
|
1650
1664
|
|
|
@@ -1956,9 +1970,9 @@ registerToolConditional(
|
|
|
1956
1970
|
if (platform === 'windows') {
|
|
1957
1971
|
// Single-quote escaping: replace ' with '' (PowerShell convention)
|
|
1958
1972
|
const escapedDir = workingDir.replace(/'/g, '\'\'');
|
|
1959
|
-
fullCommand = `Set-Location '${escapedDir}'; ${command}`;
|
|
1973
|
+
fullCommand = `Set-Location -LiteralPath '${escapedDir}'; ${command}`;
|
|
1960
1974
|
} else {
|
|
1961
|
-
fullCommand = `cd ${workingDir} && ${command}`;
|
|
1975
|
+
fullCommand = `cd -- ${shellPath(workingDir)} && ${command}`;
|
|
1962
1976
|
}
|
|
1963
1977
|
} else {
|
|
1964
1978
|
fullCommand = command;
|
|
@@ -2292,7 +2306,7 @@ registerToolConditional(
|
|
|
2292
2306
|
const deployServers = await loadServerConfig();
|
|
2293
2307
|
const deployServerConfig = deployServers[server.toLowerCase()];
|
|
2294
2308
|
for (const step of strategy.steps) {
|
|
2295
|
-
const command = step.command.replace('{{tempFile}}', tempFile);
|
|
2309
|
+
const command = step.command.replace('{{tempFile}}', () => shellQuote(tempFile));
|
|
2296
2310
|
|
|
2297
2311
|
// step.stdin carries the sudo password for steps that need it, so it
|
|
2298
2312
|
// never reaches the remote command line (issue #34).
|
|
@@ -2403,16 +2417,16 @@ registerToolConditional(
|
|
|
2403
2417
|
if (cwd) {
|
|
2404
2418
|
if (platform === 'windows') {
|
|
2405
2419
|
const escapedDir = cwd.replace(/'/g, '\'\'');
|
|
2406
|
-
fullCommand = `Set-Location '${escapedDir}'; ${fullCommand}`;
|
|
2420
|
+
fullCommand = `Set-Location -LiteralPath '${escapedDir}'; ${fullCommand}`;
|
|
2407
2421
|
} else {
|
|
2408
|
-
fullCommand = `cd ${cwd} && ${fullCommand}`;
|
|
2422
|
+
fullCommand = `cd -- ${shellPath(cwd)} && ${fullCommand}`;
|
|
2409
2423
|
}
|
|
2410
2424
|
} else if (serverConfig?.defaultDir) {
|
|
2411
2425
|
if (platform === 'windows') {
|
|
2412
2426
|
const escapedDir = serverConfig.defaultDir.replace(/'/g, '\'\'');
|
|
2413
|
-
fullCommand = `Set-Location '${escapedDir}'; ${fullCommand}`;
|
|
2427
|
+
fullCommand = `Set-Location -LiteralPath '${escapedDir}'; ${fullCommand}`;
|
|
2414
2428
|
} else {
|
|
2415
|
-
fullCommand = `cd ${serverConfig.defaultDir} && ${fullCommand}`;
|
|
2429
|
+
fullCommand = `cd -- ${shellPath(serverConfig.defaultDir)} && ${fullCommand}`;
|
|
2416
2430
|
}
|
|
2417
2431
|
}
|
|
2418
2432
|
|
|
@@ -3460,7 +3474,7 @@ registerToolConditional(
|
|
|
3460
3474
|
const metadataPath = getBackupMetadataPath(backupId, backupDirectory);
|
|
3461
3475
|
|
|
3462
3476
|
// Ensure backup directory exists with proper error handling
|
|
3463
|
-
const mkdirResult = await ssh.execCommand(
|
|
3477
|
+
const mkdirResult = await ssh.execCommand(buildEnsureBackupDirCommand(backupDirectory));
|
|
3464
3478
|
if (mkdirResult.code !== 0) {
|
|
3465
3479
|
throw new Error(`Failed to create backup directory: ${mkdirResult.stderr || mkdirResult.stdout}`);
|
|
3466
3480
|
}
|
|
@@ -3731,12 +3745,14 @@ registerToolConditional(
|
|
|
3731
3745
|
if (denied) return denied;
|
|
3732
3746
|
|
|
3733
3747
|
try {
|
|
3748
|
+
// Checked before anything connects: an ID that is not a plain file name
|
|
3749
|
+
// is refused outright, and the one that passes is still quoted.
|
|
3750
|
+
assertSafeBackupId(backupId);
|
|
3734
3751
|
const ssh = await getConnection(serverName);
|
|
3735
3752
|
const backupDirectory = backupDir || DEFAULT_BACKUP_DIR;
|
|
3736
|
-
const metadataPath = getBackupMetadataPath(backupId, backupDirectory);
|
|
3737
3753
|
|
|
3738
3754
|
// Read backup metadata
|
|
3739
|
-
const metadataResult = await ssh.execCommand(
|
|
3755
|
+
const metadataResult = await ssh.execCommand(buildReadMetadataCommand(backupId, backupDirectory));
|
|
3740
3756
|
if (metadataResult.code !== 0) {
|
|
3741
3757
|
throw new Error(`Backup not found: ${backupId}`);
|
|
3742
3758
|
}
|
|
@@ -3850,6 +3866,16 @@ registerToolConditional(
|
|
|
3850
3866
|
if (denied) return denied;
|
|
3851
3867
|
|
|
3852
3868
|
try {
|
|
3869
|
+
// The name becomes a file name, a cron comment and a find pattern, and
|
|
3870
|
+
// the schedule the first fields of a crontab line, where anything past
|
|
3871
|
+
// the fifth field is the command cron runs and a line break starts a
|
|
3872
|
+
// new job. Both are checked before anything reaches the server.
|
|
3873
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name)) {
|
|
3874
|
+
throw new Error('Backup name may only contain letters, digits, ".", "_" and "-"');
|
|
3875
|
+
}
|
|
3876
|
+
if (!isCronSchedule(schedule)) {
|
|
3877
|
+
throw new Error('Schedule must be five cron fields (e.g. "0 2 * * *") or a macro such as @daily');
|
|
3878
|
+
}
|
|
3853
3879
|
const ssh = await getConnection(serverName);
|
|
3854
3880
|
|
|
3855
3881
|
// Build backup script path
|
|
@@ -3871,29 +3897,31 @@ registerToolConditional(
|
|
|
3871
3897
|
scriptContent += `BACKUP_FILE="${backupFile}"\n\n`;
|
|
3872
3898
|
scriptContent += 'mkdir -p "$BACKUP_DIR"\n\n';
|
|
3873
3899
|
|
|
3874
|
-
// Add backup command based on type
|
|
3900
|
+
// Add backup command based on type. The script runs later from cron, so
|
|
3901
|
+
// a value spliced in raw here would run every night, not once.
|
|
3875
3902
|
switch (type) {
|
|
3876
3903
|
case BACKUP_TYPES.MYSQL:
|
|
3877
|
-
scriptContent += `mysqldump --single-transaction --routines --triggers ${database} | gzip > "$BACKUP_FILE"\n`;
|
|
3904
|
+
scriptContent += `mysqldump --single-transaction --routines --triggers ${shellQuote(database)} | gzip > "$BACKUP_FILE"\n`;
|
|
3878
3905
|
break;
|
|
3879
3906
|
case BACKUP_TYPES.POSTGRESQL:
|
|
3880
|
-
scriptContent += `pg_dump --format=custom --clean --if-exists ${database} | gzip > "$BACKUP_FILE"\n`;
|
|
3907
|
+
scriptContent += `pg_dump --format=custom --clean --if-exists ${shellQuote(database)} | gzip > "$BACKUP_FILE"\n`;
|
|
3881
3908
|
break;
|
|
3882
3909
|
case BACKUP_TYPES.MONGODB:
|
|
3883
|
-
scriptContent += `mongodump --db ${database} --out /tmp/mongo_\${RANDOM} && tar -czf "$BACKUP_FILE" -C /tmp mongo_*\n`;
|
|
3910
|
+
scriptContent += `mongodump --db ${shellQuote(database)} --out /tmp/mongo_\${RANDOM} && tar -czf "$BACKUP_FILE" -C /tmp mongo_*\n`;
|
|
3884
3911
|
break;
|
|
3885
3912
|
case BACKUP_TYPES.FILES:
|
|
3886
|
-
scriptContent += `tar -czf "$BACKUP_FILE" ${paths.join(' ')}\n`;
|
|
3913
|
+
scriptContent += `tar -czf "$BACKUP_FILE" ${(paths || []).map(shellQuote).join(' ')}\n`;
|
|
3887
3914
|
break;
|
|
3888
3915
|
}
|
|
3889
3916
|
|
|
3890
3917
|
// Add cleanup command
|
|
3891
3918
|
scriptContent += '\n# Cleanup old backups\n';
|
|
3892
|
-
scriptContent += `find "$BACKUP_DIR" -name "*_${name}_*" -type f -mtime +${retention} -delete\n`;
|
|
3919
|
+
scriptContent += `find "$BACKUP_DIR" -name "*_${name}_*" -type f -mtime +${safeInteger(retention, 7)} -delete\n`;
|
|
3893
3920
|
|
|
3894
|
-
// Save script to remote server
|
|
3895
|
-
|
|
3896
|
-
|
|
3921
|
+
// Save script to remote server. printf, not echo: dash's echo rewrites
|
|
3922
|
+
// backslashes, which would alter a quoted path inside the script.
|
|
3923
|
+
const quotedPath = shellQuote(scriptPath);
|
|
3924
|
+
await ssh.execCommand(`printf '%s' ${shellQuote(scriptContent)} > ${quotedPath} && chmod +x ${quotedPath}`);
|
|
3897
3925
|
|
|
3898
3926
|
// Add to crontab
|
|
3899
3927
|
const cronComment = `ssh-manager-backup-${name}`;
|
|
@@ -4824,7 +4852,7 @@ registerToolConditional(
|
|
|
4824
4852
|
registerToolConditional(
|
|
4825
4853
|
'ssh_db_query',
|
|
4826
4854
|
{
|
|
4827
|
-
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
|
|
4855
|
+
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.',
|
|
4828
4856
|
inputSchema: {
|
|
4829
4857
|
server: z.string().describe('Server name'),
|
|
4830
4858
|
type: z.enum(['mysql', 'postgresql', 'mongodb'])
|
|
@@ -4886,7 +4914,11 @@ registerToolConditional(
|
|
|
4886
4914
|
// Execute query
|
|
4887
4915
|
const result = await ssh.execCommand(queryCommand);
|
|
4888
4916
|
|
|
4889
|
-
|
|
4917
|
+
// The MySQL JSON output is piped through awk, whose exit status hides the
|
|
4918
|
+
// client's: a write refused by the read-only transaction (ERROR 1792) or
|
|
4919
|
+
// a syntax error would otherwise come back as an empty result.
|
|
4920
|
+
const clientError = type === DB_TYPES.MYSQL && /^ERROR \d+/m.test(result.stderr || '');
|
|
4921
|
+
if (result.code !== 0 || clientError) {
|
|
4890
4922
|
throw new Error(`Query failed: ${result.stderr || result.stdout}`);
|
|
4891
4923
|
}
|
|
4892
4924
|
|
package/src/logger.js
CHANGED
|
@@ -5,10 +5,7 @@
|
|
|
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
|
|
14
11
|
/**
|
|
@@ -78,23 +75,49 @@ class Logger {
|
|
|
78
75
|
// Enable verbose mode from environment
|
|
79
76
|
this.verbose = process.env.SSH_VERBOSE === 'true';
|
|
80
77
|
|
|
81
|
-
// Log file path
|
|
82
|
-
this.logFile = process.env.SSH_LOG_FILE || path.join(__dirname, '..', '.ssh-manager.log');
|
|
83
|
-
|
|
84
|
-
// Command history file
|
|
85
|
-
this.historyFile = path.join(__dirname, '..', '.ssh-command-history.json');
|
|
86
|
-
|
|
87
78
|
// Initialize command history
|
|
88
79
|
this.commandHistory = this.loadCommandHistory();
|
|
89
80
|
}
|
|
90
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
|
+
|
|
91
113
|
/**
|
|
92
114
|
* Load command history from file
|
|
93
115
|
*/
|
|
94
116
|
loadCommandHistory() {
|
|
95
117
|
try {
|
|
96
|
-
|
|
97
|
-
|
|
118
|
+
const file = this.historyFile;
|
|
119
|
+
if (file && fs.existsSync(file)) {
|
|
120
|
+
const data = fs.readFileSync(file, 'utf8');
|
|
98
121
|
return JSON.parse(data);
|
|
99
122
|
}
|
|
100
123
|
} catch (error) {
|
|
@@ -124,7 +147,8 @@ class Logger {
|
|
|
124
147
|
}
|
|
125
148
|
|
|
126
149
|
try {
|
|
127
|
-
|
|
150
|
+
const file = this.historyFile;
|
|
151
|
+
if (file) fs.writeFileSync(file, JSON.stringify(this.commandHistory, null, 2), { mode: 0o600 });
|
|
128
152
|
} catch (error) {
|
|
129
153
|
// Ignore write errors
|
|
130
154
|
}
|
|
@@ -174,9 +198,11 @@ class Logger {
|
|
|
174
198
|
// Output to stderr for proper MCP logging
|
|
175
199
|
console.error(formatted.console);
|
|
176
200
|
|
|
177
|
-
// Also write to file
|
|
201
|
+
// Also write to file, readable by its owner only: it records the commands
|
|
202
|
+
// run on remote servers.
|
|
178
203
|
try {
|
|
179
|
-
|
|
204
|
+
const file = this.logFile;
|
|
205
|
+
if (file) fs.appendFileSync(file, formatted.file + '\n', { mode: 0o600 });
|
|
180
206
|
} catch (error) {
|
|
181
207
|
// Ignore file write errors
|
|
182
208
|
}
|
|
@@ -298,8 +324,8 @@ class Logger {
|
|
|
298
324
|
clear() {
|
|
299
325
|
this.commandHistory = [];
|
|
300
326
|
try {
|
|
301
|
-
fs.writeFileSync(this.historyFile, '[]');
|
|
302
|
-
fs.writeFileSync(this.logFile, '');
|
|
327
|
+
if (this.historyFile) fs.writeFileSync(this.historyFile, '[]', { mode: 0o600 });
|
|
328
|
+
if (this.logFile) fs.writeFileSync(this.logFile, '', { mode: 0o600 });
|
|
303
329
|
this.info('Logs and history cleared');
|
|
304
330
|
} catch (error) {
|
|
305
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}`);
|
package/src/shell-quote.js
CHANGED
|
@@ -28,6 +28,14 @@ export function shellQuote(value) {
|
|
|
28
28
|
return SQ + String(value).replace(/'/g, SQ + '\\' + SQ + SQ) + SQ;
|
|
29
29
|
}
|
|
30
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
|
+
|
|
31
39
|
/**
|
|
32
40
|
* Coerce a value to a safe non-negative integer for use in a command.
|
|
33
41
|
*
|