Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix(secret-rotation): match Unix/Linux passwd prompts against the full session buffer

Claudeb98156267177
diff --git a/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns.test.ts b/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns.test.ts
new file mode 100644
index 0000000000..242c3aec9a
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns.test.ts
@@ -0,0 +1,251 @@
+import { describe, expect, test } from "vitest";
+
+import {
+ runManagedPasswordChange,
+ runSelfPasswordChange,
+ runSuLoginVerification,
+ TInteractiveShellStream
+} from "./unix-linux-local-account-rotation-fns";
+
+const OLD_PASSWORD = "0ld-P@ssw0rd";
+const NEW_PASSWORD = "n3w-P@ssw0rd";
+const APP_CONNECTION_PASSWORD = "svc-P@ssw0rd";
+
+type TFakeStream = {
+ stream: TInteractiveShellStream;
+ writes: string[];
+ feed: (text: string) => void;
+ feedBytes: (chunk: Buffer) => void;
+ close: () => void;
+};
+
+const createFakeStream = (): TFakeStream => {
+ const writes: string[] = [];
+ const dataListeners: ((chunk: Buffer) => void)[] = [];
+ const closeListeners: (() => void)[] = [];
+
+ const stream = {
+ on: (event: string, listener: unknown) => {
+ if (event === "data") dataListeners.push(listener as (chunk: Buffer) => void);
+ if (event === "close") closeListeners.push(listener as () => void);
+ },
+ write: (data: string) => {
+ writes.push(data);
+ },
+ end: () => {}
+ } as unknown as TInteractiveShellStream;
+
+ const feedBytes = (chunk: Buffer) => dataListeners.forEach((listener) => listener(chunk));
+
+ return {
+ stream,
+ writes,
+ feed: (text: string) => feedBytes(Buffer.from(text, "utf8")),
+ feedBytes,
+ close: () => closeListeners.forEach((listener) => listener())
+ };
+};
+
+// Real transcripts, `\r\n` included, because the handlers read a PTY where ONLCR is on.
+const LINUX_MANAGED_TRANSCRIPT = "New password: \r\nRetype new password: \r\npasswd: password updated successfully\r\n";
+
+const AIX_MANAGED_TRANSCRIPT =
+ "Changing password for \"root\"\r\nroot's New password: \r\nRe-enter root's new password: \r\n";
+
+const SUDO_MANAGED_TRANSCRIPT =
+ "[sudo] password for svc: \r\nChanging password for \"root\"\r\nroot's New password: \r\nRe-enter root's new password: \r\n";
+
+const LINUX_SELF_TRANSCRIPT =
+ "Changing password for jdoe.\r\nCurrent password: \r\nNew password: \r\nRetype new password: \r\npasswd: password updated successfully\r\n";
+
+const driveManagedChange = (chunks: string[]) => {
+ const fake = createFakeStream();
+ const result = runManagedPasswordChange(fake.stream, NEW_PASSWORD, APP_CONNECTION_PASSWORD);
+ chunks.forEach((chunk) => fake.feed(chunk));
+ fake.close();
+ return { writes: fake.writes, result };
+};
+
+const driveSelfChange = (chunks: string[]) => {
+ const fake = createFakeStream();
+ const result = runSelfPasswordChange(fake.stream, OLD_PASSWORD, NEW_PASSWORD);
+ chunks.forEach((chunk) => fake.feed(chunk));
+ fake.close();
+ return { writes: fake.writes, result };
+};
+
+const everySplitOf = (transcript: string) => {
+ const splits: { offset: number; chunks: string[] }[] = [];
+ for (let offset = 0; offset <= transcript.length; offset += 1) {
+ splits.push({ offset, chunks: [transcript.slice(0, offset), transcript.slice(offset)] });
+ }
+ return splits;
+};
+
+const MANAGED_TRANSCRIPTS: [string, string, string[]][] = [
+ ["Linux passwd", LINUX_MANAGED_TRANSCRIPT, [`${NEW_PASSWORD}\n`, `${NEW_PASSWORD}\n`]],
+ ["AIX 7.2 passwd", AIX_MANAGED_TRANSCRIPT, [`${NEW_PASSWORD}\n`, `${NEW_PASSWORD}\n`]],
+ ["sudo passwd", SUDO_MANAGED_TRANSCRIPT, [`${APP_CONNECTION_PASSWORD}\n`, `${NEW_PASSWORD}\n`, `${NEW_PASSWORD}\n`]]
+];
+
+describe("runManagedPasswordChange", () => {
+ test.each(MANAGED_TRANSCRIPTS)(
+ "%s: answers every prompt identically however the transcript is split",
+ async (_name, transcript, expectedWrites) => {
+ const runs = everySplitOf(transcript).map(({ offset, chunks }) => ({
+ offset,
+ ...driveManagedChange(chunks)
+ }));
+
+ await Promise.all(runs.map(({ result }) => expect(result).resolves.toBeUndefined()));
+
+ runs.forEach(({ offset, writes }) => {
+ expect(writes, `split at offset ${offset}`).toEqual(expectedWrites);
+ });
+ }
+ );
+
+ test.each(MANAGED_TRANSCRIPTS)(
+ "%s: completes when the host coalesces the whole transcript into one chunk",
+ async (_name, transcript, expectedWrites) => {
+ const { writes, result } = driveManagedChange([transcript]);
+
+ await expect(result).resolves.toBeUndefined();
+ expect(writes).toEqual(expectedWrites);
+ }
+ );
+
+ test("sends the new password exactly twice, never a third time", async () => {
+ // AIX names the password twice ("root's New password", "Re-enter root's new password"), so an
+ // unconsumed buffer would let the first prompt satisfy the confirmation as well.
+ const runs = [
+ driveManagedChange([AIX_MANAGED_TRANSCRIPT]),
+ ...everySplitOf(AIX_MANAGED_TRANSCRIPT).map(({ chunks }) => driveManagedChange(chunks))
+ ];
+
+ await Promise.all(runs.map(({ result }) => expect(result).resolves.toBeUndefined()));
+
+ runs.forEach(({ writes }) => {
+ expect(writes.filter((write) => write === `${NEW_PASSWORD}\n`)).toHaveLength(2);
+ });
+ });
+
+ test("rejects when the host floods the channel without a recognized prompt", async () => {
+ const fake = createFakeStream();
+ const result = runManagedPasswordChange(fake.stream, NEW_PASSWORD);
+
+ fake.feed("motd line\r\n".repeat(7_000));
+
+ await expect(result).rejects.toThrow(/without a recognized prompt/);
+ expect(fake.writes).toEqual([]);
+ });
+
+ test("treats `passwd: password unchanged` as a failure, not a successful rotation", async () => {
+ const { writes, result } = driveManagedChange([
+ "New password: \r\nRetype new password: \r\n",
+ "passwd: password unchanged\r\n"
+ ]);
+
+ await expect(result).rejects.toThrow(/passwd: password unchanged/);
+ expect(writes).toEqual([`${NEW_PASSWORD}\n`, `${NEW_PASSWORD}\n`]);
+ });
+
+ test("reassembles a multi-byte character split across two data events", async () => {
+ const fake = createFakeStream();
+ const result = runManagedPasswordChange(fake.stream, NEW_PASSWORD);
+ const banner = Buffer.from("motd: caf\u00e9\r\n", "utf8");
+
+ fake.feedBytes(banner.subarray(0, 10));
+ fake.feedBytes(banner.subarray(10));
+ fake.close();
+
+ const error = await result.catch((err: unknown) => err as Error);
+
+ expect(error.message).toContain("motd: caf\u00e9");
+ expect(error.message).not.toContain("\ufffd");
+ });
+
+ test("rejects with sudoers guidance when sudo asks for a password we do not have", async () => {
+ const fake = createFakeStream();
+ const result = runManagedPasswordChange(fake.stream, NEW_PASSWORD);
+
+ fake.feed(SUDO_MANAGED_TRANSCRIPT);
+
+ await expect(result).rejects.toThrow(/NOPASSWD in sudoers/);
+ expect(fake.writes).toEqual([]);
+ });
+});
+
+describe("runSelfPasswordChange", () => {
+ test("answers every prompt identically however the transcript is split", async () => {
+ const expectedWrites = [`${OLD_PASSWORD}\n`, `${NEW_PASSWORD}\n`, `${NEW_PASSWORD}\n`];
+ const runs = everySplitOf(LINUX_SELF_TRANSCRIPT).map(({ offset, chunks }) => ({
+ offset,
+ ...driveSelfChange(chunks)
+ }));
+
+ await Promise.all(runs.map(({ result }) => expect(result).resolves.toBeUndefined()));
+
+ runs.forEach(({ offset, writes }) => {
+ expect(writes, `split at offset ${offset}`).toEqual(expectedWrites);
+ });
+ });
+
+ test("treats `passwd: password unchanged` as a failure, not a successful rotation", async () => {
+ const { writes, result } = driveSelfChange([
+ "Current password: \r\nNew password: \r\nRetype new password: \r\n",
+ "passwd: password unchanged\r\n"
+ ]);
+
+ await expect(result).rejects.toThrow(/passwd: password unchanged/);
+ expect(writes).toEqual([`${OLD_PASSWORD}\n`, `${NEW_PASSWORD}\n`, `${NEW_PASSWORD}\n`]);
+ });
+
+ test("keeps passwords out of the rejection message when the tty echoes them", async () => {
+ const fake = createFakeStream();
+ const result = runSelfPasswordChange(fake.stream, OLD_PASSWORD, NEW_PASSWORD);
+
+ // Echo is still on until passwd disables it, so a password written at the wrong moment comes
+ // straight back and would otherwise be persisted as the rotation's last error.
+ fake.feed("Current password: ");
+ fake.feed(`${OLD_PASSWORD}\r\nNew password: `);
+ fake.feed(`${NEW_PASSWORD}\r\n`);
+ fake.close();
+
+ const error = await result.catch((err: unknown) => err as Error);
+
+ expect(error).toBeInstanceOf(Error);
+ expect(error.message).not.toContain(OLD_PASSWORD);
+ expect(error.message).not.toContain(NEW_PASSWORD);
+ expect(error.message).toContain("***");
+ });
+});
+
+describe("runSuLoginVerification", () => {
+ test("answers a password prompt split across data events", async () => {
+ const fake = createFakeStream();
+ const result = runSuLoginVerification(fake.stream, "root", NEW_PASSWORD);
+
+ fake.feed("Pass");
+ fake.feed("word: ");
+ fake.feed("\r\n[root@host ~]# ");
+ fake.feed("whoami\r\nroot\r\n[root@host ~]# ");
+ fake.close();
+
+ await expect(result).resolves.toBeUndefined();
+ expect(fake.writes).toEqual([`${NEW_PASSWORD}\n`, "whoami\n", "exit\n"]);
+ });
+
+ test("rejects on an authentication failure without leaking the password", async () => {
+ const fake = createFakeStream();
+ const result = runSuLoginVerification(fake.stream, "root", NEW_PASSWORD);
+
+ fake.feed("Password: ");
+ fake.feed(`${NEW_PASSWORD}\r\nsu: Authentication failure\r\n`);
+
+ const error = await result.catch((err: unknown) => err as Error);
+
+ expect(error.message).toMatch(/su authentication failed for user root/);
+ expect(error.message).not.toContain(NEW_PASSWORD);
+ });
+});
diff --git a/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns.ts
index e4b6ec607c..9434b8ac95 100644
--- a/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns.ts
+++ b/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns.ts
@@ -1,3 +1,6 @@
+import { StringDecoder } from "node:string_decoder";
+
+import RE2 from "re2";
import { Client, ClientChannel } from "ssh2";
import {
@@ -27,6 +30,59 @@ import {
} from "./unix-linux-local-account-rotation-types";
const SHELL_TIMEOUT = 15_000;
+const MAX_BUFFER_SIZE = 64 * 1024;
+const MAX_TRANSCRIPT_SIZE = 4 * 1024;
+
+const SUDO_PROMPT = new RE2("\\[sudo\\]", "i");
+const ANY_PASSWORD_PROMPT = new RE2("password", "i");
+const NEW_PASSWORD_PROMPT = new RE2("new\\s+password", "i");
+const CONFIRM_PASSWORD_PROMPT = new RE2("retype|re-?enter|again|new\\s+password", "i");
+const PASSWORD_CHANGE_SUCCEEDED = new RE2("\\b(?:success(?:fully)?|updated|changed)\\b", "i");
+const MANAGED_PASSWORD_CHANGE_FAILED = new RE2(
+ "\\bauthentication\\s+failure\\b|\\bsorry\\b|\\bunknown\\s+user\\b|\\buser\\s+not\\s+known\\b|\\bdoes\\s+not\\s+exist\\b|\\bunchanged\\b",
+ "i"
+);
+const SELF_PASSWORD_CHANGE_FAILED = new RE2("\\berror\\b|\\bfail(?:ed|ure|s)?\\b|\\bunchanged\\b", "i");
+const SU_LOGIN_FAILED = new RE2("\\bauthentication\\s+failure\\b|\\bincorrect\\s+password\\b|\\bsu:", "i");
+
+export type TInteractiveShellStream = {
+ on(event: "data", listener: (chunk: Buffer) => void): void;
+ on(event: "close", listener: () => void): void;
+ on(event: "error", listener: (err: Error) => void): void;
+ write(data: string): void;
+ end(): void;
+};
+
+const escapeForPattern = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+
+const lineAt = (text: string, index: number) => {
+ const start = text.lastIndexOf("\n", index) + 1;
+ const end = text.indexOf("\n", index);
+ return (end === -1 ? text.slice(start) : text.slice(start, end)).trim();
+};
+
+// The transcript is interpolated into rotation errors, which are persisted and rendered in the UI,
+// so bounding and redaction live here: no individual error site can forget to apply them.
+const createTranscript = (secrets: (string | undefined)[]) => {
+ const knownSecrets = secrets.filter((secret): secret is string => Boolean(secret));
+ const redact = (value: string) =>
+ knownSecrets.reduce((redacted, secret) => redacted.replaceAll(secret, "***"), value);
+
+ let text = "";
+ let truncated = false;
+
+ return {
+ append: (chunk: string) => {
+ text += chunk;
+ if (text.length > MAX_TRANSCRIPT_SIZE) {
+ text = text.slice(-MAX_TRANSCRIPT_SIZE);
+ truncated = true;
+ }
+ },
+ redact,
+ read: () => (truncated ? `...${redact(text)}` : redact(text))
+ };
+};
// Execute a command via SSH exec with a PTY (no login shell, no MOTD)
// Returns a stream that can be used for interactive I/O
@@ -42,24 +98,24 @@ const execCommandWithPty = (client: Client, command: string): Promise<ClientChan
});
};
-// Change password for managed rotation (admin changing another user's password)
-// Uses `sudo passwd <username>` (or `passwd <username>`) executed via PTY
-// LC_ALL=C forces English prompts regardless of system locale
-const changeManagedPassword = async (
- client: Client,
- targetUsername: string,
+// Drives the prompts of `passwd <username>` for managed rotation (admin changing another user's
+// password). Prompts are matched against everything received so far, not just the arriving chunk:
+// a PTY behind an SSH channel and a gateway tunnel re-segments freely, so a prompt can straddle
+// two data events.
+export const runManagedPasswordChange = (
+ stream: TInteractiveShellStream,
newPassword: string,
- useSudo: boolean = false,
appConnectionPassword?: string
): Promise<void> => {
- const command = useSudo ? `LC_ALL=C sudo passwd ${targetUsername}` : `LC_ALL=C passwd ${targetUsername}`;
- const stream = await execCommandWithPty(client, command);
-
return new Promise((resolve, reject) => {
- let output = "";
+ const transcript = createTranscript([newPassword, appConnectionPassword]);
+ const decoder = new StringDecoder("utf8");
+
+ let pending = "";
let step = 0;
let completed = false;
let settled = false;
+ let closing = false;
let errorMessage = "";
const safeReject = (error: Error) => {
@@ -72,60 +128,114 @@ const changeManagedPassword = async (
const timeout = setTimeout(() => {
if (!settled) {
stream.end();
- safeReject(new Error(`Password change timed out. Output: ${output}`));
+ safeReject(new Error(`Password change timed out. Output: ${transcript.read()}`));
}
}, SHELL_TIMEOUT);
- stream.on("data", (data: Buffer) => {
- if (settled) return;
+ const finish = () => {
+ closing = true;
+ clearTimeout(timeout);
+ stream.end();
+ };
- const text = data.toString();
- output += text;
- const lower = text.toLowerCase();
+ // Matched text is dropped so the same bytes cannot satisfy a later step as well, which would
+ // send the new password a third time or read the first prompt as its own confirmation.
+ const consume = (match: RegExpExecArray) => {
+ pending = pending.slice(match.index + match[0].length);
+ };
- if (step === 0 && lower.includes("[sudo]")) {
- // sudo is asking for the logged-in user's password
- if (!appConnectionPassword) {
- clearTimeout(timeout);
- safeReject(
- new Error(
- "sudo is requesting a password but the app connection uses SSH key authentication. Configure the app connection with password authentication, or configure NOPASSWD in sudoers for this user."
- )
- );
- stream.end();
- return;
+ const advance = (): boolean => {
+ const failure = MANAGED_PASSWORD_CHANGE_FAILED.exec(pending);
+ if (failure) {
+ errorMessage = transcript.redact(lineAt(pending, failure.index));
+ consume(failure);
+ finish();
+ return false;
+ }
+
+ if (step === 0) {
+ const sudoPrompt = SUDO_PROMPT.exec(pending);
+ if (sudoPrompt) {
+ if (!appConnectionPassword) {
+ clearTimeout(timeout);
+ safeReject(
+ new Error(
+ "sudo is requesting a password but the app connection uses SSH key authentication. Configure the app connection with password authentication, or configure NOPASSWD in sudoers for this user."
+ )
+ );
+ stream.end();
+ return false;
+ }
+ consume(sudoPrompt);
+ stream.write(`${appConnectionPassword}\n`);
+ // Still step 0: the new-password prompt follows, and may already be in this buffer.
+ return true;
}
- stream.write(`${appConnectionPassword}\n`);
- // stay at step 0 to catch "New password" next
- } else if (step === 0 && lower.includes("new password")) {
- stream.write(`${newPassword}\n`);
- step = 1;
- } else if (
- step === 1 &&
- (lower.includes("retype") || lower.includes("again") || lower.includes("new password"))
- ) {
- stream.write(`${newPassword}\n`);
- step = 2;
- } else if (step >= 2 && (lower.includes("success") || lower.includes("updated") || lower.includes("changed"))) {
+
+ const newPasswordPrompt = NEW_PASSWORD_PROMPT.exec(pending);
+ if (newPasswordPrompt) {
+ consume(newPasswordPrompt);
+ stream.write(`${newPassword}\n`);
+ step = 1;
+ return true;
+ }
+
+ return false;
+ }
+
+ if (step === 1) {
+ const confirmPrompt = CONFIRM_PASSWORD_PROMPT.exec(pending);
+ if (confirmPrompt) {
+ consume(confirmPrompt);
+ stream.write(`${newPassword}\n`);
+ step = 2;
+ return true;
+ }
+
+ return false;
+ }
+
+ const success = PASSWORD_CHANGE_SUCCEEDED.exec(pending);
+ if (success) {
+ consume(success);
completed = true;
+ finish();
+ }
+
+ return false;
+ };
+
+ stream.on("data", (chunk: Buffer) => {
+ if (settled || closing) return;
+
+ const text = decoder.write(chunk);
+ if (!text) return;
+
+ transcript.append(text);
+ pending += text;
+
+ // A host can coalesce several prompts into one chunk, and once it is waiting on our answer no
+ // further data event arrives, so advance until nothing more matches instead of once per event.
+ let progressed = true;
+ while (progressed && !settled && !closing) {
+ progressed = advance();
+ }
+
+ if (!settled && !closing && pending.length > MAX_BUFFER_SIZE) {
clearTimeout(timeout);
stream.end();
- } else if (
- step >= 0 &&
- (lower.includes("authentication failure") ||
- lower.includes("sorry") ||
- lower.includes("unknown user") ||
- lower.includes("user not known") ||
- lower.includes("does not exist"))
- ) {
- errorMessage = text.trim();
- clearTimeout(timeout);
- stream.end();
+ safeReject(
+ new Error(
+ `Password change failed: the host sent more than ${MAX_BUFFER_SIZE / 1024} KB of output without a recognized prompt. Output: ${transcript.read()}`
+ )
+ );
}
});
stream.on("close", () => {
clearTimeout(timeout);
+ const tail = decoder.end();
+ if (tail) transcript.append(tail);
if (settled) return;
settled = true;
@@ -134,7 +244,7 @@ const changeManagedPassword = async (
} else if (completed || step >= 2) {
resolve();
} else {
- reject(new Error(`Password change incomplete (step ${step}). Output: ${output}`));
+ reject(new Error(`Password change incomplete (step ${step}). Output: ${transcript.read()}`));
}
});
@@ -145,17 +255,38 @@ const changeManagedPassword = async (
});
};
-// Change password for self rotation (user changing their own password)
-// Uses `passwd` executed via PTY to handle interactive prompts
+// Change password for managed rotation (admin changing another user's password)
+// Uses `sudo passwd <username>` (or `passwd <username>`) executed via PTY
// LC_ALL=C forces English prompts regardless of system locale
-const changeSelfPassword = async (client: Client, oldPassword: string, newPassword: string): Promise<void> => {
- const stream = await execCommandWithPty(client, "LC_ALL=C passwd");
+const changeManagedPassword = async (
+ client: Client,
+ targetUsername: string,
+ newPassword: string,
+ useSudo: boolean = false,
+ appConnectionPassword?: string
+): Promise<void> => {
+ const command = useSudo ? `LC_ALL=C sudo passwd ${targetUsername}` : `LC_ALL=C passwd ${targetUsername}`;
+ const stream = await execCommandWithPty(client, command);
+
+ return runManagedPasswordChange(stream, newPassword, appConnectionPassword);
+};
+// Drives the prompts of `passwd` for self rotation (user changing their own password), matching
+// against everything received so far for the same reason as the managed handler.
+export const runSelfPasswordChange = (
+ stream: TInteractiveShellStream,
+ oldPassword: string,
+ newPassword: string
+): Promise<void> => {
return new Promise((resolve, reject) => {
- let output = "";
+ const transcript = createTranscript([oldPassword, newPassword]);
+ const decoder = new StringDecoder("utf8");
+
+ let pending = "";
let step = 0;
let completed = false;
let settled = false;
+ let closing = false;
let errorMessage = "";
const safeReject = (error: Error) => {
@@ -168,48 +299,106 @@ const changeSelfPassword = async (client: Client, oldPassword: string, newPasswo
const timeout = setTimeout(() => {
if (!settled) {
stream.end();
- safeReject(new Error(`Password change timed out. Output: ${output}`));
+ safeReject(new Error(`Password change timed out. Output: ${transcript.read()}`));
}
}, SHELL_TIMEOUT);
- stream.on("data", (data: Buffer) => {
- if (settled) return;
+ const finish = () => {
+ closing = true;
+ clearTimeout(timeout);
+ stream.end();
+ };
- const text = data.toString();
- output += text;
- const lower = text.toLowerCase();
-
- // Handle passwd prompts step by step
- if (step === 0 && lower.includes("password")) {
- // Current/old password prompt (could be "Current password:", "Old password:", etc.)
- stream.write(`${oldPassword}\n`);
- step = 1;
- } else if (step === 1 && lower.includes("new password")) {
- // New password prompt
- stream.write(`${newPassword}\n`);
- step = 2;
- } else if (
- step === 2 &&
- (lower.includes("retype") || lower.includes("again") || lower.includes("new password"))
- ) {
- // Confirm new password prompt
- stream.write(`${newPassword}\n`);
- step = 3;
- } else if (step === 3 && (lower.includes("success") || lower.includes("updated") || lower.includes("changed"))) {
- // Password changed successfully
+ const consume = (match: RegExpExecArray) => {
+ pending = pending.slice(match.index + match[0].length);
+ };
+
+ const advance = (): boolean => {
+ if (step >= 1) {
+ const failure = SELF_PASSWORD_CHANGE_FAILED.exec(pending);
+ if (failure) {
+ errorMessage = transcript.redact(lineAt(pending, failure.index));
+ consume(failure);
+ finish();
+ return false;
+ }
+ }
+
+ if (step === 0) {
+ const currentPasswordPrompt = ANY_PASSWORD_PROMPT.exec(pending);
+ if (currentPasswordPrompt) {
+ consume(currentPasswordPrompt);
+ stream.write(`${oldPassword}\n`);
+ step = 1;
+ return true;
+ }
+
+ return false;
+ }
+
+ if (step === 1) {
+ const newPasswordPrompt = NEW_PASSWORD_PROMPT.exec(pending);
+ if (newPasswordPrompt) {
+ consume(newPasswordPrompt);
+ stream.write(`${newPassword}\n`);
+ step = 2;
+ return true;
+ }
+
+ return false;
+ }
+
+ if (step === 2) {
+ const confirmPrompt = CONFIRM_PASSWORD_PROMPT.exec(pending);
+ if (confirmPrompt) {
+ consume(confirmPrompt);
+ stream.write(`${newPassword}\n`);
+ step = 3;
+ return true;
+ }
+
+ return false;
+ }
+
+ const success = PASSWORD_CHANGE_SUCCEEDED.exec(pending);
+ if (success) {
+ consume(success);
completed = true;
+ finish();
+ }
+
+ return false;
+ };
+
+ stream.on("data", (chunk: Buffer) => {
+ if (settled || closing) return;
+
+ const text = decoder.write(chunk);
+ if (!text) return;
+
+ transcript.append(text);
+ pending += text;
+
+ let progressed = true;
+ while (progressed && !settled && !closing) {
+ progressed = advance();
+ }
+
+ if (!settled && !closing && pending.length > MAX_BUFFER_SIZE) {
clearTimeout(timeout);
stream.end();
- } else if (step >= 1 && (lower.includes("error") || lower.includes("fail") || lower.includes("unchanged"))) {
- // Password change failed
- errorMessage = text.trim();
- clearTimeout(timeout);
- stream.end();
+ safeReject(
+ new Error(
+ `Password change failed: the host sent more than ${MAX_BUFFER_SIZE / 1024} KB of output without a recognized prompt. Output: ${transcript.read()}`
+ )
+ );
}
});
stream.on("close", () => {
clearTimeout(timeout);
+ const tail = decoder.end();
+ if (tail) transcript.append(tail);
if (settled) return;
settled = true;
@@ -218,7 +407,7 @@ const changeSelfPassword = async (client: Client, oldPassword: string, newPasswo
} else if (completed || step >= 3) {
resolve();
} else {
- reject(new Error(`Password change incomplete (step ${step}). Output: ${output}`));
+ reject(new Error(`Password change incomplete (step ${step}). Output: ${transcript.read()}`));
}
});
@@ -229,17 +418,32 @@ const changeSelfPassword = async (client: Client, oldPassword: string, newPasswo
});
};
-// Verify credentials by using `su - <username>` via an existing SSH connection
-// Used as fallback when direct SSH login is not allowed for the target account
+// Change password for self rotation (user changing their own password)
+// Uses `passwd` executed via PTY to handle interactive prompts
// LC_ALL=C forces English prompts regardless of system locale
-const verifySuLogin = async (client: Client, targetUsername: string, targetPassword: string): Promise<void> => {
- const stream = await execCommandWithPty(client, `LC_ALL=C su - ${targetUsername}`);
+const changeSelfPassword = async (client: Client, oldPassword: string, newPassword: string): Promise<void> => {
+ const stream = await execCommandWithPty(client, "LC_ALL=C passwd");
+
+ return runSelfPasswordChange(stream, oldPassword, newPassword);
+};
+// Drives the prompts of `su - <username>`, matching against everything received so far for the same
+// reason as the password handlers.
+export const runSuLoginVerification = (
+ stream: TInteractiveShellStream,
+ targetUsername: string,
+ targetPassword: string
+): Promise<void> => {
return new Promise((resolve, reject) => {
- let output = "";
+ const transcript = createTranscript([targetPassword]);
+ const decoder = new StringDecoder("utf8");
+ const whoamiReply = new RE2(escapeForPattern(targetUsername), "i");
+
+ let pending = "";
let step = 0;
let completed = false;
let settled = false;
+ let closing = false;
const safeReject = (error: Error) => {
if (!settled) {
@@ -251,49 +455,100 @@ const verifySuLogin = async (client: Client, targetUsername: string, targetPassw
const timeout = setTimeout(() => {
if (!settled) {
stream.end();
- safeReject(new Error(`su verification timed out. Output: ${output}`));
+ safeReject(new Error(`su verification timed out. Output: ${transcript.read()}`));
}
}, SHELL_TIMEOUT);
- stream.on("data", (data: Buffer) => {
- if (settled) return;
+ const finish = () => {
+ closing = true;
+ clearTimeout(timeout);
+ stream.end();
+ };
- const text = data.toString();
- output += text;
- const lower = text.toLowerCase();
+ const consume = (match: RegExpExecArray) => {
+ pending = pending.slice(match.index + match[0].length);
+ };
- if (step === 0 && lower.includes("password")) {
- // su is asking for the target user's password
- stream.write(`${targetPassword}\n`);
- step = 1;
- } else if (step === 1) {
- if (lower.includes("authentication failure") || lower.includes("incorrect password") || lower.includes("su:")) {
+ const advance = (): boolean => {
+ if (step >= 1) {
+ const failure = SU_LOGIN_FAILED.exec(pending);
+ if (failure) {
+ const diagnostic = transcript.redact(lineAt(pending, failure.index));
+ consume(failure);
clearTimeout(timeout);
- safeReject(new Error(`su authentication failed for user ${targetUsername}. Output: ${text.trim()}`));
+ safeReject(new Error(`su authentication failed for user ${targetUsername}. Output: ${diagnostic}`));
stream.end();
- return;
+ return false;
}
- // After successful su, run whoami
+ }
+
+ if (step === 0) {
+ const passwordPrompt = ANY_PASSWORD_PROMPT.exec(pending);
+ if (passwordPrompt) {
+ consume(passwordPrompt);
+ stream.write(`${targetPassword}\n`);
+ step = 1;
+ return true;
+ }
+
+ return false;
+ }
+
+ if (step === 1) {
+ // Anything buffered here is su's own banner or shell prompt; only the reply to whoami names
+ // the user we ended up as, so it is dropped rather than sliced.
+ if (!pending.trim()) return false;
+ pending = "";
stream.write("whoami\n");
step = 2;
- } else if (step === 2 && lower.includes(targetUsername.toLowerCase())) {
- // whoami confirmed we are the target user
+ return true;
+ }
+
+ if (whoamiReply.test(pending)) {
completed = true;
- clearTimeout(timeout);
stream.write("exit\n");
+ finish();
+ }
+
+ return false;
+ };
+
+ stream.on("data", (chunk: Buffer) => {
+ if (settled || closing) return;
+
+ const text = decoder.write(chunk);
+ if (!text) return;
+
+ transcript.append(text);
+ pending += text;
+
+ let progressed = true;
+ while (progressed && !settled && !closing) {
+ progressed = advance();
+ }
+
+ if (!settled && !closing && pending.length > MAX_BUFFER_SIZE) {
+ clearTimeout(timeout);
stream.end();
+ safeReject(
+ new Error(
+ `su verification failed for user ${targetUsername}: the host sent more than ${MAX_BUFFER_SIZE / 1024} KB of output without a recognized prompt. Output: ${transcript.read()}`
+ )
+ );
}
});
stream.on("close", () => {
clearTimeout(timeout);
+ const tail = decoder.end();
+ if (tail) transcript.append(tail);
if (settled) return;
settled = true;
if (completed) {
resolve();
} else {
- reject(new Error(`su verification failed for user ${targetUsername}. Output: ${output}`));
+ reject(new Error(`su verification failed for user ${targetUsername}. Output: ${transcript.read()}`));
}
});
@@ -304,6 +559,15 @@ const verifySuLogin = async (client: Client, targetUsername: string, targetPassw
});
};
+// Verify credentials by using `su - <username>` via an existing SSH connection
+// Used as fallback when direct SSH login is not allowed for the target account
+// LC_ALL=C forces English prompts regardless of system locale
+const verifySuLogin = async (client: Client, targetUsername: string, targetPassword: string): Promise<void> => {
+ const stream = await execCommandWithPty(client, `LC_ALL=C su - ${targetUsername}`);
+
+ return runSuLoginVerification(stream, targetUsername, targetPassword);
+};
+
export const unixLinuxLocalAccountRotationFactory: TRotationFactory<
TUnixLinuxLocalAccountRotationWithConnection,
TUnixLinuxLocalAccountRotationGeneratedCredentials,