mcp-ssh-manager 3.8.5 → 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 +80 -0
- package/README.md +12 -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 +5 -3
- package/profiles/default.json +6 -4
- package/server.json +2 -2
- package/src/backup-manager.js +24 -1
- package/src/command-aliases.js +9 -6
- 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 +39 -22
- 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 +17 -41
- package/src/user-state.js +60 -0
- package/.hooks-config.json +0 -131
package/src/database-manager.js
CHANGED
|
@@ -393,6 +393,7 @@ export function buildMySQLQueryCommand(options) {
|
|
|
393
393
|
if (!isSafeQuery(query)) {
|
|
394
394
|
throw new Error('Only SELECT queries are allowed');
|
|
395
395
|
}
|
|
396
|
+
const script = readOnlyScript(DB_TYPES.MYSQL, query);
|
|
396
397
|
|
|
397
398
|
let command = 'mysql';
|
|
398
399
|
if (user) command += ` -u${shellQuote(user)}`;
|
|
@@ -408,9 +409,9 @@ export function buildMySQLQueryCommand(options) {
|
|
|
408
409
|
// Use JSON output if MySQL 5.7.8+. The awk pipe stays on the heredoc opening line so
|
|
409
410
|
// the terminator remains alone on its own line.
|
|
410
411
|
const awk = 'awk \'BEGIN{print "["} {if(NR>1)print ","; printf "{\\"row\\":%d,\\"data\\":\\"%s\\"}", NR, $0} END{print "]"}\'';
|
|
411
|
-
command += ` --batch --skip-column-names${buildHeredoc(
|
|
412
|
+
command += ` --batch --skip-column-names${buildHeredoc(script, { pipeline: `| ${awk}` })}`;
|
|
412
413
|
} else {
|
|
413
|
-
command += buildHeredoc(
|
|
414
|
+
command += buildHeredoc(script);
|
|
414
415
|
}
|
|
415
416
|
|
|
416
417
|
return command;
|
|
@@ -431,14 +432,16 @@ export function buildPostgreSQLQueryCommand(options) {
|
|
|
431
432
|
command = `PGPASSWORD=${shellQuote(password)} `;
|
|
432
433
|
}
|
|
433
434
|
|
|
434
|
-
|
|
435
|
+
// -q keeps the BEGIN/ROLLBACK of the read-only wrapper out of the output, and
|
|
436
|
+
// ON_ERROR_STOP keeps the query from running if the wrapper itself fails.
|
|
437
|
+
command += 'psql -q -v ON_ERROR_STOP=1';
|
|
435
438
|
if (user) command += ` -U ${shellQuote(user)}`;
|
|
436
439
|
if (host) command += ` -h ${shellQuote(host)}`;
|
|
437
440
|
if (port) command += ` -p ${shellQuote(port)}`;
|
|
438
441
|
command += ` -d ${shellQuote(database)}`;
|
|
439
442
|
// Feed SQL via stdin (quoted heredoc) instead of `-c "${query}"` so the remote shell
|
|
440
443
|
// never parses it. See buildHeredoc and issue #44.
|
|
441
|
-
command += buildHeredoc(query);
|
|
444
|
+
command += buildHeredoc(readOnlyScript(DB_TYPES.POSTGRESQL, query));
|
|
442
445
|
|
|
443
446
|
return command;
|
|
444
447
|
}
|
|
@@ -456,38 +459,214 @@ export function buildMongoDBQueryCommand(options) {
|
|
|
456
459
|
if (password) command += ` --password ${shellQuote(password)}`;
|
|
457
460
|
command += ` ${shellQuote(database)}`;
|
|
458
461
|
// Feed the JS script via stdin (quoted heredoc) instead of `--eval "..."` so the
|
|
459
|
-
// remote shell never expands backticks/`$` in the query.
|
|
460
|
-
//
|
|
461
|
-
|
|
462
|
+
// remote shell never expands backticks/`$` in the query. See buildHeredoc and issue #44.
|
|
463
|
+
//
|
|
464
|
+
// The heredoc only keeps the shell out: mongo evaluates the script as
|
|
465
|
+
// JavaScript. Up to 3.8.5 the collection and the query were spliced into it
|
|
466
|
+
// raw, so `{}).forEach(printjson); db.dropDatabase(); db.x.find({` ran on a
|
|
467
|
+
// tool documented as read-only (GHSA-q37w-vhpx-q5q9). The collection now
|
|
468
|
+
// travels as a string literal, and the query must parse as a plain filter
|
|
469
|
+
// document: literals and a few type constructors, never code.
|
|
470
|
+
const filter = query && query.trim() ? checkMongoFilter(query) : '{}';
|
|
471
|
+
const script = `db.getCollection(${jsString(collection)}).find(${filter}).forEach(printjson)`;
|
|
462
472
|
command += ` --quiet${buildHeredoc(script)}`;
|
|
463
473
|
|
|
464
474
|
return command;
|
|
465
475
|
}
|
|
466
476
|
|
|
467
477
|
/**
|
|
468
|
-
*
|
|
478
|
+
* A JavaScript string literal for any text. JSON.stringify leaves U+2028 and
|
|
479
|
+
* U+2029 raw, which older JavaScript engines read as line breaks.
|
|
480
|
+
* @param {any} value
|
|
481
|
+
*/
|
|
482
|
+
function jsString(value) {
|
|
483
|
+
if (typeof value !== 'string' || !value || value.includes('\0')) {
|
|
484
|
+
throw new Error('A MongoDB collection name must be a non-empty string');
|
|
485
|
+
}
|
|
486
|
+
return JSON.stringify(value).replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// Constructors a filter document may call, as the mongo shell spells them.
|
|
490
|
+
const MONGO_CONSTRUCTORS = new Set([
|
|
491
|
+
'ObjectId', 'ISODate', 'Date', 'NumberLong', 'NumberInt', 'NumberDecimal',
|
|
492
|
+
'Timestamp', 'UUID', 'BinData', 'MinKey', 'MaxKey', 'RegExp',
|
|
493
|
+
]);
|
|
494
|
+
// Operators that run JavaScript on the database server.
|
|
495
|
+
const MONGO_CODE_OPERATORS = new Set(['$where', '$function', '$accumulator']);
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* Check that a MongoDB query is a filter document and nothing else, and
|
|
499
|
+
* return it unchanged. Accepted: JSON, or the mongo shell's relaxed form
|
|
500
|
+
* (unquoted keys, single-quoted strings, regex literals, ObjectId("…") and
|
|
501
|
+
* the other constructors above). Refused: anything that is code — function
|
|
502
|
+
* calls outside that list, property access, operators, statements — and the
|
|
503
|
+
* operators that evaluate JavaScript on the server ($where, $function,
|
|
504
|
+
* $accumulator), which a read-only tool has no use for.
|
|
505
|
+
* @param {string} query
|
|
506
|
+
* @returns {string}
|
|
507
|
+
*/
|
|
508
|
+
export function checkMongoFilter(query) {
|
|
509
|
+
const text = String(query);
|
|
510
|
+
let i = 0;
|
|
511
|
+
const fail = (what) => {
|
|
512
|
+
throw new Error(`MongoDB query must be a filter document such as {"status": "active"}: ${what} at offset ${i}`);
|
|
513
|
+
};
|
|
514
|
+
const skip = () => { while (i < text.length && /\s/.test(text[i])) i++; };
|
|
515
|
+
const identifier = () => {
|
|
516
|
+
const m = /^[$A-Za-z_][\w$]*/.exec(text.slice(i));
|
|
517
|
+
if (!m) return null;
|
|
518
|
+
i += m[0].length;
|
|
519
|
+
return m[0];
|
|
520
|
+
};
|
|
521
|
+
const string = () => {
|
|
522
|
+
const quote = text[i];
|
|
523
|
+
let value = '';
|
|
524
|
+
i++;
|
|
525
|
+
while (i < text.length && text[i] !== quote) {
|
|
526
|
+
if (text[i] === '\n' || text[i] === '\r') fail('a line break inside a string');
|
|
527
|
+
if (text[i] === '\\') { value += text[i + 1]; i += 2; continue; }
|
|
528
|
+
value += text[i++];
|
|
529
|
+
}
|
|
530
|
+
if (i >= text.length) fail('an unterminated string');
|
|
531
|
+
i++;
|
|
532
|
+
return value;
|
|
533
|
+
};
|
|
534
|
+
const number = () => {
|
|
535
|
+
const m = /^-?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/.exec(text.slice(i));
|
|
536
|
+
if (!m) return false;
|
|
537
|
+
i += m[0].length;
|
|
538
|
+
return true;
|
|
539
|
+
};
|
|
540
|
+
const value = () => {
|
|
541
|
+
skip();
|
|
542
|
+
const ch = text[i];
|
|
543
|
+
if (ch === '{') return object();
|
|
544
|
+
if (ch === '[') return array();
|
|
545
|
+
if (ch === '"' || ch === '\'') { string(); return; }
|
|
546
|
+
if (ch === '/') {
|
|
547
|
+
const m = /^\/(?:\\.|[^/\\\n])+\/[gimsuy]*/.exec(text.slice(i));
|
|
548
|
+
if (!m) fail('an invalid regular expression');
|
|
549
|
+
i += m[0].length;
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
if (number()) return;
|
|
553
|
+
const start = i;
|
|
554
|
+
let name = identifier();
|
|
555
|
+
if (name === 'new') { skip(); name = identifier(); }
|
|
556
|
+
if (name === 'true' || name === 'false' || name === 'null' || name === 'undefined') return;
|
|
557
|
+
if (name && MONGO_CONSTRUCTORS.has(name)) {
|
|
558
|
+
skip();
|
|
559
|
+
if (text[i] !== '(') fail(`${name} without arguments`);
|
|
560
|
+
i++;
|
|
561
|
+
skip();
|
|
562
|
+
while (text[i] !== ')') {
|
|
563
|
+
skip();
|
|
564
|
+
if (text[i] === '"' || text[i] === '\'') string();
|
|
565
|
+
else if (!number()) fail(`an argument to ${name} that is not a string or a number`);
|
|
566
|
+
skip();
|
|
567
|
+
if (text[i] === ',') { i++; continue; }
|
|
568
|
+
if (text[i] !== ')') fail(`an unterminated ${name}(`);
|
|
569
|
+
}
|
|
570
|
+
i++;
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
i = start;
|
|
574
|
+
fail(name ? `"${name}", which is not a value` : 'something that is not a value');
|
|
575
|
+
};
|
|
576
|
+
const key = () => {
|
|
577
|
+
skip();
|
|
578
|
+
const ch = text[i];
|
|
579
|
+
const name = ch === '"' || ch === '\'' ? string() : identifier() ?? (number() ? '' : fail('a key that is not a name'));
|
|
580
|
+
if (MONGO_CODE_OPERATORS.has(name)) fail(`${name}, which runs JavaScript on the server`);
|
|
581
|
+
};
|
|
582
|
+
const object = () => {
|
|
583
|
+
i++;
|
|
584
|
+
skip();
|
|
585
|
+
while (text[i] !== '}') {
|
|
586
|
+
key();
|
|
587
|
+
skip();
|
|
588
|
+
if (text[i] !== ':') fail('a missing ":"');
|
|
589
|
+
i++;
|
|
590
|
+
value();
|
|
591
|
+
skip();
|
|
592
|
+
if (text[i] === ',') { i++; skip(); continue; }
|
|
593
|
+
if (text[i] !== '}') fail('a missing "," or "}"');
|
|
594
|
+
}
|
|
595
|
+
i++;
|
|
596
|
+
};
|
|
597
|
+
const array = () => {
|
|
598
|
+
i++;
|
|
599
|
+
skip();
|
|
600
|
+
while (text[i] !== ']') {
|
|
601
|
+
value();
|
|
602
|
+
skip();
|
|
603
|
+
if (text[i] === ',') { i++; skip(); continue; }
|
|
604
|
+
if (text[i] !== ']') fail('a missing "," or "]"');
|
|
605
|
+
}
|
|
606
|
+
i++;
|
|
607
|
+
};
|
|
608
|
+
|
|
609
|
+
skip();
|
|
610
|
+
if (text[i] !== '{') fail('no opening "{"');
|
|
611
|
+
object();
|
|
612
|
+
skip();
|
|
613
|
+
if (i < text.length) fail('text after the filter');
|
|
614
|
+
return text.trim();
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// Words a read-only SELECT has no business containing. The statement verbs
|
|
618
|
+
// were always refused; INTO and the file functions were not, and a SELECT can
|
|
619
|
+
// write: `SELECT … INTO OUTFILE` writes a file on the database server
|
|
620
|
+
// (GHSA-9w6j-vg8f-hp8g), `SELECT … INTO new_table` creates a table in
|
|
621
|
+
// PostgreSQL, and the server-file functions read or write outside the
|
|
622
|
+
// database. Matched as whole words, case-insensitively.
|
|
623
|
+
const FORBIDDEN_SQL_WORDS = [
|
|
624
|
+
'insert', 'update', 'delete', 'drop', 'create', 'alter',
|
|
625
|
+
'truncate', 'grant', 'revoke', 'exec', 'execute',
|
|
626
|
+
'into', 'outfile', 'dumpfile', 'load_file', 'sys_exec', 'sys_eval',
|
|
627
|
+
'pg_read_file', 'pg_read_binary_file', 'pg_ls_dir', 'pg_stat_file',
|
|
628
|
+
'pg_file_write', 'pg_file_rename', 'pg_file_unlink',
|
|
629
|
+
'lo_import', 'lo_export', 'lo_from_bytea', 'lo_put', 'lo_create', 'lo_unlink',
|
|
630
|
+
'dblink', 'dblink_exec', 'pg_terminate_backend', 'pg_cancel_backend',
|
|
631
|
+
'pg_reload_conf', 'pg_rotate_logfile', 'pg_promote', 'set_config',
|
|
632
|
+
];
|
|
633
|
+
const FORBIDDEN_SQL = new RegExp(`\\b(${FORBIDDEN_SQL_WORDS.join('|')})\\b`, 'i');
|
|
634
|
+
|
|
635
|
+
/**
|
|
636
|
+
* Validate query is safe (SELECT only): one statement, beginning with SELECT,
|
|
637
|
+
* containing none of the words above. The builders also run it inside a
|
|
638
|
+
* read-only transaction, which catches what a word list cannot see, such as a
|
|
639
|
+
* stored function that writes.
|
|
469
640
|
*/
|
|
470
641
|
export function isSafeQuery(query) {
|
|
471
|
-
|
|
642
|
+
if (typeof query !== 'string') return false;
|
|
643
|
+
const statement = query.trim().replace(/;\s*$/, '');
|
|
472
644
|
|
|
473
645
|
// Must start with SELECT
|
|
474
|
-
if (
|
|
646
|
+
if (!/^select\b/i.test(statement)) {
|
|
475
647
|
return false;
|
|
476
648
|
}
|
|
477
649
|
|
|
478
|
-
//
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
'truncate', 'grant', 'revoke', 'exec', 'execute'
|
|
482
|
-
];
|
|
483
|
-
|
|
484
|
-
for (const keyword of dangerousKeywords) {
|
|
485
|
-
if (trimmedQuery.includes(keyword)) {
|
|
486
|
-
return false;
|
|
487
|
-
}
|
|
650
|
+
// One statement only: a second one would run after the check, unchecked.
|
|
651
|
+
if (statement.includes(';')) {
|
|
652
|
+
return false;
|
|
488
653
|
}
|
|
489
654
|
|
|
490
|
-
return
|
|
655
|
+
return !FORBIDDEN_SQL.test(statement);
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
/**
|
|
659
|
+
* The SQL fed to the client: the query inside a read-only transaction. The
|
|
660
|
+
* database then refuses any write the query would make, including one hidden
|
|
661
|
+
* in a function it calls (MySQL 5.6.5+, MariaDB 10.0+, every PostgreSQL).
|
|
662
|
+
* @param {string} type - DB_TYPES.MYSQL or DB_TYPES.POSTGRESQL
|
|
663
|
+
* @param {string} query - A query that passed isSafeQuery
|
|
664
|
+
*/
|
|
665
|
+
function readOnlyScript(type, query) {
|
|
666
|
+
const statement = query.trim().replace(/;\s*$/, '');
|
|
667
|
+
return type === DB_TYPES.MYSQL
|
|
668
|
+
? `SET SESSION TRANSACTION READ ONLY;\n${statement};`
|
|
669
|
+
: `BEGIN TRANSACTION READ ONLY;\n${statement};\nROLLBACK;`;
|
|
491
670
|
}
|
|
492
671
|
|
|
493
672
|
/**
|
package/src/deploy-helper.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import path from 'path';
|
|
2
2
|
import crypto from 'crypto';
|
|
3
|
+
import { shellQuote } from './shell-quote.js';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* Deploy helper functions for secure file deployment
|
|
@@ -11,8 +12,11 @@ import crypto from 'crypto';
|
|
|
11
12
|
export function getTempFilename(originalName) {
|
|
12
13
|
const timestamp = Date.now();
|
|
13
14
|
const random = crypto.randomBytes(4).toString('hex');
|
|
14
|
-
|
|
15
|
-
|
|
15
|
+
// The local name is only a hint for whoever reads /tmp: keep the characters
|
|
16
|
+
// that need no quoting anywhere, so the name stays inert in every command.
|
|
17
|
+
const safe = text => text.replace(/[^A-Za-z0-9._-]/g, '_');
|
|
18
|
+
const ext = safe(path.extname(originalName));
|
|
19
|
+
const base = safe(path.basename(originalName, path.extname(originalName)));
|
|
16
20
|
return `/tmp/${base}_${timestamp}_${random}${ext}`;
|
|
17
21
|
}
|
|
18
22
|
|
|
@@ -33,11 +37,15 @@ export function buildDeploymentStrategy(remotePath, options = {}) {
|
|
|
33
37
|
requiresSudo: false
|
|
34
38
|
};
|
|
35
39
|
|
|
40
|
+
// Every value below reaches the remote shell. Up to 3.8.5 the path sat in
|
|
41
|
+
// double quotes, where $(…) still runs, and owner and permissions were bare.
|
|
42
|
+
const target = shellQuote(remotePath);
|
|
43
|
+
|
|
36
44
|
// Step 1: Backup existing file if requested
|
|
37
45
|
if (backup) {
|
|
38
46
|
strategy.steps.push({
|
|
39
47
|
type: 'backup',
|
|
40
|
-
command: `if [ -f
|
|
48
|
+
command: `if [ -f ${target} ]; then cp ${target} ${target}.bak.$(date +%Y%m%d_%H%M%S); fi`
|
|
41
49
|
});
|
|
42
50
|
}
|
|
43
51
|
|
|
@@ -60,8 +68,8 @@ export function buildDeploymentStrategy(remotePath, options = {}) {
|
|
|
60
68
|
|
|
61
69
|
// Step 3: Copy from temp to final location
|
|
62
70
|
const copyCmd = needsSudo ?
|
|
63
|
-
`${sudoPrefix}cp {{tempFile}}
|
|
64
|
-
`cp {{tempFile}}
|
|
71
|
+
`${sudoPrefix}cp {{tempFile}} ${target}` :
|
|
72
|
+
`cp {{tempFile}} ${target}`;
|
|
65
73
|
|
|
66
74
|
strategy.steps.push(needsSudo ? withSudoStdin({
|
|
67
75
|
type: 'copy',
|
|
@@ -75,7 +83,7 @@ export function buildDeploymentStrategy(remotePath, options = {}) {
|
|
|
75
83
|
if (owner) {
|
|
76
84
|
strategy.steps.push(withSudoStdin({
|
|
77
85
|
type: 'chown',
|
|
78
|
-
command: `${sudoPrefix}chown ${owner}
|
|
86
|
+
command: `${sudoPrefix}chown ${shellQuote(owner)} ${target}`
|
|
79
87
|
}));
|
|
80
88
|
}
|
|
81
89
|
|
|
@@ -83,7 +91,7 @@ export function buildDeploymentStrategy(remotePath, options = {}) {
|
|
|
83
91
|
if (permissions) {
|
|
84
92
|
strategy.steps.push(withSudoStdin({
|
|
85
93
|
type: 'chmod',
|
|
86
|
-
command: `${sudoPrefix}chmod ${permissions}
|
|
94
|
+
command: `${sudoPrefix}chmod ${shellQuote(permissions)} ${target}`
|
|
87
95
|
}));
|
|
88
96
|
}
|
|
89
97
|
|