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
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Split a shell command line into the simple commands it would run, for the
|
|
3
|
+
* per-server security policy.
|
|
4
|
+
*
|
|
5
|
+
* The policy used to test its regexes against the whole command line. An
|
|
6
|
+
* allow pattern such as `^docker ps` therefore only checked how a line
|
|
7
|
+
* started, and `docker ps; id` passed (GHSA-rfxw-26h6-7w42); a deny pattern
|
|
8
|
+
* such as `^rm ` missed `echo x; rm -rf /data` for the same reason. Splitting
|
|
9
|
+
* the line lets every command in a list or pipeline be checked on its own.
|
|
10
|
+
*
|
|
11
|
+
* This is a conservative reader, not a shell. Whatever it cannot place with
|
|
12
|
+
* confidence is reported so the caller can refuse it: command substitution
|
|
13
|
+
* (`$(…)`, backticks), process substitution, and redirections that write to a
|
|
14
|
+
* file. It does not recognise comments, so `ls # a; b` yields a second segment
|
|
15
|
+
* ` b` that a caller will refuse: a false refusal, never a missed command.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const CONTROL_OPERATORS = /^(;;|;&|&&|\|\||\|&)/;
|
|
19
|
+
const HARMLESS_WRITE_TARGETS = new Set(['/dev/null', '/dev/stdout', '/dev/stderr']);
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Index of the `)` closing the `(` at `open`, skipping quoted text and nested
|
|
23
|
+
* parentheses, or -1 when there is none.
|
|
24
|
+
* @param {string} text
|
|
25
|
+
* @param {number} open
|
|
26
|
+
*/
|
|
27
|
+
function closingParen(text, open) {
|
|
28
|
+
let depth = 0;
|
|
29
|
+
for (let i = open; i < text.length; i++) {
|
|
30
|
+
const ch = text[i];
|
|
31
|
+
if (ch === '\\') { i++; continue; }
|
|
32
|
+
if (ch === '\'') {
|
|
33
|
+
const end = text.indexOf('\'', i + 1);
|
|
34
|
+
if (end < 0) return -1;
|
|
35
|
+
i = end;
|
|
36
|
+
} else if (ch === '"') {
|
|
37
|
+
i++;
|
|
38
|
+
while (i < text.length && text[i] !== '"') i += text[i] === '\\' ? 2 : 1;
|
|
39
|
+
if (i >= text.length) return -1;
|
|
40
|
+
} else if (ch === '(') {
|
|
41
|
+
depth++;
|
|
42
|
+
} else if (ch === ')') {
|
|
43
|
+
depth--;
|
|
44
|
+
if (depth === 0) return i;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return -1;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Index of the backtick closing the one before `start`, or -1.
|
|
52
|
+
* @param {string} text
|
|
53
|
+
* @param {number} start
|
|
54
|
+
*/
|
|
55
|
+
function closingBacktick(text, start) {
|
|
56
|
+
for (let i = start; i < text.length; i++) {
|
|
57
|
+
if (text[i] === '\\') { i++; continue; }
|
|
58
|
+
if (text[i] === '`') return i;
|
|
59
|
+
}
|
|
60
|
+
return -1;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* @typedef {object} ShellSegments
|
|
65
|
+
* @property {string[]} segments - Each simple command, trimmed, in order
|
|
66
|
+
* @property {string[]} substitutions - The command text inside every `$(…)`,
|
|
67
|
+
* backtick pair or process substitution, split the same way, nested ones included
|
|
68
|
+
* @property {string[]} writes - Targets of redirections that open a file for
|
|
69
|
+
* writing; /dev/null, /dev/stdout, /dev/stderr and descriptor copies (`2>&1`)
|
|
70
|
+
* are not listed
|
|
71
|
+
* @property {string|null} problem - Why the line could not be read, if it could not
|
|
72
|
+
*/
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* @param {string} command
|
|
76
|
+
* @returns {ShellSegments}
|
|
77
|
+
*/
|
|
78
|
+
export function splitShellCommand(command) {
|
|
79
|
+
/** @type {ShellSegments} */
|
|
80
|
+
const result = { segments: [], substitutions: [], writes: [], problem: null };
|
|
81
|
+
const text = String(command);
|
|
82
|
+
let current = '';
|
|
83
|
+
|
|
84
|
+
const endSegment = () => {
|
|
85
|
+
if (current.trim()) result.segments.push(current.trim());
|
|
86
|
+
current = '';
|
|
87
|
+
};
|
|
88
|
+
/** @param {string} body */
|
|
89
|
+
const addSubstitution = body => {
|
|
90
|
+
const inner = splitShellCommand(body);
|
|
91
|
+
result.substitutions.push(...inner.segments, ...inner.substitutions);
|
|
92
|
+
result.writes.push(...inner.writes);
|
|
93
|
+
result.problem ||= inner.problem;
|
|
94
|
+
if (!inner.segments.length && !inner.substitutions.length) result.substitutions.push(body);
|
|
95
|
+
};
|
|
96
|
+
/** @param {string} reason */
|
|
97
|
+
const fail = reason => {
|
|
98
|
+
result.problem = reason;
|
|
99
|
+
return result;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
for (let i = 0; i < text.length;) {
|
|
103
|
+
const ch = text[i];
|
|
104
|
+
|
|
105
|
+
if (ch === '\\') {
|
|
106
|
+
current += text.slice(i, i + 2);
|
|
107
|
+
i += 2;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (ch === '\'') {
|
|
111
|
+
const end = text.indexOf('\'', i + 1);
|
|
112
|
+
if (end < 0) return fail('an unterminated single quote');
|
|
113
|
+
current += text.slice(i, end + 1);
|
|
114
|
+
i = end + 1;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (ch === '"') {
|
|
118
|
+
// Double quotes do not stop $(…) or backticks from running.
|
|
119
|
+
let j = i + 1;
|
|
120
|
+
while (j < text.length && text[j] !== '"') {
|
|
121
|
+
if (text[j] === '\\') { j += 2; continue; }
|
|
122
|
+
if (text[j] === '$' && text[j + 1] === '(') {
|
|
123
|
+
const end = closingParen(text, j + 1);
|
|
124
|
+
if (end < 0) return fail('an unterminated $(');
|
|
125
|
+
addSubstitution(text.slice(j + 2, end));
|
|
126
|
+
j = end + 1;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (text[j] === '`') {
|
|
130
|
+
const end = closingBacktick(text, j + 1);
|
|
131
|
+
if (end < 0) return fail('an unterminated backtick');
|
|
132
|
+
addSubstitution(text.slice(j + 1, end));
|
|
133
|
+
j = end + 1;
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
j++;
|
|
137
|
+
}
|
|
138
|
+
if (j >= text.length) return fail('an unterminated double quote');
|
|
139
|
+
current += text.slice(i, j + 1);
|
|
140
|
+
i = j + 1;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if ((ch === '$' || ch === '<' || ch === '>') && text[i + 1] === '(') {
|
|
144
|
+
// $(…) command substitution, <(…) and >(…) process substitution.
|
|
145
|
+
const end = closingParen(text, i + 1);
|
|
146
|
+
if (end < 0) return fail(`an unterminated ${ch}(`);
|
|
147
|
+
addSubstitution(text.slice(i + 2, end));
|
|
148
|
+
current += text.slice(i, end + 1);
|
|
149
|
+
i = end + 1;
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (ch === '`') {
|
|
153
|
+
const end = closingBacktick(text, i + 1);
|
|
154
|
+
if (end < 0) return fail('an unterminated backtick');
|
|
155
|
+
addSubstitution(text.slice(i + 1, end));
|
|
156
|
+
current += text.slice(i, end + 1);
|
|
157
|
+
i = end + 1;
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (ch === '>' || (ch === '&' && text[i + 1] === '>') || (ch === '<' && text[i + 1] === '>')) {
|
|
161
|
+
// >, >>, >|, &>, &>>, >&N and <> all open something for writing.
|
|
162
|
+
let j = i + (ch === '>' ? 1 : 2);
|
|
163
|
+
if (ch !== '<' && (text[j] === '>' || text[j] === '|')) j++;
|
|
164
|
+
let copiesDescriptor = false;
|
|
165
|
+
if (text[j] === '&') { copiesDescriptor = true; j++; }
|
|
166
|
+
while (text[j] === ' ' || text[j] === '\t') j++;
|
|
167
|
+
let k = j;
|
|
168
|
+
while (k < text.length && !/[\s;&|<>()]/.test(text[k])) k++;
|
|
169
|
+
const target = text.slice(j, k);
|
|
170
|
+
const harmless = (copiesDescriptor && /^(\d+|-)$/.test(target))
|
|
171
|
+
|| (ch !== '<' && HARMLESS_WRITE_TARGETS.has(target));
|
|
172
|
+
if (!harmless) result.writes.push(target || '(no target)');
|
|
173
|
+
current += text.slice(i, k);
|
|
174
|
+
i = k;
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
if (ch === ';' || ch === '\n' || ch === '|' || ch === '&') {
|
|
178
|
+
endSegment();
|
|
179
|
+
const operator = CONTROL_OPERATORS.exec(text.slice(i));
|
|
180
|
+
i += operator ? operator[0].length : 1;
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
current += ch;
|
|
184
|
+
i++;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
endSegment();
|
|
188
|
+
return result;
|
|
189
|
+
}
|
package/src/ssh-key-manager.js
CHANGED
|
@@ -1,29 +1,101 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { execFileSync, spawn } from 'child_process';
|
|
2
2
|
import fs from 'fs';
|
|
3
3
|
import path from 'path';
|
|
4
4
|
import os from 'os';
|
|
5
5
|
import crypto from 'crypto';
|
|
6
6
|
import { logger } from './logger.js';
|
|
7
7
|
|
|
8
|
-
//
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
// The standard OpenSSH file remains the default. The override also lets tests
|
|
9
|
+
// and headless deployments isolate trust without touching a user's key files.
|
|
10
|
+
function knownHostsPath() {
|
|
11
|
+
return process.env.SSH_MANAGER_KNOWN_HOSTS || path.join(os.homedir(), '.ssh', 'known_hosts');
|
|
12
|
+
}
|
|
11
13
|
|
|
12
|
-
/**
|
|
13
|
-
* Parse a known_hosts entry
|
|
14
|
-
*/
|
|
14
|
+
/** Parse ordinary, hashed and marker-prefixed OpenSSH known_hosts entries. */
|
|
15
15
|
function parseKnownHostEntry(line) {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
const
|
|
16
|
+
const parts = line.trim().split(/\s+/);
|
|
17
|
+
if (!parts[0] || parts[0].startsWith('#')) return null;
|
|
18
|
+
const marker = parts[0].startsWith('@') ? parts.shift() : null;
|
|
19
19
|
if (parts.length < 3) return null;
|
|
20
|
+
return { host: parts[0], keyType: parts[1], key: parts[2], marker,
|
|
21
|
+
comment: parts.slice(3).join(' ') || '' };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function hostEntryName(host, port) {
|
|
25
|
+
return Number(port) === 22 ? host.toLowerCase() : `[${host.toLowerCase()}]:${port}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function matchesHostPattern(pattern, host) {
|
|
29
|
+
if (pattern.startsWith('|1|')) {
|
|
30
|
+
const [, version, salt, expected] = pattern.split('|');
|
|
31
|
+
if (version !== '1' || !salt || !expected) return false;
|
|
32
|
+
const actual = crypto.createHmac('sha1', Buffer.from(salt, 'base64')).update(host).digest();
|
|
33
|
+
const hash = Buffer.from(expected, 'base64');
|
|
34
|
+
return actual.length === hash.length && crypto.timingSafeEqual(actual, hash);
|
|
35
|
+
}
|
|
36
|
+
const expression = pattern.toLowerCase().split('').map(char =>
|
|
37
|
+
char === '*' ? '.*' : char === '?' ? '.' : char.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('');
|
|
38
|
+
return new RegExp(`^${expression}$`).test(host);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function matchesHost(entry, host) {
|
|
42
|
+
let matched = false;
|
|
43
|
+
for (const pattern of entry.host.split(',')) {
|
|
44
|
+
if (pattern.startsWith('!')) {
|
|
45
|
+
if (matchesHostPattern(pattern.slice(1), host)) return false;
|
|
46
|
+
} else if (matchesHostPattern(pattern, host)) matched = true;
|
|
47
|
+
}
|
|
48
|
+
return matched;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function matchingEntries(host, port) {
|
|
52
|
+
let content;
|
|
53
|
+
try { content = fs.readFileSync(knownHostsPath(), 'utf8'); }
|
|
54
|
+
catch (error) { if (error.code === 'ENOENT') return []; throw error; }
|
|
55
|
+
const name = hostEntryName(host, port);
|
|
56
|
+
return content.split('\n').map(parseKnownHostEntry).filter(entry => entry && matchesHost(entry, name));
|
|
57
|
+
}
|
|
20
58
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
59
|
+
/** Prefer a stored key's algorithm so a multi-key server presents a trusted key. */
|
|
60
|
+
export function trustedHostKeyAlgorithms(host, port = 22) {
|
|
61
|
+
return [...new Set(matchingEntries(host, port)
|
|
62
|
+
.filter(entry => !entry.marker)
|
|
63
|
+
.flatMap(entry => entry.keyType === 'ssh-rsa'
|
|
64
|
+
? ['rsa-sha2-512', 'rsa-sha2-256', 'ssh-rsa'] : [entry.keyType]))];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Verify the actual handshake key. An unknown host is trusted on first use and
|
|
69
|
+
* that exact key is pinned synchronously before authentication can proceed.
|
|
70
|
+
* Existing entries, including hashed hostnames and revocations, fail closed.
|
|
71
|
+
*/
|
|
72
|
+
export function verifyHostKey(host, port, key) {
|
|
73
|
+
if (!Buffer.isBuffer(key) || key.length < 4) throw new Error('Invalid SSH host key');
|
|
74
|
+
const size = key.readUInt32BE(0);
|
|
75
|
+
if (size < 1 || size > key.length - 4) throw new Error('Invalid SSH host key');
|
|
76
|
+
const keyType = key.subarray(4, 4 + size).toString('ascii');
|
|
77
|
+
if (!/^[a-zA-Z0-9@._+-]+$/.test(keyType)) throw new Error('Invalid SSH host key type');
|
|
78
|
+
const encoded = key.toString('base64');
|
|
79
|
+
const entries = matchingEntries(host, port);
|
|
80
|
+
if (entries.some(entry => entry.marker === '@revoked' && entry.key === encoded)) {
|
|
81
|
+
throw new Error(`SSH host key is revoked for ${host}:${port}`);
|
|
82
|
+
}
|
|
83
|
+
if (entries.some(entry => !entry.marker && entry.key === encoded)) return true;
|
|
84
|
+
if (entries.length) {
|
|
85
|
+
throw new Error(`SSH host key changed or is not trusted for ${host}:${port}; verify the server identity before updating known_hosts`);
|
|
86
|
+
}
|
|
87
|
+
const name = hostEntryName(host, port);
|
|
88
|
+
if (/[\s,|!]/.test(name)) throw new Error('Invalid SSH hostname');
|
|
89
|
+
const file = knownHostsPath();
|
|
90
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
91
|
+
let prefix = '';
|
|
92
|
+
try {
|
|
93
|
+
const existing = fs.readFileSync(file, 'utf8');
|
|
94
|
+
if (existing && !existing.endsWith('\n')) prefix = '\n';
|
|
95
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
96
|
+
fs.appendFileSync(file, `${prefix}${name} ${keyType} ${encoded}\n`, { mode: 0o600 });
|
|
97
|
+
logger.info('SSH host key trusted on first use', { host, port });
|
|
98
|
+
return true;
|
|
27
99
|
}
|
|
28
100
|
|
|
29
101
|
/**
|
|
@@ -77,76 +149,51 @@ export async function getHostKeyFingerprint(host, port = 22) {
|
|
|
77
149
|
* Check if a host key exists in known_hosts
|
|
78
150
|
*/
|
|
79
151
|
export function isHostKnown(host, port = 22) {
|
|
80
|
-
|
|
81
|
-
return false;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
const content = fs.readFileSync(KNOWN_HOSTS_PATH, 'utf8');
|
|
85
|
-
const lines = content.split('\n');
|
|
86
|
-
|
|
87
|
-
// Format host entry as SSH does
|
|
88
|
-
const hostEntry = port === 22 ? host : `[${host}]:${port}`;
|
|
89
|
-
|
|
90
|
-
for (const line of lines) {
|
|
91
|
-
if (line.includes(hostEntry)) {
|
|
92
|
-
return true;
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
return false;
|
|
152
|
+
return matchingEntries(host, port).length > 0;
|
|
97
153
|
}
|
|
98
154
|
|
|
99
|
-
/**
|
|
100
|
-
* Get current host key from known_hosts
|
|
101
|
-
*/
|
|
155
|
+
/** Get matching trusted fingerprints without contacting the server. */
|
|
102
156
|
export function getCurrentHostKey(host, port = 22) {
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
// Format host entry as SSH does
|
|
111
|
-
const hostEntry = port === 22 ? host : `[${host}]:${port}`;
|
|
112
|
-
const keys = [];
|
|
113
|
-
|
|
114
|
-
for (const line of lines) {
|
|
115
|
-
if (line.includes(hostEntry)) {
|
|
116
|
-
const entry = parseKnownHostEntry(line);
|
|
117
|
-
if (entry) {
|
|
118
|
-
const keyData = Buffer.from(entry.key, 'base64');
|
|
119
|
-
const hash = crypto.createHash('sha256').update(keyData).digest('base64');
|
|
120
|
-
|
|
121
|
-
keys.push({
|
|
122
|
-
host: entry.host,
|
|
123
|
-
type: entry.keyType,
|
|
124
|
-
fingerprint: `SHA256:${hash}`,
|
|
125
|
-
fullKey: line
|
|
126
|
-
});
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
return keys.length > 0 ? keys : null;
|
|
157
|
+
const keys = matchingEntries(host, port).map(entry => ({
|
|
158
|
+
host: entry.host, type: entry.keyType,
|
|
159
|
+
fingerprint: `SHA256:${crypto.createHash('sha256').update(Buffer.from(entry.key, 'base64')).digest('base64')}`,
|
|
160
|
+
fullKey: `${entry.marker ? `${entry.marker} ` : ''}${entry.host} ${entry.keyType} ${entry.key}`,
|
|
161
|
+
}));
|
|
162
|
+
return keys.length ? keys : null;
|
|
132
163
|
}
|
|
133
164
|
|
|
134
165
|
/**
|
|
135
166
|
* Remove a host from known_hosts
|
|
136
167
|
*/
|
|
137
168
|
export function removeHostKey(host, port = 22) {
|
|
138
|
-
|
|
139
|
-
const hostEntry = port === 22 ? host : `[${host}]:${port}`;
|
|
169
|
+
const hostEntry = port === 22 ? host : `[${host}]:${port}`;
|
|
140
170
|
|
|
141
|
-
|
|
142
|
-
|
|
171
|
+
// Was it there to begin with? ssh-keygen -R succeeds either way, so without
|
|
172
|
+
// this the function would report success for a host it never touched — and a
|
|
173
|
+
// control plane would tell an operator it forgot a key that is still there.
|
|
174
|
+
// Return before touching ssh-keygen when there is nothing to remove: the
|
|
175
|
+
// command fails outright where no known_hosts file exists at all (a fresh CI
|
|
176
|
+
// runner, a container), and reporting that as an error would be wrong — there
|
|
177
|
+
// was simply no key.
|
|
178
|
+
if (!isHostKnown(host, port)) {
|
|
179
|
+
logger.info('No host key to remove', { host, port });
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
143
182
|
|
|
144
|
-
|
|
145
|
-
|
|
183
|
+
try {
|
|
184
|
+
// execFileSync, not execSync: arguments are passed to the process directly
|
|
185
|
+
// instead of through a shell. `host` comes from a server config, which an
|
|
186
|
+
// operator (or the control plane's own form) can set to anything, so a
|
|
187
|
+
// value containing a quote or $(...) used to be a command injection here —
|
|
188
|
+
// the same class of bug fixed across the database and backup builders.
|
|
189
|
+
execFileSync('ssh-keygen', ['-R', hostEntry, '-f', knownHostsPath()], { stdio: 'ignore' });
|
|
146
190
|
} catch (error) {
|
|
147
191
|
logger.error('Failed to remove host key', { host, port, error: error.message });
|
|
148
192
|
throw new Error(`Failed to remove host key: ${error.message}`);
|
|
149
193
|
}
|
|
194
|
+
|
|
195
|
+
logger.info('Host key removed', { host, port });
|
|
196
|
+
return true;
|
|
150
197
|
}
|
|
151
198
|
|
|
152
199
|
/**
|
|
@@ -159,7 +206,7 @@ export async function addHostKey(host, port = 22, keyData = null) {
|
|
|
159
206
|
// file can be replaced, and the check adds a race without preventing the
|
|
160
207
|
// failure it appears to guard against.
|
|
161
208
|
try {
|
|
162
|
-
fs.copyFileSync(
|
|
209
|
+
fs.copyFileSync(knownHostsPath(), `${knownHostsPath()}.mcp-backup`);
|
|
163
210
|
} catch (error) {
|
|
164
211
|
if (error.code !== 'ENOENT') throw error;
|
|
165
212
|
}
|
|
@@ -176,11 +223,11 @@ export async function addHostKey(host, port = 22, keyData = null) {
|
|
|
176
223
|
// Ensure .ssh directory exists. No existsSync guard: mkdirSync with
|
|
177
224
|
// recursive:true is already a no-op on an existing directory, and checking
|
|
178
225
|
// first only opens a window where the directory can change underneath us.
|
|
179
|
-
const sshDir = path.dirname(
|
|
226
|
+
const sshDir = path.dirname(knownHostsPath());
|
|
180
227
|
fs.mkdirSync(sshDir, { mode: 0o700, recursive: true });
|
|
181
228
|
|
|
182
229
|
// Append to known_hosts
|
|
183
|
-
fs.appendFileSync(
|
|
230
|
+
fs.appendFileSync(knownHostsPath(), keyData + '\n', { mode: 0o600 });
|
|
184
231
|
|
|
185
232
|
logger.info('Host key added', { host, port });
|
|
186
233
|
return true;
|
|
@@ -251,11 +298,11 @@ export async function hasHostKeyChanged(host, port = 22) {
|
|
|
251
298
|
* List all known hosts
|
|
252
299
|
*/
|
|
253
300
|
export function listKnownHosts() {
|
|
254
|
-
if (!fs.existsSync(
|
|
301
|
+
if (!fs.existsSync(knownHostsPath())) {
|
|
255
302
|
return [];
|
|
256
303
|
}
|
|
257
304
|
|
|
258
|
-
const content = fs.readFileSync(
|
|
305
|
+
const content = fs.readFileSync(knownHostsPath(), 'utf8');
|
|
259
306
|
const lines = content.split('\n');
|
|
260
307
|
const hosts = new Map();
|
|
261
308
|
|
package/src/ssh-manager.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { Client } from 'ssh2';
|
|
2
2
|
import fs from 'fs';
|
|
3
3
|
import os from 'os';
|
|
4
|
-
import {
|
|
4
|
+
import { trustedHostKeyAlgorithms, verifyHostKey } from './ssh-key-manager.js';
|
|
5
5
|
import { logger } from './logger.js';
|
|
6
|
+
import { shellPath } from './shell-quote.js';
|
|
6
7
|
|
|
7
8
|
// Validate liveness-probe output across shells (bash, cmd.exe, PowerShell).
|
|
8
9
|
// Normalize CRLF, stray quotes/backslashes and case before matching so quoted
|
|
@@ -107,46 +108,20 @@ class SSHManager {
|
|
|
107
108
|
}
|
|
108
109
|
};
|
|
109
110
|
|
|
110
|
-
//
|
|
111
|
+
// Verify the key ssh2 received on this connection, never a second
|
|
112
|
+
// ssh-keyscan connection. First contact remains noninteractive TOFU;
|
|
113
|
+
// a changed known key is refused before credentials are sent.
|
|
114
|
+
// Up to 3.8.5 this callback accepted every key (GHSA-cwg3-pfmm-w8rm).
|
|
111
115
|
if (this.hostKeyVerification) {
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
logger.info('Host key verified', { host, port });
|
|
121
|
-
return true;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
// Host is not known
|
|
125
|
-
logger.info('New host detected', { host, port });
|
|
126
|
-
|
|
127
|
-
// If autoAcceptHostKey is enabled, accept and add the key
|
|
128
|
-
if (this.autoAcceptHostKey) {
|
|
129
|
-
logger.info('Auto-accept host key', { host, port });
|
|
130
|
-
// Schedule key addition after connection
|
|
131
|
-
setImmediate(async () => {
|
|
132
|
-
try {
|
|
133
|
-
await addHostKey(host, port);
|
|
134
|
-
logger.info('Host key added', { host, port });
|
|
135
|
-
} catch (err) {
|
|
136
|
-
logger.warn('Failed to add host key', {
|
|
137
|
-
host,
|
|
138
|
-
port,
|
|
139
|
-
error: err.message
|
|
140
|
-
});
|
|
141
|
-
}
|
|
142
|
-
});
|
|
143
|
-
return true;
|
|
116
|
+
const trusted = trustedHostKeyAlgorithms(this.config.host, this.config.port || 22);
|
|
117
|
+
if (trusted.length) connConfig.algorithms.serverHostKey = trusted;
|
|
118
|
+
connConfig.hostVerifier = key => {
|
|
119
|
+
try {
|
|
120
|
+
return verifyHostKey(this.config.host, this.config.port || 22, key);
|
|
121
|
+
} catch (error) {
|
|
122
|
+
reject(error);
|
|
123
|
+
return false;
|
|
144
124
|
}
|
|
145
|
-
|
|
146
|
-
// For backward compatibility, accept new hosts by default
|
|
147
|
-
// In production, you might want to prompt the user or check a whitelist
|
|
148
|
-
logger.warn('Auto-accepting new host', { host, port });
|
|
149
|
-
return true;
|
|
150
125
|
};
|
|
151
126
|
}
|
|
152
127
|
|
|
@@ -167,6 +142,14 @@ class SSHManager {
|
|
|
167
142
|
if (keyPath) {
|
|
168
143
|
const resolvedKeyPath = keyPath.replace('~', os.homedir());
|
|
169
144
|
connConfig.privateKey = fs.readFileSync(resolvedKeyPath);
|
|
145
|
+
// OpenSSH user certificate (<key>-cert.pub): sent to the server as the
|
|
146
|
+
// identity while privateKey signs. Read on every connect, so a renewed
|
|
147
|
+
// short-lived certificate is picked up without restarting the server.
|
|
148
|
+
// Requires an ssh2 release with certificate support (mscdex/ssh2#1495);
|
|
149
|
+
// older ssh2 ignores the unknown option and authenticates with the key.
|
|
150
|
+
if (this.config.certPath) {
|
|
151
|
+
connConfig.publicKey = fs.readFileSync(this.config.certPath.replace('~', os.homedir()));
|
|
152
|
+
}
|
|
170
153
|
if (this.config.passphrase) {
|
|
171
154
|
connConfig.passphrase = this.config.passphrase;
|
|
172
155
|
}
|
|
@@ -189,7 +172,8 @@ class SSHManager {
|
|
|
189
172
|
}
|
|
190
173
|
|
|
191
174
|
const { timeout = 30000, cwd, rawCommand = false, stdin = null } = options;
|
|
192
|
-
|
|
175
|
+
// Quoted: a working directory is data, never shell code (GHSA-37fv-fcpc-j236).
|
|
176
|
+
const fullCommand = (cwd && !rawCommand) ? `cd -- ${shellPath(cwd)} && ${command}` : command;
|
|
193
177
|
|
|
194
178
|
return new Promise((resolve, reject) => {
|
|
195
179
|
let stdout = '';
|
|
@@ -297,7 +281,7 @@ class SSHManager {
|
|
|
297
281
|
}
|
|
298
282
|
|
|
299
283
|
const { cwd, onStdout, onStderr } = options;
|
|
300
|
-
const fullCommand = cwd ? `cd ${cwd} && ${command}` : command;
|
|
284
|
+
const fullCommand = cwd ? `cd -- ${shellPath(cwd)} && ${command}` : command;
|
|
301
285
|
|
|
302
286
|
return new Promise((resolve, reject) => {
|
|
303
287
|
this.client.exec(fullCommand, (err, stream) => {
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Settings a user changes while the server runs: hooks, command and server
|
|
3
|
+
* aliases, the active profile.
|
|
4
|
+
*
|
|
5
|
+
* Up to 3.8.5 they were written inside the installed package. Every upgrade
|
|
6
|
+
* replaced that directory, so a change made through a tool vanished on the
|
|
7
|
+
* next `npm install -g`, and the server needed write access to its own
|
|
8
|
+
* install directory (issue #87). They now live beside the .env, in
|
|
9
|
+
* SSH_MANAGER_HOME (~/.ssh-manager by default), readable by their owner only.
|
|
10
|
+
*
|
|
11
|
+
* The old file is still read while the new one does not exist, so a source
|
|
12
|
+
* checkout keeps what it had until its next change writes the new file.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import fs from 'fs';
|
|
16
|
+
import path from 'path';
|
|
17
|
+
import { managerHome } from './config-paths.js';
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param {string} name - File name inside the manager home
|
|
21
|
+
* @returns {string}
|
|
22
|
+
*/
|
|
23
|
+
function userStatePath(name) {
|
|
24
|
+
return path.join(managerHome(), name);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Read a state file, falling back to its pre-4.0 location inside the package.
|
|
29
|
+
* @param {string} name - File name inside the manager home
|
|
30
|
+
* @param {string} [legacyFile] - Absolute path of the old file, if any
|
|
31
|
+
* @returns {{file: string, text: string}|null} null when neither exists
|
|
32
|
+
*/
|
|
33
|
+
export function readUserState(name, legacyFile) {
|
|
34
|
+
for (const file of [userStatePath(name), legacyFile]) {
|
|
35
|
+
if (!file) continue;
|
|
36
|
+
try {
|
|
37
|
+
return { file, text: fs.readFileSync(file, 'utf8') };
|
|
38
|
+
} catch (error) {
|
|
39
|
+
if (error.code !== 'ENOENT') throw error;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Replace a state file atomically, creating the manager home if needed. The
|
|
47
|
+
* directory is created 0700 and the file 0600: these files name servers and
|
|
48
|
+
* commands, which are nobody else's business on a shared machine.
|
|
49
|
+
* @param {string} name - File name inside the manager home
|
|
50
|
+
* @param {string} text - Complete new contents
|
|
51
|
+
* @returns {string} The path written
|
|
52
|
+
*/
|
|
53
|
+
export function writeUserState(name, text) {
|
|
54
|
+
const file = userStatePath(name);
|
|
55
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
56
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
57
|
+
fs.writeFileSync(temp, text, { mode: 0o600 });
|
|
58
|
+
fs.renameSync(temp, file);
|
|
59
|
+
return file;
|
|
60
|
+
}
|