From ddf04a1e8e1658e6c0b1bbf36191c387fc122d91 Mon Sep 17 00:00:00 2001 From: Doug Horner Date: Sat, 5 Dec 2026 19:13:07 -0500 Subject: [PATCH] Run Manager guest exec as the authenticated Linux user --- create-a-container/openapi.v1.yaml | 11 +- .../api/v1/__tests__/containers.exec.test.js | 25 ++- .../routers/api/v1/containers.js | 14 +- .../utils/__tests__/guest-exec.test.js | 146 ++++++++++++++++-- create-a-container/utils/guest-exec.js | 101 ++++++++---- .../docs/admins/guest-exec.md | 17 +- packages/os-cloud-provider/README.md | 10 +- .../os-cloud-provider/test/exec-guest.e2e.mjs | 16 +- 8 files changed, 266 insertions(+), 74 deletions(-) diff --git a/create-a-container/openapi.v1.yaml b/create-a-container/openapi.v1.yaml index efa9542b..d0893fb4 100644 --- a/create-a-container/openapi.v1.yaml +++ b/create-a-container/openapi.v1.yaml @@ -1307,10 +1307,13 @@ paths: post: operationId: exec_container tags: [Containers] - summary: Run one command as root in a running guest (owner/admin) + summary: Run one command in a running guest as the authenticated caller (owner/admin) description: >- Proxmox guests only. The command runs through the Proxmox console API, - so the guest needs no SSH route, but it needs a POSIX `sh`. The + so the guest needs no SSH route. It needs a POSIX `sh`, `sudo`, + `setsid`, `timeout`, and a non-root Linux account with the caller's exact Manager + username. Guest and Manager numeric UIDs can differ. The Manager + selects this account for both owners and admins. The executable and its arguments are passed as separate words, without shell interpretation. The first call on a guest created before this feature switches its console mode and returns `exec_restart_required`; @@ -1357,9 +1360,9 @@ paths: '401': { description: Authentication required } '403': { $ref: '#/components/responses/Forbidden' } '404': { $ref: '#/components/responses/NotFound' } - '409': { description: 'Guest is stopped (guest_not_running), its hostname does not match (guest_identity_mismatch), another command is running in it (exec_busy), or it must be restarted once to enable exec (exec_restart_required)' } + '409': { description: 'Guest is stopped (guest_not_running), its hostname does not match (guest_identity_mismatch), its matching non-root caller account is unavailable (guest_user_unavailable), another command is running in it (exec_busy), or it must be restarted once to enable exec (exec_restart_required)' } '415': { description: Expected application/json } - '501': { description: Execution is unavailable on this node } + '501': { description: Execution is unavailable on this node or the guest lacks required tools such as sudo or setsid (exec_unavailable) } '502': { description: Guest command outcome is unknown } '504': { description: Guest command timed out } /sites/{siteId}/containers/{id}/collaborators: diff --git a/create-a-container/routers/api/v1/__tests__/containers.exec.test.js b/create-a-container/routers/api/v1/__tests__/containers.exec.test.js index 054ee1c0..556ad2fd 100644 --- a/create-a-container/routers/api/v1/__tests__/containers.exec.test.js +++ b/create-a-container/routers/api/v1/__tests__/containers.exec.test.js @@ -10,8 +10,10 @@ jest.mock('../../../../utils/guest-exec', () => ({ const { executeGuest, EXEC_LEASE_SECONDS } = require('../../../../utils/guest-exec'); describe('POST container exec', () => { - let app, site, otherSite, node, box, otherBox, owner, ownerKey, adminKey, viewerKey, audit; + let app, site, otherSite, node, box, otherBox, owner, ownerKey, admin, adminKey, viewerKey, audit; const argv = ['node', '--version']; + // The guest's NSS directory assigns its own numeric IDs independently of Manager. + const guestUid = 12001; const result = { stdout: Buffer.from([0, 255, 10]).toString('base64'), stderr: Buffer.from('guest diagnostic').toString('base64'), @@ -21,7 +23,7 @@ describe('POST container exec', () => { beforeAll(async () => { await resetDb(); app = buildApp(); - const admin = await createUser({ admin: true }); + admin = await createUser({ admin: true }); owner = await createUser(); const viewer = await createUser(); ({ plainKey: ownerKey } = await createApiKey(owner)); @@ -45,7 +47,7 @@ describe('POST container exec', () => { beforeEach(async () => { await Container.update({ execLeaseUntil: null }, { where: {} }); executeGuest.mockReset(); - executeGuest.mockResolvedValue(result); + executeGuest.mockResolvedValue({ ...result, guestUid }); audit = jest.spyOn(console, 'info').mockImplementation(() => {}); }); afterEach(() => audit.mockRestore()); @@ -65,6 +67,7 @@ describe('POST container exec', () => { expect(executeGuest).toHaveBeenCalledTimes(1); expect(executeGuest).toHaveBeenCalledWith({ node: expect.objectContaining({ id: node.id, name: node.name }), vmid: 701, hostname: box.hostname, argv: args, + guestUser: owner.uid, leaseUntil: expect.any(Date), }); const { leaseUntil } = executeGuest.mock.calls[0][0]; @@ -72,6 +75,7 @@ describe('POST container exec', () => { const log = audit.mock.calls[0][0]; expect(JSON.parse(log)).toMatchObject({ event: 'container.exec', callerUidNumber: owner.uidNumber, siteId: site.id, containerId: box.id, + requestedGuestUser: owner.uid, guestUid, startedAt: expect.any(String), durationMs: expect.any(Number), outcome: 'exited', exitCode: 0, }); for (const secret of ['secret=', result.stdout, result.stderr, ownerKey]) expect(log).not.toContain(secret); @@ -79,10 +83,14 @@ describe('POST container exec', () => { test('an authorized admin receives a nonzero exit and truncation as an ordinary result', async () => { const failed = { ...result, exitCode: 23, stderrTruncated: true }; - executeGuest.mockResolvedValue(failed); + executeGuest.mockResolvedValue({ ...failed, guestUid: 12002 }); const res = await post({ argv }, { key: adminKey }); expect(res.status).toBe(200); expect(res.body.data).toEqual(failed); + expect(executeGuest.mock.calls[0][0].guestUser).toBe(admin.uid); + expect(JSON.parse(audit.mock.calls[0][0])).toMatchObject({ + callerUidNumber: admin.uidNumber, requestedGuestUser: admin.uid, guestUid: 12002, + }); }); test('denies anonymous callers, read-only collaborators, other owners and cross-site requests', async () => { @@ -99,6 +107,7 @@ describe('POST container exec', () => { {}, { argv: [] }, { argv: [''] }, { argv: 'ls' }, { argv: ['ls', 1] }, { argv: ['ls', 'x\0y'] }, { argv: ['ls', '\ud800'] }, { argv: Array(129).fill('x') }, { argv: ['x'.repeat(16384)] }, { argv, vmid: 702 }, { argv, user: 'root' }, + { argv, guestUser: { name: admin.uid, uid: admin.uidNumber } }, ]) { expect((await post(body)).status).toBe(400); } @@ -120,7 +129,7 @@ describe('POST container exec', () => { test('runs one command per guest at a time, across Manager processes', async () => { let finish; - executeGuest.mockImplementation(() => new Promise((resolve) => { finish = () => resolve(result); })); + executeGuest.mockImplementation(() => new Promise((resolve) => { finish = () => resolve({ ...result, guestUid }); })); // supertest sends a request only once it is awaited or then()'d. const first = post({ argv }).then((res) => res); await new Promise((resolve) => { const wait = () => (finish ? resolve() : setTimeout(wait, 5)); wait(); }); @@ -153,7 +162,7 @@ describe('POST container exec', () => { test.each([ ['exec_restart_required', 409], ['guest_not_running', 409], - ['guest_identity_mismatch', 409], ['exec_unavailable', 501], + ['guest_identity_mismatch', 409], ['guest_user_unavailable', 409], ['exec_unavailable', 501], ['exec_timeout', 504], ['exec_outcome_unknown', 502], ['ECONNRESET', 502], ])('maps backend failure %s without logging or returning raw diagnostics', async (code, status) => { executeGuest.mockRejectedValue(Object.assign(new Error('private diagnostic'), { code })); @@ -163,7 +172,9 @@ describe('POST container exec', () => { expect(res.body.error.code).toBe(expectedCode); expect(res.text).not.toContain('private diagnostic'); expect(audit.mock.calls[0][0]).not.toContain('private diagnostic'); - expect(JSON.parse(audit.mock.calls[0][0]).outcome).toBe(expectedCode); + const log = JSON.parse(audit.mock.calls[0][0]); + expect(log).toMatchObject({ outcome: expectedCode, requestedGuestUser: owner.uid }); + expect(log).not.toHaveProperty('guestUid'); expect(executeGuest).toHaveBeenCalledTimes(1); }); }); diff --git a/create-a-container/routers/api/v1/containers.js b/create-a-container/routers/api/v1/containers.js index 3d8f2a37..9fe15e79 100644 --- a/create-a-container/routers/api/v1/containers.js +++ b/create-a-container/routers/api/v1/containers.js @@ -421,6 +421,7 @@ const execErrors = new Map([ ['exec_restart_required', [409, 'Restart the guest to enable command execution']], ['guest_not_running', [409, 'The guest is not running']], ['guest_identity_mismatch', [409, 'The running guest identity could not be verified']], + ['guest_user_unavailable', [409, 'The command could not be run as the authenticated guest user']], ['exec_timeout', [504, 'Guest execution timed out']], ['exec_outcome_unknown', [502, 'The guest command outcome is unknown']], ]); @@ -456,9 +457,7 @@ router.post('/:id/exec', asyncHandler(async (req, res) => { }; res.set('Cache-Control', 'no-store'); try { - // Look up only the stable numerical account ID for the audit record. - // A bearer-authenticated session also holds the credential's ORM record. - const caller = await User.findOne({ where: { uid: req.session.user }, attributes: ['uidNumber'], raw: true }); + const caller = await User.findOne({ where: { uid: req.session.user }, attributes: ['uid', 'uidNumber'], raw: true }); if (!Number.isSafeInteger(caller?.uidNumber)) throw new ApiError(403, 'forbidden', 'Unknown Manager account'); audit.callerUidNumber = caller.uidNumber; if (![req.params.siteId, req.params.id].every(id => /^[1-9]\d*$/.test(id) && Number.isSafeInteger(Number(id)))) { @@ -467,6 +466,7 @@ router.post('/:id/exec', asyncHandler(async (req, res) => { const { site, container } = await loadContainerForSession(siteId, containerId, req.session, { requireManage: true }); if (container.siteId !== site.id) throw new ApiError(404, 'not_found', 'Container not found'); const argv = readExecArgs(req); + audit.requestedGuestUser = caller.uid; if (container.node.nodeType !== 'proxmox') throw new ApiError(501, 'exec_unavailable', 'Guest execution is unavailable on this node'); if (!container.containerId) throw new ApiError(409, 'guest_not_running', 'The guest has not been provisioned'); const vmid = Number(container.containerId); @@ -482,7 +482,7 @@ router.post('/:id/exec', asyncHandler(async (req, res) => { let keepLease = false; try { result = await executeGuest({ - node: container.node, vmid, hostname: container.hostname, argv, leaseUntil: lease, + node: container.node, vmid, hostname: container.hostname, argv, guestUser: caller.uid, leaseUntil: lease, }); } catch (err) { const code = execErrors.has(err?.code) ? err.code : 'exec_outcome_unknown'; @@ -495,9 +495,11 @@ router.post('/:id/exec', asyncHandler(async (req, res) => { } finally { if (!keepLease) await container.releaseExecLease(lease); } + const { guestUid, ...commandResult } = result; audit.outcome = 'exited'; - audit.exitCode = result.exitCode; - return ok(res, result); + audit.guestUid = guestUid; + audit.exitCode = commandResult.exitCode; + return ok(res, commandResult); } catch (err) { const safe = err instanceof ApiError ? err : new ApiError(500, 'internal_error', 'Internal server error'); audit.outcome = safe.code; diff --git a/create-a-container/utils/__tests__/guest-exec.test.js b/create-a-container/utils/__tests__/guest-exec.test.js index 5ad090a9..2342537e 100644 --- a/create-a-container/utils/__tests__/guest-exec.test.js +++ b/create-a-container/utils/__tests__/guest-exec.test.js @@ -1,7 +1,9 @@ const fs = require('node:fs'); -const { spawn, execFileSync } = require('node:child_process'); +const os = require('node:os'); +const path = require('node:path'); +const { spawn, spawnSync, execFileSync } = require('node:child_process'); const WebSocket = require('ws'); -const { executeGuest, bootstrapLine, wrapperScript, parseResult } = require('../guest-exec'); +const { executeGuest, bootstrapLine, wrapperScript, guestUserScript, parseResult } = require('../guest-exec'); const NONCE = '0123456789abcdef0123456789abcdef'; @@ -111,6 +113,54 @@ describe('wrapperScript', () => { }); }); +// Exercise the real credential transition when the test host can act as guest root. +const linuxSudoTest = process.platform === 'linux' && process.getuid() === 0 && + spawnSync('sudo', ['-n', '-H', '-u', 'nobody', '--', 'true']).status === 0 ? test : test.skip; + +describe('guestUserScript with sudo', () => { + let dir; + + beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mieweb-guest-user-')); + // Both root and the target user must be able to create the test file. + fs.chmodSync(dir, 0o777); + }); + afterEach(() => fs.rmSync(dir, { recursive: true, force: true })); + + linuxSudoTest('runs with the guest UID, preserves argv, and creates files owned by the guest user', async () => { + const uid = Number(execFileSync('id', ['-u', 'nobody'], { encoding: 'utf8' })); + const file = path.join(dir, 'created'); + const args = ["it's two words", '$HOME *', '', 'fs\x1csep', 'line\nbreak']; + const command = 'touch "$1" || exit 1; shift; id -un; printf "%s|" "$@"; printf failure >&2; exit 23'; + const out = await runSh(guestUserScript(NONCE, 'nobody', ['sh', '-c', command, 'guest', file, ...args])); + const { result, guestUid } = parseResult(out, NONCE); + + expect(guestUid).toBe(uid); + expect(fs.statSync(file).uid).toBe(uid); + expect(result.exitCode).toBe(23); + expect(decode(result.stdout).toString()).toBe(`nobody\n${args.map(arg => `${arg}|`).join('')}`); + expect(decode(result.stderr).toString()).toBe('failure'); + }); + + linuxSudoTest('refuses a missing guest account before dispatch', async () => { + const file = path.join(dir, 'unexpected'); + const out = await runSh(guestUserScript(NONCE, 'mieweb-no-such-guest-account', ['touch', file])); + expect(parseResult(out, NONCE)).toEqual({ error: 'guest_user_unavailable' }); + expect(fs.existsSync(file)).toBe(false); + }); + + linuxSudoTest('stops the guest process when its time limit expires', async () => { + const script = 'echo $$; exec sleep 60'; + const out = await runSh(guestUserScript(NONCE, 'nobody', ['sh', '-c', script], { timeLimitSeconds: 1 })); + const { timedOut, result } = parseResult(out, NONCE); + expect(timedOut).toBe(true); + expect(result.exitCode).toBe(137); + const pid = Number(decode(result.stdout).toString().trim()); + expect(pid).toBeGreaterThan(1); + expect(() => process.kill(pid, 0)).toThrow(expect.objectContaining({ code: 'ESRCH' })); + }); +}); + describe('parseResult', () => { test('waits for a complete result and ignores markers with another nonce', () => { expect(parseResult('MIEWEB-BEGIN-other 0 0 0 0\nMIEWEB-SPLIT-other\nMIEWEB-END-other\n', NONCE)).toBeNull(); @@ -129,7 +179,7 @@ describe('parseResult', () => { * then unframes `0::` input into a shell standing in for the * guest's console. Output is relayed unframed. */ -function fakeTermproxy({ onInput } = {}) { +function fakeTermproxy({ onInput, env = process.env } = {}) { const server = new WebSocket.Server({ port: 0, host: '127.0.0.1' }); server.sessionsEnded = 0; server.on('connection', (socket) => { @@ -142,7 +192,7 @@ function fakeTermproxy({ onInput } = {}) { if (newline < 0) return; if (pending.subarray(0, newline).toString() !== 'root@pam:TICKET') return socket.close(); pending = pending.subarray(newline + 1); - shell = spawn('/bin/sh', [], { stdio: ['pipe', 'pipe', 'pipe'], detached: true }); + shell = spawn('/bin/sh', [], { env, stdio: ['pipe', 'pipe', 'pipe'], detached: true }); // Like lxc-attach's host terminal, output processing turns \n into \r\n. const relay = (chunk) => socket.send(Buffer.from(chunk.toString('latin1').replace(/\n/g, '\r\n'), 'latin1')); shell.stdout.on('data', relay); @@ -180,26 +230,74 @@ function fakeNode(server, config = {}) { describe('executeGuest', () => { let server; + let guestTools; + + // Exercise the transport independently of host sudoers and the Jest user's UID. + beforeAll(() => { + guestTools = fs.mkdtempSync(path.join(os.tmpdir(), 'mieweb-guest-tools-')); + const addTool = (name, body) => fs.writeFileSync(path.join(guestTools, name), body, { mode: 0o755 }); + addTool('sudo', '#!/bin/sh\n[ "$1 $2 $3 $4 $5" = "-n -H -u guest-user --" ] || exit 1\nshift 5\nexport TEST_GUEST_USER=guest-user\nexec "$@"\n'); + addTool('id', `#!/bin/sh +[ "$TEST_GUEST_USER" = guest-user ] || exit 1 +case "$1" in + -u) echo "\${TEST_GUEST_UID:-1777}" ;; + -un) echo "\${TEST_GUEST_NAME:-guest-user}" ;; + *) exit 1 ;; +esac +`); + if (process.platform === 'darwin') { + addTool('setsid', `#!${process.execPath} +const { spawnSync } = require('node:child_process'); +const [cmd, ...args] = process.argv.slice(3); // skip --wait +process.exit(spawnSync(cmd, args, { detached: true, stdio: 'inherit' }).status ?? 1); +`); + addTool('timeout', '#!/bin/sh\nshift 3\nexec "$@"\n'); + } + }); + afterAll(() => fs.rmSync(guestTools, { recursive: true, force: true })); afterEach(() => new Promise((resolve) => server.close(resolve))); - test('runs a command through the termproxy console', async () => { - server = await fakeTermproxy(); + test('runs a command through the termproxy console as the requested guest user', async () => { + server = await fakeTermproxy({ env: { ...process.env, PATH: `${guestTools}:${process.env.PATH}` } }); const { node } = fakeNode(server); const result = await executeGuest({ - node, vmid: 701, hostname: 'web', leaseUntil: lease(), argv: ['sh', '-c', 'printf out; printf err >&2; exit 3'], + node, vmid: 701, hostname: 'web', guestUser: 'guest-user', leaseUntil: lease(), argv: ['sh', '-c', 'printf out; printf err >&2; exit 3'], }); expect(result).toEqual({ stdout: Buffer.from('out').toString('base64'), stderr: Buffer.from('err').toString('base64'), - exitCode: 3, stdoutTruncated: false, stderrTruncated: false, + exitCode: 3, stdoutTruncated: false, stderrTruncated: false, guestUid: 1777, }); // The console session is over before the caller can release its lease. expect(server.sessionsEnded).toBe(1); }); + test.each([ + ['UID zero', { TEST_GUEST_UID: '0' }], + ['another account', { TEST_GUEST_NAME: 'other' }], + ])('refuses a credential switch to %s without executing the payload', async (_label, mismatch) => { + const env = { ...process.env, ...mismatch, PATH: `${guestTools}:${process.env.PATH}` }; + server = await fakeTermproxy({ env }); + const { node } = fakeNode(server); + const marker = path.join(guestTools, 'unexpected'); + await expect(executeGuest({ + node, vmid: 701, hostname: 'web', guestUser: 'guest-user', argv: ['touch', marker], leaseUntil: lease(), + })).rejects.toMatchObject({ code: 'guest_user_unavailable' }); + expect(fs.existsSync(marker)).toBe(false); + }); + + test.each(['root', '#0', '-u', '', undefined])('refuses the guest login %p before opening the console', async (guestUser) => { + server = await fakeTermproxy(); + const { node, client } = fakeNode(server); + await expect(executeGuest({ + node, vmid: 701, hostname: 'web', guestUser, argv: ['id'], leaseUntil: lease(), + })).rejects.toMatchObject({ code: 'guest_user_unavailable' }); + expect(client.lxcTermproxy).not.toHaveBeenCalled(); + }); + test('refuses a guest whose hostname does not match', async () => { server = await fakeTermproxy(); const { node, client } = fakeNode(server, { hostname: 'other' }); - await expect(executeGuest({ node, vmid: 701, hostname: 'web', argv: ['id'], leaseUntil: lease() })) + await expect(executeGuest({ node, vmid: 701, hostname: 'web', guestUser: 'guest-user', argv: ['id'], leaseUntil: lease() })) .rejects.toMatchObject({ code: 'guest_identity_mismatch' }); expect(client.lxcTermproxy).not.toHaveBeenCalled(); }); @@ -207,7 +305,7 @@ describe('executeGuest', () => { test('switches a running guest to shell mode and asks for a restart', async () => { server = await fakeTermproxy(); const { node, client } = fakeNode(server, { cmode: undefined }); - await expect(executeGuest({ node, vmid: 701, hostname: 'web', argv: ['id'], leaseUntil: lease() })) + await expect(executeGuest({ node, vmid: 701, hostname: 'web', guestUser: 'guest-user', argv: ['id'], leaseUntil: lease() })) .rejects.toMatchObject({ code: 'exec_restart_required' }); expect(client.updateLxcConfig).toHaveBeenCalledWith('pve1', 701, { cmode: 'shell' }); expect(client.lxcTermproxy).not.toHaveBeenCalled(); @@ -216,7 +314,7 @@ describe('executeGuest', () => { test('refuses a stopped guest', async () => { server = await fakeTermproxy(); const { node } = fakeNode(server, { status: 'stopped' }); - await expect(executeGuest({ node, vmid: 701, hostname: 'web', argv: ['id'], leaseUntil: lease() })) + await expect(executeGuest({ node, vmid: 701, hostname: 'web', guestUser: 'guest-user', argv: ['id'], leaseUntil: lease() })) .rejects.toMatchObject({ code: 'guest_not_running' }); }); @@ -229,14 +327,34 @@ describe('executeGuest', () => { }, }); const { node } = fakeNode(server); - await expect(executeGuest({ node, vmid: 701, hostname: 'web', argv: ['id'], leaseUntil: lease() })) + await expect(executeGuest({ node, vmid: 701, hostname: 'web', guestUser: 'guest-user', argv: ['id'], leaseUntil: lease() })) .rejects.toMatchObject({ code: 'exec_outcome_unknown' }); }); + test('keeps the outcome unknown if the console closes after the guest result but before the root session ends', async () => { + server = await fakeTermproxy({ + onInput(bytes, socket) { + const match = bytes.toString().match(/MIEWEB-SESSION-END-([0-9a-f]{32})/); + if (!match) return true; + const nonce = match[1]; + const result = [ + `MIEWEB-USER-${nonce} 1777`, `MIEWEB-BEGIN-${nonce} 0 0 0 0`, + `MIEWEB-SPLIT-${nonce}`, `MIEWEB-END-${nonce}`, '', + ].join('\n'); + socket.send(result, () => socket.close()); + return false; + }, + }); + const { node } = fakeNode(server); + await expect(executeGuest({ + node, vmid: 701, hostname: 'web', guestUser: 'guest-user', argv: ['id'], leaseUntil: lease(), + })).rejects.toMatchObject({ code: 'exec_outcome_unknown' }); + }); + test('does not open the console when the lease would expire first', async () => { server = await fakeTermproxy(); const { node, client } = fakeNode(server); - await expect(executeGuest({ node, vmid: 701, hostname: 'web', argv: ['id'], leaseUntil: lease(30) })) + await expect(executeGuest({ node, vmid: 701, hostname: 'web', guestUser: 'guest-user', argv: ['id'], leaseUntil: lease(30) })) .rejects.toMatchObject({ code: 'exec_unavailable' }); expect(client.lxcTermproxy).not.toHaveBeenCalled(); }); @@ -245,7 +363,7 @@ describe('executeGuest', () => { server = await fakeTermproxy(); const { node, client } = fakeNode(server); client.lxcTermproxy.mockResolvedValue({ user: 'root@pam', ticket: 'WRONG', port: server.address().port }); - await expect(executeGuest({ node, vmid: 701, hostname: 'web', argv: ['id'], leaseUntil: lease() })) + await expect(executeGuest({ node, vmid: 701, hostname: 'web', guestUser: 'guest-user', argv: ['id'], leaseUntil: lease() })) .rejects.toMatchObject({ code: 'exec_unavailable' }); }); }); diff --git a/create-a-container/utils/guest-exec.js b/create-a-container/utils/guest-exec.js index 3e69e9b2..a27f47d9 100644 --- a/create-a-container/utils/guest-exec.js +++ b/create-a-container/utils/guest-exec.js @@ -2,8 +2,9 @@ // // With `cmode: shell`, the guest console opened by termproxy is a root shell // (`lxc-attach`) with no login. A one-line bootstrap switches that terminal to -// raw mode and replaces the login shell with a non-interactive `sh -s`. A -// POSIX wrapper then runs the command, collecting stdout and stderr in files, +// raw mode and replaces the login shell with a non-interactive `sh -s`. +// sudo switches to the authenticated guest account before a POSIX wrapper +// runs the command, collecting stdout and stderr in files, // and prints the result hex-encoded between markers that contain a // per-request nonce. See docs/admins/guest-exec.md. const crypto = require('node:crypto'); @@ -18,7 +19,9 @@ const BOOTSTRAP_RETRY_MS = 2_000; // A shell that bootstrapped but never received a complete wrapper kills // itself after this long, so it can't hold the shared console session. const UNARMED_SHELL_SECONDS = 10; -const RESULT_TIMEOUT_MS = (TIME_LIMIT_SECONDS + 10) * 1_000; +// Bound sudo/PAM/NSS setup and teardown as well as the command's own timer. +const SESSION_LIMIT_SECONDS = TIME_LIMIT_SECONDS + 15; +const RESULT_TIMEOUT_MS = (SESSION_LIMIT_SECONDS + 5) * 1_000; // After the result, wait this long for the console to close: the shell has // exited, and the session should be gone before the lease is released. const SESSION_END_MS = 5_000; @@ -66,15 +69,8 @@ function bootstrapLine(nonce) { } /** - * The script read by `sh -s`. It is one brace group, so the shell runs - * nothing until it has read all of it: a connection that drops mid-script - * can't start the command without its time limit. The group first cancels - * the bootstrap's timer. - * - * The command's stdin must be /dev/null because the shell reads this script - * from the terminal. Some shells (dash) treat `sh -s` on a terminal as - * interactive and give background jobs their own process group, so job - * control is turned off and the shell hangs up its own group at the end, like + * Runs entirely as the guest user. The command gets /dev/null for stdin. + * Job control is turned off and the shell hangs up its own group at the end, like * an SSH session closing: plain background jobs stop while processes that * detached on purpose (setsid, nohup) keep running. Background jobs can still * write until then, so each stream is copied before it is measured and @@ -85,7 +81,6 @@ function wrapperScript(nonce, argv, { timeLimitSeconds = TIME_LIMIT_SECONDS } = const fail = `{ printf '\\nMIEWEB-ERROR-${nonce}\\n'; exit 1; }`; return [ '{', - 'kill -s KILL "$MIEWEB_T" 2>/dev/null; unset MIEWEB_T', 'set +m', `d=/tmp/.mieweb-exec-${nonce}`, // Private without changing the umask the command inherits. @@ -100,12 +95,12 @@ function wrapperScript(nonce, argv, { timeLimitSeconds = TIME_LIMIT_SECONDS } = 'rc=$?', 'kill -s KILL "$w" 2>/dev/null', 't=0; [ -e "$d/t" ] && t=1', - `dd if="$d/o" of="$d/O" bs=${STREAM_LIMIT + 1} count=1 2>/dev/null`, - `dd if="$d/e" of="$d/E" bs=${STREAM_LIMIT + 1} count=1 2>/dev/null`, - `printf '\\nMIEWEB-BEGIN-${nonce} %s %s %s %s\\n' "$rc" "$t" $(wc -c <"$d/O") $(wc -c <"$d/E")`, - `dd if="$d/O" bs=${STREAM_LIMIT} count=1 2>/dev/null | od -A n -t x1 -v`, + `dd if="$d/o" of="$d/o.capture" bs=${STREAM_LIMIT + 1} count=1 2>/dev/null`, + `dd if="$d/e" of="$d/e.capture" bs=${STREAM_LIMIT + 1} count=1 2>/dev/null`, + `printf '\\nMIEWEB-BEGIN-${nonce} %s %s %s %s\\n' "$rc" "$t" $(wc -c <"$d/o.capture") $(wc -c <"$d/e.capture")`, + `dd if="$d/o.capture" bs=${STREAM_LIMIT} count=1 2>/dev/null | od -A n -t x1 -v`, `printf 'MIEWEB-SPLIT-${nonce}\\n'`, - `dd if="$d/E" bs=${STREAM_LIMIT} count=1 2>/dev/null | od -A n -t x1 -v`, + `dd if="$d/e.capture" bs=${STREAM_LIMIT} count=1 2>/dev/null | od -A n -t x1 -v`, `printf 'MIEWEB-END-${nonce}\\n'`, 'rm -rf "$d"', "trap '' HUP", @@ -116,6 +111,41 @@ function wrapperScript(nonce, argv, { timeLimitSeconds = TIME_LIMIT_SECONDS } = ].join('\n'); } +/** + * The root shell reads this entire brace group before doing anything. Only a + * fixed identity check is passed to sudo. The requested argv and the capture + * script travel on a pipe to the switched shell, outside sudo's command log. + * setsid keeps the guest process away from the controlling root console. + */ +function guestUserScript(nonce, guestUser, argv, options) { + // sudo also accepts #uid selectors. The Manager session identifies a name. + if (typeof guestUser !== 'string' || !guestUser || guestUser === 'root' + || /^[#-]|[\x00-\x1f\x7f]/.test(guestUser)) { + throw failure('guest_user_unavailable'); + } + const unavailable = `{ printf '\\nMIEWEB-ERROR-${nonce}\\n'; exit 1; }`; + const verifyUser = [ + 'uid=$(id -u) && [ "$uid" -gt 0 ] && [ "$(id -un)" = "$1" ] || exit 1', + `printf '\\nMIEWEB-USER-${nonce} %s\\n' "$uid"`, + 'exec /bin/sh -s', + ].join('\n'); + return [ + '{', + 'kill -s KILL "$MIEWEB_T" 2>/dev/null; unset MIEWEB_T', + 'set +m', + `trap "printf '\\nMIEWEB-SESSION-END-${nonce}\\n'" 0`, + `cd / || ${unavailable}`, + `for tool in sudo setsid timeout id cat; do command -v "$tool" >/dev/null || ${unavailable}; done`, + `printf '%s' ${quoteArg(wrapperScript(nonce, argv, options))} |`, + ` setsid --wait timeout -k 1 ${SESSION_LIMIT_SECONDS} sudo -n -H -u ${quoteArg(guestUser)} -- /bin/sh -c ${quoteArg(verifyUser)} sh ${quoteArg(guestUser)} 2>/dev/null |`, + // Only the root-side relay holds the console FD, even during sudo setup. + ` timeout -k 1 ${SESSION_LIMIT_SECONDS + 2} cat`, + 'exit', + '}', + '', + ].join('\n'); +} + function decodeStream(hex, size) { const digits = hex.replace(/\s+/g, ''); const bytes = Buffer.from(digits, 'hex'); @@ -127,7 +157,7 @@ function decodeStream(hex, size) { /** * Find the wrapper's result in the console output. - * @returns {null | {error: string} | {timedOut: boolean, result: object}} + * @returns {null | {error: string} | {guestUid?: number, timedOut: boolean, result: object}} * null while the result is incomplete */ function parseResult(output, nonce) { @@ -135,10 +165,15 @@ function parseResult(output, nonce) { `MIEWEB-ERROR-${nonce}\\n|MIEWEB-BEGIN-${nonce} (\\d+) ([01]) (\\d+) (\\d+)\\n` + `([0-9a-f\\s]*)MIEWEB-SPLIT-${nonce}\\n([0-9a-f\\s]*)MIEWEB-END-${nonce}\\n`, )); - if (!match) return null; + const identity = output.match(new RegExp(`MIEWEB-USER-${nonce} ([1-9]\\d*)\\n`)); + if (!match) { + if (!output.includes(`MIEWEB-SESSION-END-${nonce}\n`)) return null; + return { error: identity ? 'exec_outcome_unknown' : 'guest_user_unavailable' }; + } if (match[1] === undefined) return { error: 'exec_unavailable' }; const [, exitCode, timedOut, stdoutSize, stderrSize, stdout, stderr] = match; return { + guestUid: identity ? Number(identity[1]) : undefined, timedOut: timedOut === '1', result: { stdout: decodeStream(stdout, Number(stdoutSize)), @@ -283,44 +318,50 @@ function requireLease(leaseUntil, ms) { } /** - * Run argv as root in a running Proxmox guest. + * Run argv as the authenticated account in a running Proxmox guest. * @param {object} request * @param {object} request.node - Node model instance (proxmox) * @param {number} request.vmid * @param {string} request.hostname - Expected guest hostname + * @param {string} request.guestUser - Canonical Manager login * @param {string[]} request.argv * @param {Date} request.leaseUntil - Expiry of the caller's * Container#claimExecLease * @returns {Promise<{stdout: string, stderr: string, exitCode: number, - * stdoutTruncated: boolean, stderrTruncated: boolean}>} base64 streams + * stdoutTruncated: boolean, stderrTruncated: boolean, guestUid: number}>} base64 streams * Callers must hold Container#claimExecLease: commands on one guest share a * console session. * @throws {Error} with `code`: exec_unavailable, guest_not_running, - * guest_identity_mismatch, exec_restart_required, exec_timeout or + * guest_identity_mismatch, guest_user_unavailable, exec_restart_required, exec_timeout or * exec_outcome_unknown. Never retried: the command may have run. */ -async function executeGuest({ node, vmid, hostname, argv, leaseUntil }) { +async function executeGuest({ node, vmid, hostname, guestUser, argv, leaseUntil }) { + const nonce = crypto.randomBytes(16).toString('hex'); + const script = guestUserScript(nonce, guestUser, argv); let term; let dispatched = false; try { const client = await node.api({ timeout: API_TIMEOUT_MS }); await prepareGuest(client, node.name, vmid, hostname); - const nonce = crypto.randomBytes(16).toString('hex'); requireLease(leaseUntil, 3 * API_TIMEOUT_MS + BOOTSTRAP_TIMEOUT_MS + RESULT_TIMEOUT_MS); term = await openConsole(client, node.name, vmid); await bootstrap(term, nonce); requireLease(leaseUntil, RESULT_TIMEOUT_MS); - term.write(wrapperScript(nonce, argv)); + term.write(script); dispatched = true; - const outcome = await term.until(out => parseResult(out, nonce), RESULT_TIMEOUT_MS); + // A result can arrive before sudo finishes PAM cleanup. Hold the lease + // until the root shell exits its pipeline, even if the command has exited. + const outcome = await term.until(out => out.includes(`MIEWEB-SESSION-END-${nonce}\n`) + && parseResult(out, nonce), RESULT_TIMEOUT_MS); // The wrapper exits after printing its result, which ends the shared // console session. Let it finish so the next exec gets a new session. await term.ended(SESSION_END_MS); if (outcome.error) throw failure(outcome.error); if (outcome.timedOut) throw failure('exec_timeout'); - return outcome.result; + if (!Number.isSafeInteger(outcome.guestUid)) throw failure('exec_outcome_unknown'); + return { ...outcome.result, guestUid: outcome.guestUid }; } catch (err) { - if (['exec_unavailable', 'guest_not_running', 'guest_identity_mismatch', + if (['exec_unavailable', 'guest_not_running', 'guest_identity_mismatch', 'guest_user_unavailable', 'exec_restart_required', 'exec_timeout', 'exec_outcome_unknown'].includes(err.code)) throw err; throw failure(dispatched ? 'exec_outcome_unknown' : 'exec_unavailable'); } finally { @@ -328,4 +369,4 @@ async function executeGuest({ node, vmid, hostname, argv, leaseUntil }) { } } -module.exports = { executeGuest, EXEC_LEASE_SECONDS, quoteArg, bootstrapLine, wrapperScript, parseResult }; +module.exports = { executeGuest, EXEC_LEASE_SECONDS, quoteArg, bootstrapLine, wrapperScript, guestUserScript, parseResult }; diff --git a/mie-opensource-landing/docs/admins/guest-exec.md b/mie-opensource-landing/docs/admins/guest-exec.md index 9e0dcf05..0a164386 100644 --- a/mie-opensource-landing/docs/admins/guest-exec.md +++ b/mie-opensource-landing/docs/admins/guest-exec.md @@ -1,11 +1,11 @@ # Guest Exec -`mieweb exec` runs one command as root in a running Proxmox container, for its owner or an admin. Manager uses only the node's Proxmox API (the `termproxy` console), so nothing is installed on the Proxmox hosts or in the guest, and the guest needs no SSH. +`mieweb exec` lets a container owner or a Manager admin run a command in a running Proxmox container. Manager connects through the node's `termproxy` console and uses `sudo` to start the command as the signed-in caller's Linux account. The guest needs no SSH access. ```sh mieweb login -mieweb exec --site 1 --container 42 -- id -mieweb exec --site 1 --container 42 -- sh -c 'apt-get update && apt-get install -y curl' +mieweb exec --site 1 --container 42 -- id -un +mieweb exec --site 1 --container 42 -- id -u ``` `--container` is the Manager container ID, not the Proxmox VMID. Each word after `--` is passed as one argument, without shell interpretation. Call `sh -c` explicitly for shell syntax. @@ -17,7 +17,12 @@ mieweb exec --site 1 --container 42 -- sh -c 'apt-get update && apt-get install | Node type | Proxmox only. Docker and dummy nodes return `exec_unavailable`. | | Console mode | The container's `cmode` must be `shell`. Manager sets it on new containers (see below). | | Node credentials | `VM.Audit`, `VM.Console` and `VM.Config.Options` on the container. `root@pam` (see [Nodes](core-concepts/nodes.md#authentication)) has them; API tokens work too. | -| Guest tools | `sh`, `stty`, `mkdir`, `sleep`, `cat`, `wc`, `dd` and `od`. Images without a shell (distroless) are unsupported. | +| Guest account | The guest must resolve the caller's exact Manager username to a non-root Linux account. The guest's numeric UID may differ from the Manager UID. This also applies to admins running commands in someone else's container and to the owner of a Manager API key. | +| Guest tools | `sudo`, util-linux `setsid`, `timeout`, `id`, `sh`, `stty`, `mkdir`, `sleep`, `cat`, `wc`, `dd` and `od`. Images without a shell (distroless) are unsupported. | + +If the guest account is missing, has a different name, resolves to UID 0, or `sudo` refuses the switch, Manager returns `guest_user_unavailable` before running the command. Check the guest's local account, directory service, and sudo configuration. A guest missing `sudo`, `setsid`, `timeout`, or `id` returns `exec_unavailable`. + +For a command that previously depended on implicit root, request elevation explicitly, for example `mieweb exec --site 1 --container 42 -- sudo -n apt-get update`. The guest's sudo policy must allow that command without a password prompt. The supplied base image grants passwordless sudo to members of `ldapusers`. ## Console mode @@ -32,14 +37,14 @@ Proxmox applies a `cmode` change to a running container only after it restarts. | Item | Behavior | | --- | --- | -| User | Guest root, in `/`, with stdin from `/dev/null` | +| User | The caller's matching guest account, in `/`, with stdin from `/dev/null` and no controlling terminal | | Time limit | 30 seconds, after which the command is killed (`exec_timeout`) | | Output | First 64 KiB of stdout and stderr each, reported separately with truncation flags | | Exit status | Returned as-is. A nonzero exit is still HTTP 200. Killed by a signal: 128 + signal number. | | Arguments | At most 128 arguments and 16 KiB in total, no NUL bytes | | Background processes | When the command returns, plain `&` jobs receive SIGHUP. Processes started with `setsid`, `nohup` or a service manager keep running. Their stdout and stderr stay attached to the command's capture files, which are deleted after the exec but keep using disk while written to, so redirect a long-running process's output (for example `nohup app >/var/log/app.log 2>&1 &`) or start it with a service manager. | | Concurrency | One command per container at a time, across all Manager processes (`exec_busy`). If the outcome is unknown (the connection dropped after the command was sent), or the Manager process died, the container stays busy until the claim expires after 150 seconds. | -| Audit | Manager logs the caller, container, timing and outcome. Arguments and output are not logged. | +| Audit | Manager logs the caller's Manager UID, the effective guest identity for a completed command, the container, timing, and outcome. Arguments and output are not logged. | If the connection drops after the command was sent, the result is `exec_outcome_unknown`. Check the container's state before running a command that changes state again. diff --git a/packages/os-cloud-provider/README.md b/packages/os-cloud-provider/README.md index 8a47247d..91986b8b 100644 --- a/packages/os-cloud-provider/README.md +++ b/packages/os-cloud-provider/README.md @@ -28,9 +28,13 @@ The Manager record ID can differ from the Proxmox VMID in `DeployResult`. mieweb exec --site 1 --container 12 -- node --version ``` -Exec uses the same Manager login or `MIEWEB_OS_TOKEN` as deploy. It works -with SSH unpublished. If the connection drops before the result arrives, -check the guest before retrying a command that changes state. +Exec uses the same Manager login or `MIEWEB_OS_TOKEN` as deploy. On a Manager +with caller-scoped exec, the guest must have `sudo`, `setsid`, `timeout`, and a non-root +Linux account with the caller's exact Manager username. Guest and Manager UIDs +may differ. This applies to admins as well as owners. Use +`id -un` and `id -u` to check the guest identity. Exec works with SSH +unpublished. If the connection drops before the result arrives, check the +guest before retrying a command that changes state. `login` prints a short verification code and a Manager URL. Open the URL on any device, including a phone while the CLI runs on a server over SSH. Check diff --git a/packages/os-cloud-provider/test/exec-guest.e2e.mjs b/packages/os-cloud-provider/test/exec-guest.e2e.mjs index 1041265e..7a76e9b2 100644 --- a/packages/os-cloud-provider/test/exec-guest.e2e.mjs +++ b/packages/os-cloud-provider/test/exec-guest.e2e.mjs @@ -1,14 +1,16 @@ // Run from a project with the exec-capable CLI and OS provider, after // mieweb login or with MIEWEB_OS_URL / MIEWEB_OS_TOKEN. The first guest must -// be running, owned by this non-admin caller, with sh and no published SSH. +// be running, owned by this non-admin caller, with sudo, setsid, a matching +// Linux account, and no published SSH. Supply the caller's Manager username. // The second must exist and be owned by someone else. -// node /path/to/exec-guest.e2e.mjs +// node /path/to/exec-guest.e2e.mjs import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; -const [site, own, other] = process.argv.slice(2); +const [site, own, other, username] = process.argv.slice(2); assert([site, own, other].every(id => /^[1-9]\d*$/.test(id)), 'Supply positive site, owned guest, and other guest IDs'); assert.notEqual(own, other, 'The guests must be distinct'); +assert(username, "Supply the caller's Manager username"); function exec(guest, argv) { const result = spawnSync(process.env.MIEWEB_BIN || 'mieweb', ['exec', '--target', 'mieweb', '--site', site, '--container', guest, '--', ...argv], @@ -17,6 +19,12 @@ function exec(guest, argv) { return result; } +const identity = exec(own, ['sh', '-c', 'id -un && id -u']); +assert.equal(identity.status, 0, identity.stderr); +const [guestUser, guestUid] = identity.stdout.trimEnd().split('\n'); +assert.equal(guestUser, username); +assert.match(guestUid, /^[1-9]\d*$/); + const literal = 'two words; $HOME *'; const success = exec(own, ['sh', '-c', 'printf "%s" "$1"', 'argv0', literal]); assert.equal(success.status, 0, success.stderr); @@ -32,4 +40,4 @@ const denied = exec(other, ['sh', '-c', 'printf unexpected']); assert.equal(denied.status, 125, denied.stderr); assert.equal(denied.stdout, ''); assert.match(denied.stderr, /not found|forbidden|only the owner/i); -console.log('PASS: literal argv, separate streams, guest exit 23, and denied execution on another guest'); +console.log('PASS: caller username and UID, literal argv, separate streams, guest exit 23, and denied execution on another guest');