Skip to content

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

fix(secret-rotation): clear AIX ADMCHG flag after unix local account rotation

DimitrisStaratzis3190f996ab67
diff --git a/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/pty-expect-engine.ts b/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/pty-expect-engine.ts
index 9c8a0aaa87..8616a2e74f 100644
--- a/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/pty-expect-engine.ts
+++ b/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/pty-expect-engine.ts
@@ -8,6 +8,7 @@ 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;
+ on(event: "exit", listener: (code: number | null) => void): void;
write(data: string): void;
end(): void;
};
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
index b8988b1b28..f73852c2b4 100644
--- 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
@@ -1,6 +1,8 @@
import { describe, expect, test } from "vitest";
import {
+ parseAixPasswordFlags,
+ runAdminCommand,
runManagedPasswordChange,
runSelfPasswordChange,
runSuLoginVerification,
@@ -18,6 +20,7 @@ type TFakeStream = {
writes: string[];
feed: (text: string) => void;
feedBytes: (chunk: Buffer) => void;
+ exit: (code: number) => void;
close: () => void;
};
@@ -25,11 +28,13 @@ const createFakeStream = (): TFakeStream => {
const writes: string[] = [];
const dataListeners: ((chunk: Buffer) => void)[] = [];
const closeListeners: (() => void)[] = [];
+ const exitListeners: ((code: number | null) => 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);
+ if (event === "exit") exitListeners.push(listener as (code: number | null) => void);
},
write: (data: string) => {
writes.push(data);
@@ -44,6 +49,7 @@ const createFakeStream = (): TFakeStream => {
writes,
feed: (text: string) => feedBytes(Buffer.from(text, "utf8")),
feedBytes,
+ exit: (code: number) => exitListeners.forEach((listener) => listener(code)),
close: () => closeListeners.forEach((listener) => listener())
};
};
@@ -316,3 +322,115 @@ describe("runSuLoginVerification", () => {
expect((error as Error).message).not.toContain(ROTATED_SENTINEL);
});
});
+
+describe("runAdminCommand", () => {
+ // `lssec -f /etc/security/passwd -s svc -a flags` over a PTY, after sudo asked for a password.
+ const SUDO_LSSEC_TRANSCRIPT = "[sudo] password for svc: \r\nsvc flags=ADMCHG,ADMIN\r\n";
+
+ test("answers the sudo prompt once and returns the output and exit code", async () => {
+ const fake = createFakeStream();
+ const result = runAdminCommand(fake.stream, SUDO_SENTINEL);
+
+ fake.feed(SUDO_LSSEC_TRANSCRIPT);
+ fake.exit(0);
+ fake.close();
+
+ await expect(result).resolves.toEqual({ output: SUDO_LSSEC_TRANSCRIPT, exitCode: 0 });
+ expect(fake.writes).toEqual([`${SUDO_SENTINEL}\n`]);
+ });
+
+ test("answers a sudo prompt split across data events exactly once", async () => {
+ const runs = everySplitOf(SUDO_LSSEC_TRANSCRIPT).map(({ offset, chunks }) => {
+ const fake = createFakeStream();
+ const result = runAdminCommand(fake.stream, SUDO_SENTINEL);
+ chunks.forEach((chunk) => fake.feed(chunk));
+ fake.exit(0);
+ fake.close();
+ return { offset, result, writes: fake.writes };
+ });
+
+ await Promise.all(runs.map(({ result }) => expect(result).resolves.toMatchObject({ exitCode: 0 })));
+
+ runs.forEach(({ offset, writes }) => {
+ expect(writes, `split at offset ${offset}`).toEqual([`${SUDO_SENTINEL}\n`]);
+ });
+ });
+
+ test("returns a non-zero exit code when the command fails instead of rejecting", async () => {
+ const fake = createFakeStream();
+ const result = runAdminCommand(fake.stream);
+
+ fake.feed("sudo: a password is required\r\n");
+ fake.exit(1);
+ fake.close();
+
+ await expect(result).resolves.toEqual({ output: "sudo: a password is required\r\n", exitCode: 1 });
+ expect(fake.writes).toEqual([]);
+ });
+
+ test("reports a null exit code when the host never sends one", async () => {
+ const fake = createFakeStream();
+ const result = runAdminCommand(fake.stream);
+
+ fake.feed("svc flags=\r\n");
+ fake.close();
+
+ await expect(result).resolves.toEqual({ output: "svc flags=\r\n", exitCode: null });
+ });
+
+ test("rejects with sudoers guidance when sudo asks for a password we do not have", async () => {
+ const fake = createFakeStream();
+ const result = runAdminCommand(fake.stream);
+
+ fake.feed("[sudo] password for svc: ");
+
+ await expect(result).rejects.toThrow(/NOPASSWD in sudoers/);
+ expect(fake.writes).toEqual([]);
+ });
+
+ test("rejects when sudo prompts a second time rather than resending the password", async () => {
+ const fake = createFakeStream();
+ const result = runAdminCommand(fake.stream, SUDO_SENTINEL);
+
+ fake.feed("[sudo] password for svc: \r\nSorry, try again.\r\n[sudo] password for svc: ");
+
+ await expect(result).rejects.toThrow(/sudo rejected the app connection password/);
+ expect(fake.writes).toEqual([`${SUDO_SENTINEL}\n`]);
+ });
+
+ test("redacts the app connection password from the returned output", async () => {
+ const fake = createFakeStream();
+ const result = runAdminCommand(fake.stream, SUDO_SENTINEL);
+
+ fake.feed(`[sudo] password for svc: ${SUDO_SENTINEL}\r\nsvc flags=ADMCHG\r\n`);
+ fake.exit(0);
+ fake.close();
+
+ const { output } = await result;
+
+ expect(output).not.toContain(SUDO_SENTINEL);
+ expect(output).toContain("svc flags=ADMCHG");
+ });
+});
+
+describe("parseAixPasswordFlags", () => {
+ test.each([
+ ["svc flags=ADMCHG\r\n", ["ADMCHG"]],
+ ["svc flags=ADMCHG,ADMIN\r\n", ["ADMCHG", "ADMIN"]],
+ ["svc flags=ADMIN, NOCHECK\r\n", ["ADMIN", "NOCHECK"]],
+ ["svc flags=\r\n", []],
+ ["[sudo] password for svc: \r\nsvc flags=ADMCHG\r\n", ["ADMCHG"]]
+ ])("parses %j", (output, expected) => {
+ expect(parseAixPasswordFlags(output)).toEqual(expected);
+ });
+
+ test("rejects flag values that are not plain flag names", () => {
+ expect(parseAixPasswordFlags("svc flags=ADMIN;reboot\r\n")).toBeUndefined();
+ expect(parseAixPasswordFlags("svc flags=ADMIN,$(id)\r\n")).toBeUndefined();
+ });
+
+ test("returns undefined when lssec printed an error instead of the flags", () => {
+ expect(parseAixPasswordFlags('3004-704 Cannot open file "/etc/security/passwd".\r\n')).toBeUndefined();
+ expect(parseAixPasswordFlags("")).toBeUndefined();
+ });
+});
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 be92be8ff0..9e2ce6a78e 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
@@ -12,6 +12,7 @@ import {
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import {
+ execOverSshClient,
executeWithPotentialGateway,
getSshConnectionClient,
SshConnectionMethod,
@@ -25,6 +26,7 @@ import {
lineAt,
MAX_BUFFER_SIZE,
runExpectSession,
+ SHELL_TIMEOUT,
TInteractiveShellStream
} from "./pty-expect-engine";
import { UnixLinuxLocalAccountRotationMethod } from "./unix-linux-local-account-rotation-schemas";
@@ -66,6 +68,14 @@ const MANAGED_PASSWORD_CHANGE_FAILED = new RE2(
);
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");
+const AIX_PASSWORD_FLAGS = new RE2("flags=([^\\r\\n]*)");
+const AIX_PASSWORD_FLAG_NAME = new RE2("^[A-Za-z0-9_]+$");
+
+const SUDO_PASSWORD_REQUIRED_MESSAGE =
+ "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.";
+
+const AIX_SECURITY_PASSWD_FILE = "/etc/security/passwd";
+const AIX_ADMCHG_FLAG = "ADMCHG";
const passwdOverflowMessage = (t: string) =>
`Password change failed: the host sent more than ${MAX_BUFFER_SIZE / 1024} KB of output without a recognized prompt. Output: ${t}`;
@@ -110,11 +120,7 @@ export const runManagedPasswordChange = (
const sudoPrompt = SUDO_PROMPT.exec(ctx.unmatched);
if (sudoPrompt) {
if (!appConnectionPassword) {
- ctx.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."
- )
- );
+ ctx.safeReject(new Error(SUDO_PASSWORD_REQUIRED_MESSAGE));
return false;
}
ctx.consume(sudoPrompt);
@@ -188,6 +194,158 @@ const changeManagedPassword = async (
return runManagedPasswordChange(stream, newPassword, appConnectionPassword);
};
+export type TAdminCommandResult = { output: string; exitCode: number | null };
+
+export const runAdminCommand = (
+ stream: TInteractiveShellStream,
+ appConnectionPassword?: string
+): Promise<TAdminCommandResult> => {
+ let exitCode: number | null = null;
+ let output = "";
+ let sudoAnswered = false;
+
+ stream.on("exit", (code) => {
+ exitCode = code;
+ });
+
+ return runExpectSession({
+ stream,
+ secrets: [appConnectionPassword],
+
+ advance: (ctx) => {
+ const sudoPrompt = SUDO_PROMPT.exec(ctx.unmatched);
+ if (!sudoPrompt) return false;
+
+ if (!appConnectionPassword) {
+ ctx.safeReject(new Error(SUDO_PASSWORD_REQUIRED_MESSAGE));
+ return false;
+ }
+ if (sudoAnswered) {
+ ctx.safeReject(new Error("sudo rejected the app connection password."));
+ return false;
+ }
+
+ ctx.consume(sudoPrompt);
+ ctx.write(`${appConnectionPassword}\n`);
+ sudoAnswered = true;
+ return true;
+ },
+
+ resolveOnClose: (ctx) => {
+ output = ctx.transcript.read();
+ return { resolve: true };
+ },
+
+ overflowMessage: (t) =>
+ `Command failed: the host sent more than ${MAX_BUFFER_SIZE / 1024} KB of output without finishing. Output: ${t}`,
+ timeoutMessage: (t) => `Command timed out. Output: ${t}`
+ }).then(() => ({ output, exitCode }));
+};
+
+export const parseAixPasswordFlags = (lssecOutput: string): string[] | undefined => {
+ const match = AIX_PASSWORD_FLAGS.exec(lssecOutput);
+ if (!match) return undefined;
+
+ const flags = match[1]
+ .split(",")
+ .map((flag) => flag.trim())
+ .filter(Boolean);
+
+ // The flags are written back into a shell command, so anything but a plain flag name is rejected.
+ return flags.every((flag) => AIX_PASSWORD_FLAG_NAME.test(flag)) ? flags : undefined;
+};
+
+const isAixHost = async (client: Client): Promise<boolean> => {
+ try {
+ const { stdout, stderr, exitCode } = await execOverSshClient(client, "uname -s", SHELL_TIMEOUT);
+ if (exitCode !== 0) {
+ logger.warn(
+ `Unix/Linux Local Account Rotation: \`uname -s\` exited with code ${exitCode}, assuming a non-AIX host. Output: ${stderr.trim() || stdout.trim()}`
+ );
+ return false;
+ }
+ return stdout.trim() === "AIX";
+ } catch (error) {
+ logger.warn(error, "Unix/Linux Local Account Rotation: `uname -s` failed, assuming a non-AIX host");
+ return false;
+ }
+};
+
+type TAixFlagContext = {
+ client: Client;
+ targetUsername: string;
+ useSudo: boolean;
+ appConnectionPassword?: string;
+};
+
+const runAixSecurityCommand = async (
+ { client, useSudo, appConnectionPassword }: TAixFlagContext,
+ command: string
+): Promise<TAdminCommandResult> => {
+ const prefix = useSudo ? "LC_ALL=C sudo" : "LC_ALL=C";
+ return runAdminCommand(await execCommandWithPty(client, `${prefix} ${command}`), appConnectionPassword);
+};
+
+const readAixPasswordFlags = async (ctx: TAixFlagContext): Promise<{ flags?: string[]; output: string }> => {
+ const { output, exitCode } = await runAixSecurityCommand(
+ ctx,
+ `lssec -f ${AIX_SECURITY_PASSWD_FILE} -s ${ctx.targetUsername} -a flags`
+ );
+ return { flags: exitCode === 0 ? parseAixPasswordFlags(output) : undefined, output };
+};
+
+const writeAixPasswordFlags = async (
+ ctx: TAixFlagContext,
+ flags: string[]
+): Promise<{ succeeded: boolean; output: string }> => {
+ const { output, exitCode } = await runAixSecurityCommand(
+ ctx,
+ `chsec -f ${AIX_SECURITY_PASSWD_FILE} -s ${ctx.targetUsername} -a flags=${flags.join(",")}`
+ );
+ return { succeeded: exitCode === 0, output };
+};
+
+const aixSudoHint = (ctx: TAixFlagContext) =>
+ ctx.useSudo ? " If sudo is restricted, allow lssec and chsec in sudoers for the app connection user." : "";
+
+// Rewriting the flags unchanged proves lssec and chsec both work before the password changes. A
+// failure after passwd would leave a password nobody knows, since Infisical only stores it once
+// the rotation succeeds.
+const ensureAixPasswordFlagsWritable = async (ctx: TAixFlagContext): Promise<void> => {
+ const { flags, output: readOutput } = await readAixPasswordFlags(ctx);
+ if (!flags) {
+ throw new Error(
+ `Could not read the AIX password flags for user '${ctx.targetUsername}', so the password was not changed. Infisical must clear the ${AIX_ADMCHG_FLAG} flag that AIX sets on every password an administrator changes.${aixSudoHint(ctx)} Output: ${readOutput}`
+ );
+ }
+
+ const { succeeded, output: writeOutput } = await writeAixPasswordFlags(ctx, flags);
+ if (!succeeded) {
+ throw new Error(
+ `Could not update the AIX password flags for user '${ctx.targetUsername}', so the password was not changed. Infisical must clear the ${AIX_ADMCHG_FLAG} flag that AIX sets on every password an administrator changes.${aixSudoHint(ctx)} Output: ${writeOutput}`
+ );
+ }
+};
+
+// AIX adds ADMCHG to the account's flags whenever root or the security group sets its password,
+// forcing a password change at next login. Login-only verification cannot see the flag because
+// OpenSSH on AIX applies the forced change only once a session starts, so a non-interactive
+// `ssh host command` fails with "Password change required but no TTY available".
+const clearAixAdminChangeFlag = async (ctx: TAixFlagContext): Promise<void> => {
+ const failureMessage = (output: string) =>
+ `Password was changed but clearing the AIX ${AIX_ADMCHG_FLAG} flag for user '${ctx.targetUsername}' failed, so the account will be forced to change its password at next login. Reconcile the rotation to set a new password.${aixSudoHint(ctx)} Output: ${output}`;
+
+ const { flags, output: readOutput } = await readAixPasswordFlags(ctx);
+ if (!flags) throw new Error(failureMessage(readOutput));
+ if (!flags.includes(AIX_ADMCHG_FLAG)) return;
+
+ const { succeeded, output: writeOutput } = await writeAixPasswordFlags(
+ ctx,
+ flags.filter((flag) => flag !== AIX_ADMCHG_FLAG)
+ );
+ if (!succeeded) throw new Error(failureMessage(writeOutput));
+};
+
export const runSelfPasswordChange = (
stream: TInteractiveShellStream,
oldPassword: string,
@@ -508,7 +666,14 @@ export const unixLinuxLocalAccountRotationFactory: TRotationFactory<
conn.method === SshConnectionMethod.Password
? (conn.credentials as { password: string }).password
: undefined;
+ const aixFlagContext = (await isAixHost(client))
+ ? { client, targetUsername: username, useSudo: shouldUseSudo, appConnectionPassword }
+ : undefined;
+ if (aixFlagContext) await ensureAixPasswordFlagsWritable(aixFlagContext);
+
await changeManagedPassword(client, username, newPassword, shouldUseSudo, appConnectionPassword);
+
+ if (aixFlagContext) await clearAixAdminChangeFlag(aixFlagContext);
}
} finally {
client.destroy();
diff --git a/backend/src/services/app-connection/ssh/ssh-connection-fns.ts b/backend/src/services/app-connection/ssh/ssh-connection-fns.ts
index f53c7222ae..87f67ab76c 100644
--- a/backend/src/services/app-connection/ssh/ssh-connection-fns.ts
+++ b/backend/src/services/app-connection/ssh/ssh-connection-fns.ts
@@ -356,7 +356,7 @@ export const executeSshCommandViaGateway = async (
const MAX_SSH_COMMAND_OUTPUT_BYTES = 16 * 1024 * 1024;
-const execOverSshClient = (client: Client, command: string, timeoutMs: number): Promise<SshExecResult> =>
+export const execOverSshClient = (client: Client, command: string, timeoutMs: number): Promise<SshExecResult> =>
new Promise((resolve, reject) => {
let settled = false;
let timer: NodeJS.Timeout;
diff --git a/docs/documentation/platform/secret-rotation/unix-linux-local-account.mdx b/docs/documentation/platform/secret-rotation/unix-linux-local-account.mdx
index 37adfed6c2..2a17727205 100644
--- a/docs/documentation/platform/secret-rotation/unix-linux-local-account.mdx
+++ b/docs/documentation/platform/secret-rotation/unix-linux-local-account.mdx
@@ -46,6 +46,9 @@ description: "Learn how to automatically rotate Unix/Linux local account passwor
- **Login as Root** - Infisical will use the SSH Connection's credentials to log in and rotate the provided user's password.
- **Username** - The target SSH username whose password will be rotated.
- **Use Sudo** - If true, uses sudo when executing the password rotation command. Defaults to false.
+ <Note>
+ If the target host runs AIX and **Rotation Method** is **Login as Root**, Infisical also clears the `ADMCHG` flag that AIX sets on every password an administrator changes. Without this, the account is forced to pick a new password at its next login, and non-interactive SSH logins fail. If **Use Sudo** is on, the SSH Connection's user must be allowed to run `passwd`, `lssec`, and `chsec` through sudo.
+ </Note>
- **Current Password** - The current password of the target user (required when **Rotation Method** is set to **Login as Target**).
- **Password Requirements** - The constraints to apply when generating new passwords.