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/backup-manager.js
CHANGED
|
@@ -37,6 +37,52 @@ export function getBackupMetadataPath(backupId, backupDir = DEFAULT_BACKUP_DIR)
|
|
|
37
37
|
return path.join(backupDir, `${backupId}.meta.json`);
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
+
/**
|
|
41
|
+
* Refuse a backup ID that is not one.
|
|
42
|
+
*
|
|
43
|
+
* GHSA-2wjh-xm9c-7qf9: ssh_backup_restore took `backupId` from the caller and
|
|
44
|
+
* spliced the path built from it into `cat "…"`, where `$(...)` and backticks
|
|
45
|
+
* still run — remote code execution through a tool that was only meant to
|
|
46
|
+
* restore. Quoting (buildReadMetadataCommand) is the fix; this is the second
|
|
47
|
+
* wall. An ID is a file name inside the backup directory, so a path separator,
|
|
48
|
+
* a `..` segment or a control character can only mean somebody is reaching
|
|
49
|
+
* elsewhere. Spaces and dots stay allowed: IDs carry the backup's name, and a
|
|
50
|
+
* name that worked before must still restore.
|
|
51
|
+
*
|
|
52
|
+
* @param {unknown} backupId - As the caller sent it
|
|
53
|
+
* @returns {string} The same ID, known to be a plain file name
|
|
54
|
+
*/
|
|
55
|
+
export function assertSafeBackupId(backupId) {
|
|
56
|
+
const id = String(backupId ?? '');
|
|
57
|
+
// eslint-disable-next-line no-control-regex
|
|
58
|
+
if (!id || /[/\\\u0000-\u001f\u007f]/.test(id) || id === '.' || id === '..') {
|
|
59
|
+
throw new Error(`Invalid backup ID: ${JSON.stringify(id)}`);
|
|
60
|
+
}
|
|
61
|
+
return id;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Build the command that reads a backup's metadata (ssh_backup_restore).
|
|
66
|
+
* @param {string} backupId - Checked with assertSafeBackupId
|
|
67
|
+
* @param {string} [backupDir]
|
|
68
|
+
* @returns {string}
|
|
69
|
+
*/
|
|
70
|
+
export function buildReadMetadataCommand(backupId, backupDir = DEFAULT_BACKUP_DIR) {
|
|
71
|
+
return `cat ${shellQuote(getBackupMetadataPath(assertSafeBackupId(backupId), backupDir))}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Build the command that makes sure the backup directory exists
|
|
76
|
+
* (ssh_backup_create). Quoted like every other use of the directory: the
|
|
77
|
+
* inline `mkdir -p "…"` it replaces was the half of GHSA-qwwm-vrm9-4mw8 that
|
|
78
|
+
* the 3.8.x fix missed.
|
|
79
|
+
* @param {string} [backupDir]
|
|
80
|
+
* @returns {string}
|
|
81
|
+
*/
|
|
82
|
+
export function buildEnsureBackupDirCommand(backupDir = DEFAULT_BACKUP_DIR) {
|
|
83
|
+
return `mkdir -p ${shellQuote(backupDir)}`;
|
|
84
|
+
}
|
|
85
|
+
|
|
40
86
|
/**
|
|
41
87
|
* Get backup file path
|
|
42
88
|
*/
|
|
@@ -442,6 +488,29 @@ export function buildCronScheduleCommand(schedule, backupCommand, cronComment) {
|
|
|
442
488
|
// through shellQuote so a schedule or comment carrying quotes cannot break
|
|
443
489
|
// out of the echo and run something else. backupCommand is built by the
|
|
444
490
|
// builders above, which quote their own arguments.
|
|
445
|
-
|
|
491
|
+
//
|
|
492
|
+
// Quoting the echo was the 3.8.5 fix, and it was not enough: cron reads
|
|
493
|
+
// everything after the fifth field as the command to run, and a line break
|
|
494
|
+
// as the start of another job, so `* * * * * curl … | sh #` installed a job
|
|
495
|
+
// of the caller's choosing. The schedule must now be a schedule.
|
|
496
|
+
if (!isCronSchedule(schedule)) {
|
|
497
|
+
throw new Error('Schedule must be five cron fields (e.g. "0 2 * * *") or a macro such as @daily');
|
|
498
|
+
}
|
|
499
|
+
const comment = String(cronComment).replace(/[\r\n]+/g, ' ');
|
|
500
|
+
const cronLine = `${schedule.trim()} ${backupCommand} # ${comment}`;
|
|
446
501
|
return `(crontab -l 2>/dev/null; echo ${shellQuote(cronLine)}) | crontab -`;
|
|
447
502
|
}
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* Whether a string is a crontab schedule and nothing more: five time fields,
|
|
506
|
+
* or one of cron's @ macros.
|
|
507
|
+
* @param {any} schedule
|
|
508
|
+
* @returns {boolean}
|
|
509
|
+
*/
|
|
510
|
+
export function isCronSchedule(schedule) {
|
|
511
|
+
if (typeof schedule !== 'string') return false;
|
|
512
|
+
const text = schedule.trim();
|
|
513
|
+
if (/^@(yearly|annually|monthly|weekly|daily|midnight|hourly|reboot)$/.test(text)) return true;
|
|
514
|
+
const fields = text.split(/[ \t]+/);
|
|
515
|
+
return fields.length === 5 && fields.every(field => /^[0-9A-Za-z*/,-]+$/.test(field));
|
|
516
|
+
}
|
package/src/command-aliases.js
CHANGED
|
@@ -3,15 +3,18 @@
|
|
|
3
3
|
* Provides shortcuts for frequently used commands
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
import fs from 'fs';
|
|
7
6
|
import path from 'path';
|
|
8
7
|
import { fileURLToPath } from 'url';
|
|
9
8
|
import { loadProfile } from './profile-loader.js';
|
|
9
|
+
import { readUserState, writeUserState } from './user-state.js';
|
|
10
10
|
|
|
11
11
|
const __filename = fileURLToPath(import.meta.url);
|
|
12
12
|
const __dirname = path.dirname(__filename);
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
// Custom aliases live in the manager home; the package copy is read only as a
|
|
15
|
+
// fallback for a source checkout (see user-state.js, issue #87).
|
|
16
|
+
const ALIASES_NAME = 'command-aliases.json';
|
|
17
|
+
const LEGACY_ALIASES_FILE = path.join(__dirname, '..', '.command-aliases.json');
|
|
15
18
|
|
|
16
19
|
// Get aliases from the active profile
|
|
17
20
|
let profileAliases = {};
|
|
@@ -31,9 +34,9 @@ export function loadCommandAliases() {
|
|
|
31
34
|
let aliases = { ...profileAliases };
|
|
32
35
|
|
|
33
36
|
// Merge with custom aliases from file
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
aliases = { ...aliases, ...JSON.parse(
|
|
37
|
+
const state = readUserState(ALIASES_NAME, LEGACY_ALIASES_FILE);
|
|
38
|
+
if (state) {
|
|
39
|
+
aliases = { ...aliases, ...JSON.parse(state.text) };
|
|
37
40
|
}
|
|
38
41
|
|
|
39
42
|
return aliases;
|
|
@@ -56,7 +59,7 @@ function saveCommandAliases(aliases) {
|
|
|
56
59
|
}
|
|
57
60
|
}
|
|
58
61
|
|
|
59
|
-
|
|
62
|
+
writeUserState(ALIASES_NAME, JSON.stringify(customAliases, null, 2));
|
|
60
63
|
return true;
|
|
61
64
|
} catch (error) {
|
|
62
65
|
console.error(`Error saving command aliases: ${error.message}`);
|
package/src/config-loader.js
CHANGED
|
@@ -23,6 +23,7 @@ import { VALID_MODES } from './policy.js';
|
|
|
23
23
|
* @property {string} [user] SSH user.
|
|
24
24
|
* @property {string} [password] Password for password authentication.
|
|
25
25
|
* @property {string} [keyPath] Path to the private key (`KEYPATH` / `key_path`).
|
|
26
|
+
* @property {string} [certPath] OpenSSH user certificate for keyPath (`CERTPATH` / `cert_path`).
|
|
26
27
|
* @property {string} [passphrase] Passphrase for a protected private key.
|
|
27
28
|
* @property {number} [port] TCP port; defaults to 22.
|
|
28
29
|
* @property {string} [defaultDir] Working directory used when a tool omits `cwd`.
|
|
@@ -178,6 +179,7 @@ export class ConfigLoader {
|
|
|
178
179
|
user: serverConfig.user || serverConfig.username,
|
|
179
180
|
password: serverConfig.password,
|
|
180
181
|
keyPath: serverConfig.key_path || serverConfig.keypath || serverConfig.ssh_key,
|
|
182
|
+
certPath: serverConfig.cert_path,
|
|
181
183
|
passphrase: serverConfig.passphrase,
|
|
182
184
|
port: serverConfig.port || 22,
|
|
183
185
|
defaultDir: serverConfig.default_dir || serverConfig.default_directory || serverConfig.cwd,
|
|
@@ -251,6 +253,7 @@ export class ConfigLoader {
|
|
|
251
253
|
user: env[`SSH_SERVER_${match[1]}_USER`],
|
|
252
254
|
password: env[`SSH_SERVER_${match[1]}_PASSWORD`],
|
|
253
255
|
keyPath: env[`SSH_SERVER_${match[1]}_KEYPATH`],
|
|
256
|
+
certPath: env[`SSH_SERVER_${match[1]}_CERTPATH`],
|
|
254
257
|
passphrase: env[`SSH_SERVER_${match[1]}_PASSPHRASE`],
|
|
255
258
|
port: parseInt(env[`SSH_SERVER_${match[1]}_PORT`] || '22'),
|
|
256
259
|
defaultDir: env[`SSH_SERVER_${match[1]}_DEFAULT_DIR`],
|
|
@@ -317,6 +320,7 @@ export class ConfigLoader {
|
|
|
317
320
|
|
|
318
321
|
if (server.password) serverConfig.password = server.password;
|
|
319
322
|
if (server.keyPath) serverConfig.key_path = server.keyPath;
|
|
323
|
+
if (server.certPath) serverConfig.cert_path = server.certPath;
|
|
320
324
|
if (server.passphrase) serverConfig.passphrase = server.passphrase;
|
|
321
325
|
if (server.defaultDir) serverConfig.default_dir = server.defaultDir;
|
|
322
326
|
if (server.sudoPassword) serverConfig.sudo_password = server.sudoPassword;
|
|
@@ -359,6 +363,7 @@ export class ConfigLoader {
|
|
|
359
363
|
lines.push(`SSH_SERVER_${upperName}_USER=${server.user}`);
|
|
360
364
|
if (server.password) lines.push(`SSH_SERVER_${upperName}_PASSWORD="${server.password}"`);
|
|
361
365
|
if (server.keyPath) lines.push(`SSH_SERVER_${upperName}_KEYPATH=${server.keyPath}`);
|
|
366
|
+
if (server.certPath) lines.push(`SSH_SERVER_${upperName}_CERTPATH=${server.certPath}`);
|
|
362
367
|
if (server.passphrase) lines.push(`SSH_SERVER_${upperName}_PASSPHRASE="${server.passphrase}"`);
|
|
363
368
|
lines.push(`SSH_SERVER_${upperName}_PORT=${server.port || 22}`);
|
|
364
369
|
if (server.defaultDir) lines.push(`SSH_SERVER_${upperName}_DEFAULT_DIR=${server.defaultDir}`);
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import os from 'os';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The directory that holds this user's settings and state: SSH_MANAGER_HOME,
|
|
6
|
+
* or ~/.ssh-manager. Read at call time so a test or a host that sets the
|
|
7
|
+
* variable after import still gets its own directory.
|
|
8
|
+
* @returns {string}
|
|
9
|
+
*/
|
|
10
|
+
export function managerHome() {
|
|
11
|
+
return process.env.SSH_MANAGER_HOME || path.join(os.homedir(), '.ssh-manager');
|
|
12
|
+
}
|
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
|
|