Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
refactor: enhance Windows local account rotation schemas to prevent password rotation for privileged accounts and improve password validation
Victor Santos49e0ec4cbda9
diff --git a/backend/src/ee/services/secret-rotation-v2/windows-local-account-rotation/windows-local-account-rotation-schemas.ts b/backend/src/ee/services/secret-rotation-v2/windows-local-account-rotation/windows-local-account-rotation-schemas.tsindex dd11e6b153..cb6b0e22c6 100644--- a/backend/src/ee/services/secret-rotation-v2/windows-local-account-rotation/windows-local-account-rotation-schemas.ts+++ b/backend/src/ee/services/secret-rotation-v2/windows-local-account-rotation/windows-local-account-rotation-schemas.ts@@ -11,6 +11,7 @@ import { SecretRotations } from "@app/lib/api-docs";import {containsDangerousSmbChars,SMB_VALIDATION_LIMITS,+ validateSmbPassword,validateWindowsUsername} from "@app/lib/validator/validate-smb";import { SecretNameSchema } from "@app/server/lib/schemas";@@ -43,6 +44,9 @@ const WindowsPasswordRequirementsSchema = PasswordRequirementsSchema.refine(});+// Built-in Windows accounts that should never have their passwords rotated+const WINDOWS_PRIVILEGED_ACCOUNTS = ["administrator", "system", "guest", "defaultaccount"];+const WindowsLocalAccountRotationParametersSchema = z.object({username: z.string()@@ -58,6 +62,9 @@ const WindowsLocalAccountRotationParametersSchema = z.object({.refine((val) => !val.startsWith("-") && !val.startsWith(".") && !val.endsWith("."), {message: "Username cannot start with a hyphen or period, and cannot end with a period"})+ .refine((val) => !WINDOWS_PRIVILEGED_ACCOUNTS.includes(val.toLowerCase()), {+ message: "Cannot rotate passwords for privileged system accounts (Administrator, SYSTEM, Guest, DefaultAccount)"+ }).describe(SecretRotations.PARAMETERS.WINDOWS_LOCAL_ACCOUNT.username),passwordRequirements: WindowsPasswordRequirementsSchema.optional(),rotationMethod: z@@ -92,7 +99,13 @@ export const CreateWindowsLocalAccountRotationSchema = BaseCreateSecretRotationSsecretsMapping: WindowsLocalAccountRotationSecretsMappingSchema,temporaryParameters: z.object({- password: z.string().optional().describe(SecretRotations.PARAMETERS.WINDOWS_LOCAL_ACCOUNT.password)+ password: z+ .string()+ .refine((val) => !val || validateSmbPassword(val), {+ message: "Password cannot contain dangerous characters: ; | & ` $ ( ) or newlines"+ })+ .optional()+ .describe(SecretRotations.PARAMETERS.WINDOWS_LOCAL_ACCOUNT.password)}).optional()})diff --git a/backend/src/lib/smb-rpc/smb-rpc-client.ts b/backend/src/lib/smb-rpc/smb-rpc-client.tsindex 869f1b7c3a..79c4824a14 100644--- a/backend/src/lib/smb-rpc/smb-rpc-client.ts+++ b/backend/src/lib/smb-rpc/smb-rpc-client.ts@@ -1,10 +1,6 @@import { spawn } from "child_process";-import * as fs from "fs";-import * as os from "os";-import * as path from "path";import RE2 from "re2";-import { logger } from "@app/lib/logger";import {SMB_VALIDATION_LIMITS,validateDomain,@@ -123,29 +119,28 @@ const buildPortArgs = (config: SmbRpcConfig): string[] => {};/**- * Create a temporary authentication file for Samba tools- * Format: username = value, password = value, domain = value (optional)- * Returns the file path+ * Build authentication args for SMB commands using --user and --workgroup flags+ * Password is passed via PASSWD environment variable*/-const createAuthFile = (config: SmbRpcConfig): string => {- const authFilePath = path.join(os.tmpdir(), `smb-auth-${Date.now()}-${Math.random().toString(36).slice(2)}`);+const buildAuthArgs = (config: SmbRpcConfig): string[] => {+ const args = [`--user=${config.adminUser}`, ...SMB3_SECURITY_OPTIONS];- let content = `username = ${config.adminUser}\npassword = ${config.adminPassword}\n`;if (config.domain) {- content += `domain = ${config.domain}\n`;+ args.push(`--workgroup=${config.domain}`);}- // Write with restrictive permissions (owner read/write only)- fs.writeFileSync(authFilePath, content, { mode: 0o600 });-- return authFilePath;+ return args;};/**- * Helper to build common auth args for SMB commands using authentication file+ * Build environment variables for SMB commands+ * Password is passed via PASSWD environment variable to avoid command-line exposure*/-const buildAuthArgs = (authFilePath: string): string[] => {- return ["-A", authFilePath, ...SMB3_SECURITY_OPTIONS];+const buildAuthEnv = (config: SmbRpcConfig): NodeJS.ProcessEnv => {+ return {+ ...process.env,+ PASSWD: config.adminPassword+ };};/**@@ -153,11 +148,13 @@ const buildAuthArgs = (authFilePath: string): string[] => {*/const executeCommand = (command: string,- args: string[]+ args: string[],+ env?: NodeJS.ProcessEnv): Promise<{ stdout: string; stderr: string; exitCode: number }> => {return new Promise((resolve) => {const proc = spawn(command, args, {- stdio: ["pipe", "pipe", "pipe"]+ stdio: ["pipe", "pipe", "pipe"],+ env});let stdout = "";@@ -223,28 +220,19 @@ const testSmbConnection = async (config: SmbRpcConfig): Promise<void> => {// Validate all inputs before use to prevent command injectionvalidateConfig(config);- const authFilePath = createAuthFile(config);-- try {- const args = ["-L", buildTarget(config), ...buildPortArgs(config), ...buildAuthArgs(authFilePath)];+ const args = ["-L", buildTarget(config), ...buildPortArgs(config), ...buildAuthArgs(config)];+ const env = buildAuthEnv(config);- const { stdout, stderr, exitCode } = await executeCommand("smbclient", args);- const combinedOutput = stdout + stderr;+ const { stdout, stderr, exitCode } = await executeCommand("smbclient", args, env);+ const combinedOutput = stdout + stderr;- const ntStatus = parseNtStatusError(combinedOutput);- if (ntStatus) {- throw new Error(getNtStatusMessage(ntStatus));- }+ const ntStatus = parseNtStatusError(combinedOutput);+ if (ntStatus) {+ throw new Error(getNtStatusMessage(ntStatus));+ }- if (exitCode !== 0) {- throw new Error(`SMB connection failed: ${combinedOutput || "Unknown error"}`);- }- } finally {- try {- fs.unlinkSync(authFilePath);- } catch (err) {- logger.warn({ err, authFilePath }, "Failed to cleanup SMB auth file");- }+ if (exitCode !== 0) {+ throw new Error(`SMB connection failed: ${combinedOutput || "Unknown error"}`);}};@@ -292,31 +280,22 @@ export const changeWindowsPassword = async ();}- const authFilePath = createAuthFile(config);-- try {- const escapedPassword = escapePasswordForRpc(newPassword);- const rpcCommand = `setuserinfo2 ${targetUser} 23 '${escapedPassword}'`;+ const escapedPassword = escapePasswordForRpc(newPassword);+ const rpcCommand = `setuserinfo2 ${targetUser} 23 '${escapedPassword}'`;- const args = [buildTarget(config), ...buildPortArgs(config), ...buildAuthArgs(authFilePath), "-c", rpcCommand];+ const args = [buildTarget(config), ...buildPortArgs(config), ...buildAuthArgs(config), "-c", rpcCommand];+ const env = buildAuthEnv(config);- const { stdout, stderr, exitCode } = await executeCommand("rpcclient", args);- const combinedOutput = stdout + stderr;+ const { stdout, stderr, exitCode } = await executeCommand("rpcclient", args, env);+ const combinedOutput = stdout + stderr;- const ntStatus = parseNtStatusError(combinedOutput);- if (ntStatus) {- throw new Error(getNtStatusMessage(ntStatus));- }+ const ntStatus = parseNtStatusError(combinedOutput);+ if (ntStatus) {+ throw new Error(getNtStatusMessage(ntStatus));+ }- if (exitCode !== 0) {- throw new Error(`Password change failed: ${combinedOutput || "Unknown error"}`);- }- } finally {- try {- fs.unlinkSync(authFilePath);- } catch (err) {- logger.warn({ err, authFilePath }, "Failed to cleanup SMB auth file");- }+ if (exitCode !== 0) {+ throw new Error(`Password change failed: ${combinedOutput || "Unknown error"}`);}};diff --git a/docs/documentation/platform/secret-rotation/windows-local-account.mdx b/docs/documentation/platform/secret-rotation/windows-local-account.mdxindex 6a15aca445..53957ecd99 100644--- a/docs/documentation/platform/secret-rotation/windows-local-account.mdx+++ b/docs/documentation/platform/secret-rotation/windows-local-account.mdx@@ -16,6 +16,20 @@ description: "Learn how to automatically rotate Windows local account passwords- Create a [Windows Connection](/integrations/app-connections/windows) with administrator credentials- Ensure your network security policies allow SMB connections from Infisical to this rotation provider+<Accordion title="Open firewall on Windows Defender for SMB connection">+ Run the following PowerShell command as Administrator on the Windows server to allow inbound SMB connections:++ ```powershell+ New-NetFirewallRule -DisplayName "Allow SMB Inbound" -Direction Inbound -Protocol TCP -LocalPort 445 -Action Allow+ ```++ To verify the rule was created:++ ```powershell+ Get-NetFirewallRule -DisplayName "Allow SMB Inbound"+ ```+</Accordion>+## Create a Windows Local Account Rotation in Infisical<Tabs>diff --git a/docs/integrations/app-connections/windows.mdx b/docs/integrations/app-connections/windows.mdxindex f820aea6a3..211a0f7f74 100644--- a/docs/integrations/app-connections/windows.mdx+++ b/docs/integrations/app-connections/windows.mdx@@ -20,6 +20,20 @@ You will need the following information to establish a Windows connection:- **SMB3 Support** - This connection uses SMB3 with encryption enabled for secure communication with Windows servers.- **Firewall Configuration** - The server must be accessible from Infisical or from the Infisical Gateway if using it.+<Accordion title="Open firewall on Windows Defender for SMB connection">+ Run the following PowerShell command as Administrator on the Windows server to allow inbound SMB connections:++ ```powershell+ New-NetFirewallRule -DisplayName "Allow SMB Inbound" -Direction Inbound -Protocol TCP -LocalPort 445 -Action Allow+ ```++ To verify the rule was created:++ ```powershell+ Get-NetFirewallRule -DisplayName "Allow SMB Inbound"+ ```+</Accordion>+## Setup Windows Connection in Infisical<Tabs>diff --git a/frontend/src/components/secret-rotations-v2/forms/schemas/windows-local-account-rotation-schema.ts b/frontend/src/components/secret-rotations-v2/forms/schemas/windows-local-account-rotation-schema.tsindex 59f83ff89d..388542eeef 100644--- a/frontend/src/components/secret-rotations-v2/forms/schemas/windows-local-account-rotation-schema.ts+++ b/frontend/src/components/secret-rotations-v2/forms/schemas/windows-local-account-rotation-schema.ts@@ -5,11 +5,15 @@ import { PasswordRequirementsSchema } from "@app/components/secret-rotations-v2/import {containsDangerousSmbChars,SMB_USERNAME_REGEX,- SMB_VALIDATION_LIMITS+ SMB_VALIDATION_LIMITS,+ validateSmbPassword} from "@app/helpers/smb";import { SecretRotation } from "@app/hooks/api/secretRotationsV2";import { WindowsLocalAccountRotationMethod } from "@app/hooks/api/secretRotationsV2/types/windows-local-account-rotation";+// Built-in Windows accounts that should never have their passwords rotated+const WINDOWS_PRIVILEGED_ACCOUNTS = ["administrator", "system", "guest", "defaultaccount"];+// Windows-specific password requirements schema that filters dangerous characters from allowedSymbolsconst WindowsPasswordRequirementsSchema = PasswordRequirementsSchema.refine((data) => {@@ -40,6 +44,10 @@ export const WindowsLocalAccountRotationSchema = z}).refine((val) => !val.startsWith("-") && !val.startsWith(".") && !val.endsWith("."), {message: "Username cannot start with a hyphen or period, and cannot end with a period"+ })+ .refine((val) => !WINDOWS_PRIVILEGED_ACCOUNTS.includes(val.toLowerCase()), {+ message:+ "Cannot rotate passwords for privileged system accounts (Administrator, SYSTEM, Guest, DefaultAccount)"}),passwordRequirements: WindowsPasswordRequirementsSchema.optional(),rotationMethod: z.nativeEnum(WindowsLocalAccountRotationMethod).optional()@@ -50,7 +58,12 @@ export const WindowsLocalAccountRotationSchema = z}),temporaryParameters: z.object({- password: z.string().optional()+ password: z+ .string()+ .refine((val) => !val || validateSmbPassword(val), {+ message: "Password cannot contain the following characters: ; | & ` $ ( ) or newlines"+ })+ .optional()}).optional()})