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 validation for Windows local account and SMB connection schemas to prevent command injection and improve security
Victor Santosbb867262f5ca
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 f74f052170..d220f94ad6 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@@ -8,6 +8,7 @@ import {} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-schemas";import { PasswordRequirementsSchema } from "@app/ee/services/secret-rotation-v2/shared/general";import { SecretRotations } from "@app/lib/api-docs";+import { CharacterType, characterValidator } from "@app/lib/validator/validate-string";import { SecretNameSchema } from "@app/server/lib/schemas";import { AppConnection } from "@app/services/app-connection/app-connection-enums";@@ -25,12 +26,6 @@ export const WindowsLocalAccountRotationGeneratedCredentialsSchema = z.min(1).max(2);-// Windows local account username validation:-// - Must start with alphanumeric, underscore, or hyphen (not a period)-// - Can contain alphanumeric, underscore, hyphen, and period-// - Max 20 characters for local accounts-const WINDOWS_USERNAME_REGEX = /^[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$/;-const WindowsLocalAccountRotationParametersSchema = z.object({username: z.string()@@ -38,9 +33,21 @@ const WindowsLocalAccountRotationParametersSchema = z.object({.min(1, "Username required").max(20, "Username too long - Windows local accounts are limited to 20 characters").refine(- (val) => WINDOWS_USERNAME_REGEX.test(val),- "Username must start with a letter, number, underscore, or hyphen, and can only contain alphanumeric characters, underscores, hyphens, and periods"+ (val) =>+ characterValidator([+ CharacterType.AlphaNumeric,+ CharacterType.Hyphen,+ CharacterType.Underscore,+ CharacterType.Period+ ])(val),+ "Username can only contain alphanumeric characters, underscores, hyphens, and periods")+ .refine((val) => !val.startsWith("."), {+ message: "Username cannot start with a period"+ })+ .refine((val) => !val.startsWith("-"), {+ message: "Username cannot start with a hyphen"+ }).describe(SecretRotations.PARAMETERS.WINDOWS_LOCAL_ACCOUNT.username),passwordRequirements: PasswordRequirementsSchema.optional(),rotationMethod: zdiff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 4e66f6a69f..2b02db341b 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -2938,14 +2938,14 @@ export const SecretRotations = {UNIX_LINUX_LOCAL_ACCOUNT: {username: "The username of the Unix/Linux user account to rotate the password for.",rotationMethod:- 'Whether the rotation should be performed using "login-as-target" (the target user\'s own credentials) or "login-as-root" (the SSH connection\'s admin credentials). Defaults to "login-as-root".',+ 'Whether the rotation should be performed using "login-as-target" (the target user\'s own credentials) or "login-as-root" (the SSH connection\'s admin credentials). Defaults to "login-as-target".',password:'The current password of the target user. Required if "parameters.rotationMethod" is set to "login-as-target".'},WINDOWS_LOCAL_ACCOUNT: {username: "The username of the Windows user account to rotate the password for.",rotationMethod:- 'Whether the rotation should be performed using "login-as-target" (the target user\'s own credentials) or "login-as-root" (the SSH connection\'s admin credentials). Defaults to "login-as-root".',+ 'Whether the rotation should be performed using "login-as-target" (the target user\'s own credentials) or "login-as-root" (the SSH connection\'s admin credentials). Defaults to "login-as-target".',password:'The current password of the target user. Required if "parameters.rotationMethod" is set to "login-as-target".'},diff --git a/backend/src/lib/smb-rpc/smb-rpc-client.ts b/backend/src/lib/smb-rpc/smb-rpc-client.tsindex 31e69b662c..7209a3a334 100644--- a/backend/src/lib/smb-rpc/smb-rpc-client.ts+++ b/backend/src/lib/smb-rpc/smb-rpc-client.ts@@ -5,6 +5,7 @@ import * as path from "path";import RE2 from "re2";import { logger } from "@app/lib/logger";+import { CharacterType, characterValidator } from "@app/lib/validator/validate-string";export interface SmbRpcConfig {host: string;@@ -16,6 +17,128 @@ export interface SmbRpcConfig {const SMB3_SECURITY_OPTIONS = ["--option=client min protocol=SMB3", "--option=client smb encrypt=required"];+// Validation functions using RE2-based characterValidator for security (prevents ReDoS attacks)+const validateHostname = characterValidator([CharacterType.AlphaNumeric, CharacterType.Period, CharacterType.Hyphen]);++const validateDomain = characterValidator([+ CharacterType.AlphaNumeric,+ CharacterType.Period,+ CharacterType.Hyphen,+ CharacterType.Underscore+]);++const validateUsername = characterValidator([+ CharacterType.AlphaNumeric,+ CharacterType.Hyphen,+ CharacterType.Underscore,+ CharacterType.Period+]);++const MAX_USERNAME_LENGTH = 20;+const MAX_ADMIN_USERNAME_LENGTH = 104;+const MAX_HOST_LENGTH = 253;+const MAX_DOMAIN_LENGTH = 255;++// Dangerous characters that could enable command/RPC injection+// These are blocked to prevent:+// - Command separators: ; | &+// - Command substitution: ` $ ( )+// - Newlines: \n \r (auth file directive injection)+// - Null bytes: \0 (string termination attacks)+const DANGEROUS_PASSWORD_CHARS = [";", "|", "&", "`", "$", "(", ")", "\n", "\r", "\0"];++/**+ * Validate host to prevent command injection+ */+const validateHost = (host: string): void => {+ if (!host || host.length === 0) {+ throw new Error("Host is required");+ }+ if (host.length > MAX_HOST_LENGTH) {+ throw new Error("Host too long");+ }+ if (!validateHostname(host)) {+ throw new Error("Host can only contain alphanumeric characters, dots, and hyphens");+ }+ if (host.startsWith("-")) {+ throw new Error("Host cannot start with a hyphen");+ }+ if (host.startsWith(".")) {+ throw new Error("Host cannot start with a period");+ }+};++/**+ * Validate domain to prevent command injection+ */+const validateDomainInput = (domain: string | undefined): void => {+ if (!domain) return;++ if (domain.length > MAX_DOMAIN_LENGTH) {+ throw new Error("Domain too long");+ }+ if (!validateDomain(domain)) {+ throw new Error("Domain can only contain alphanumeric characters, dots, hyphens, and underscores");+ }+ if (domain.startsWith("-")) {+ throw new Error("Domain cannot start with a hyphen");+ }+};++/**+ * Validate port is a safe integer+ */+const validatePort = (port: number): void => {+ if (!Number.isInteger(port) || port < 1 || port > 65535) {+ throw new Error("Port must be a valid integer between 1 and 65535");+ }+};++/**+ * Validate admin username to prevent command injection+ */+const validateAdminUsername = (username: string): void => {+ if (!username || username.length === 0) {+ throw new Error("Admin username is required");+ }+ if (username.length > MAX_ADMIN_USERNAME_LENGTH) {+ throw new Error("Admin username too long");+ }+ if (!validateUsername(username)) {+ throw new Error("Admin username can only contain alphanumeric characters, underscores, hyphens, and periods");+ }+ if (username.startsWith("-")) {+ throw new Error("Admin username cannot start with a hyphen");+ }+ if (username.startsWith(".")) {+ throw new Error("Admin username cannot start with a period");+ }+};++/**+ * Validate password doesn't contain characters that could enable command/RPC injection+ */+const validatePassword = (password: string): void => {+ if (!password || password.length === 0) {+ throw new Error("Password is required");+ }+ // Disallow dangerous characters that could enable injection attacks+ if (DANGEROUS_PASSWORD_CHARS.some((char) => password.includes(char))) {+ throw new Error("Password cannot contain dangerous characters: ; | & ` $ ( ) or newlines");+ }+};++/**+ * Validate all config inputs before use+ */+const validateConfig = (config: SmbRpcConfig): void => {+ validateHost(config.host);+ validatePort(config.port);+ validateAdminUsername(config.adminUser);+ validatePassword(config.adminPassword);+ validateDomainInput(config.domain);+};+/*** Build the target string (//host)*/@@ -128,6 +251,9 @@ const getNtStatusMessage = (ntStatus: string): string => {* Uses smbclient to list shares and verify connectivity*/const testSmbConnection = async (config: SmbRpcConfig): Promise<void> => {+ // Validate all inputs before use to prevent command injection+ validateConfig(config);+const authFilePath = createAuthFile(config);try {@@ -162,19 +288,21 @@ const escapePasswordForRpc = (password: string): string => {};/**+ * Validate that a target username contains only safe characters to prevent command injection* Windows local account username validation:- * - Must start with alphanumeric, underscore, or hyphen (not a period)+ * - Cannot start with a period or hyphen (prevents flag injection and Windows rules)* - Can contain alphanumeric, underscore, hyphen, and period* - Max 20 characters for local accounts*/-const WINDOWS_USERNAME_REGEX = /^[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$/;-const MAX_USERNAME_LENGTH = 20;--/**- * Validate that a username contains only safe characters to prevent command injection- */export const isValidWindowsUsername = (username: string): boolean => {- return WINDOWS_USERNAME_REGEX.test(username) && username.length > 0 && username.length <= MAX_USERNAME_LENGTH;+ if (!username || username.length === 0 || username.length > MAX_USERNAME_LENGTH) {+ return false;+ }+ // Cannot start with period or hyphen (period is Windows rule, hyphen prevents flag injection)+ if (username.startsWith(".") || username.startsWith("-")) {+ return false;+ }+ return validateUsername(username);};/**@@ -186,9 +314,11 @@ export const changeWindowsPassword = async (targetUser: string,newPassword: string): Promise<void> => {+ validateConfig(config);+if (!isValidWindowsUsername(targetUser)) {throw new Error(- "Invalid username format - only alphanumeric characters, underscores, hyphens, and periods allowed"+ "Invalid username format - must be 1-20 characters, only alphanumeric characters, underscores, hyphens, and periods allowed, and cannot start with a period or hyphen");}diff --git a/backend/src/services/app-connection/smb/smb-connection-schemas.ts b/backend/src/services/app-connection/smb/smb-connection-schemas.tsindex 286b17e0cc..30adbac564 100644--- a/backend/src/services/app-connection/smb/smb-connection-schemas.ts+++ b/backend/src/services/app-connection/smb/smb-connection-schemas.ts@@ -1,6 +1,7 @@import { z } from "zod";import { AppConnections } from "@app/lib/api-docs";+import { CharacterType, characterValidator } from "@app/lib/validator/validate-string";import { AppConnection } from "@app/services/app-connection/app-connection-enums";import {BaseAppConnectionSchema,@@ -11,12 +12,91 @@ import {import { APP_CONNECTION_NAME_MAP } from "../app-connection-maps";import { SmbConnectionMethod } from "./smb-connection-enums";+// Hostname validation: alphanumeric, dots, hyphens (cannot start with hyphen)+// Supports: hostnames (server.domain.com), IPv4 (192.168.1.1)+const validateHostname = characterValidator([CharacterType.AlphaNumeric, CharacterType.Period, CharacterType.Hyphen]);++// Domain validation: alphanumeric, dots, hyphens, underscores (cannot start with hyphen)+const validateDomain = characterValidator([+ CharacterType.AlphaNumeric,+ CharacterType.Period,+ CharacterType.Hyphen,+ CharacterType.Underscore+]);++// Username validation for SMB admin user+// Windows usernames: alphanumeric, underscores, hyphens, periods (cannot start with period or hyphen)+const validateSmbUsername = characterValidator([+ CharacterType.AlphaNumeric,+ CharacterType.Hyphen,+ CharacterType.Underscore,+ CharacterType.Period+]);++// Dangerous characters that could enable command/RPC injection+// These are blocked to prevent:+// - Command separators: ; | &+// - Command substitution: ` $ ( )+// - Newlines: \n \r (auth file directive injection)+// - Null bytes: \0 (string termination attacks)+const DANGEROUS_PASSWORD_CHARS = [";", "|", "&", "`", "$", "(", ")", "\n", "\r", "\0"];++const validateSmbPassword = (password: string): boolean => {+ return !DANGEROUS_PASSWORD_CHARS.some((char) => password.includes(char));+};+export const SmbConnectionCredentialsSchema = z.object({- host: z.string().trim().min(1, "Host required").describe(AppConnections.CREDENTIALS.SMB.host),+ host: z+ .string()+ .trim()+ .min(1, "Host required")+ .max(253, "Host too long")+ .refine((val) => validateHostname(val), {+ message: "Host can only contain alphanumeric characters, dots, and hyphens"+ })+ .refine((val) => !val.startsWith("-"), {+ message: "Host cannot start with a hyphen"+ })+ .refine((val) => !val.startsWith("."), {+ message: "Host cannot start with a period"+ })+ .describe(AppConnections.CREDENTIALS.SMB.host),port: z.coerce.number().int().min(1).max(65535).describe(AppConnections.CREDENTIALS.SMB.port),- domain: z.string().trim().optional().describe(AppConnections.CREDENTIALS.SMB.domain),- username: z.string().trim().min(1, "Username required").describe(AppConnections.CREDENTIALS.SMB.username),- password: z.string().trim().min(1, "Password required").describe(AppConnections.CREDENTIALS.SMB.password)+ domain: z+ .string()+ .trim()+ .max(255, "Domain too long")+ .refine((val) => val === "" || validateDomain(val), {+ message: "Domain can only contain alphanumeric characters, dots, hyphens, and underscores"+ })+ .refine((val) => val === "" || !val.startsWith("-"), {+ message: "Domain cannot start with a hyphen"+ })+ .optional()+ .describe(AppConnections.CREDENTIALS.SMB.domain),+ username: z+ .string()+ .trim()+ .min(1, "Username required")+ .max(104, "Username too long")+ .refine((val) => validateSmbUsername(val), {+ message: "Username can only contain alphanumeric characters, underscores, hyphens, and periods"+ })+ .refine((val) => !val.startsWith("-"), {+ message: "Username cannot start with a hyphen"+ })+ .refine((val) => !val.startsWith("."), {+ message: "Username cannot start with a period"+ })+ .describe(AppConnections.CREDENTIALS.SMB.username),+ password: z+ .string()+ .trim()+ .min(1, "Password required")+ .refine((val) => validateSmbPassword(val), {+ message: "Password cannot contain the following characters: ; | & ` $ ( ) or newlines"+ })+ .describe(AppConnections.CREDENTIALS.SMB.password)});// Validation schema for credentialsdiff --git a/docs/documentation/platform/secret-rotation/windows-local-account.mdx b/docs/documentation/platform/secret-rotation/windows-local-account.mdxindex faa920a3c9..5edf156b9b 100644--- a/docs/documentation/platform/secret-rotation/windows-local-account.mdx+++ b/docs/documentation/platform/secret-rotation/windows-local-account.mdx@@ -43,7 +43,7 @@ description: "Learn how to automatically rotate Windows local account passwords- **Rotation Method** - The method to use when rotating the target user's password.- **Login as Target** - Infisical will use the target user's current credentials to authenticate and rotate its own password.- - **Login as Root** - Infisical will use the Windows Connection's administrator credentials to rotate the target user's password.+ - **Login as Root** - Infisical will use the administrator credentials provided in the Windows App Connection to rotate the target user's password.- **Username** - The target Windows username whose password will be rotated.- **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.