Skip to content

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

address final veria reviews

x40f7e43c7850
diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts
index e2f2593977..4ca6cf2e3b 100644
--- a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts
+++ b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts
@@ -234,7 +234,7 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({
});
};
- const scan = async (): Promise<TDiscoveryScanResult> => {
+ const scan = async (signal: AbortSignal): Promise<TDiscoveryScanResult> => {
const domain = connectionDetails.domain.toLowerCase();
const baseDN = buildDomainDN(connectionDetails.domain);
const machineErrors: TDiscoveryMachineError[] = [];
@@ -302,6 +302,7 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({
};
for (const computer of computers) {
+ if (signal.aborted) break;
const host = computer.resolvedIp || computer.dNSHostName || computer.cn;
const hostLabel = computer.cn || computer.dNSHostName || host;
try {
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts b/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
index 387694f8fa..ed922220aa 100644
--- a/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
@@ -19,7 +19,8 @@ export const sshExecWithGateway = async (
gatewayV2Service: TGatewayDep,
command: string,
credentials: SshExecCredentials,
- timeoutMs: number
+ timeoutMs: number,
+ signal?: AbortSignal
): Promise<string> => {
const [host] = await verifyHostInputValidity({ host: targetHost, isGateway: true, isDynamicSecret: false });
const platform = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
@@ -31,7 +32,7 @@ export const sshExecWithGateway = async (
return withGatewayV2Proxy(
async (proxyPort) => {
- const response = await callSshExec({ port: proxyPort, command, credentials, timeoutMs });
+ const response = await callSshExec({ port: proxyPort, command, credentials, timeoutMs, signal });
if (!response.ok) throw new Error(response.errorMessage);
return response.result.stdout;
},
@@ -74,7 +75,8 @@ export const sweepReachableTargets = async (
targets: { host: string; port: number }[],
gatewayId: string,
gatewayV2Service: TGatewayDep,
- dialTimeoutMs: number
+ dialTimeoutMs: number,
+ signal?: AbortSignal
): Promise<Set<string>> => {
if (!targets.length) return new Set();
@@ -94,7 +96,8 @@ export const sweepReachableTargets = async (
port: proxyPort,
targets: hostPorts,
dialTimeoutMs,
- responseTimeoutMs: SWEEP_RESPONSE_TIMEOUT_MS
+ responseTimeoutMs: SWEEP_RESPONSE_TIMEOUT_MS,
+ signal
}),
{
protocol: GatewayProxyProtocol.Discovery,
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts b/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts
index cff3366342..bcd22e8d85 100644
--- a/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts
@@ -1,3 +1,5 @@
+import pLimit from "p-limit";
+
import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
@@ -75,10 +77,14 @@ type TPamDiscoverySourceServiceFactoryDep = {
// hard ceiling on how long a single scan may run
const MAX_SCAN_DURATION_MS = 45 * 60 * 1000;
-const withScanTimeout = async <T>(scan: Promise<T>, timeoutMs: number): Promise<T> => {
+// bound concurrent discovered-account upserts so a large result set can't exhaust the DB connection pool
+const DISCOVERED_UPSERT_CONCURRENCY = 8;
+
+const withScanTimeout = async <T>(scan: Promise<T>, controller: AbortController, timeoutMs: number): Promise<T> => {
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(() => {
+ controller.abort();
reject(
new BadRequestError({
message: `Scan exceeded the maximum duration of ${Math.round(timeoutMs / 60000)} minutes`
@@ -90,7 +96,8 @@ const withScanTimeout = async <T>(scan: Promise<T>, timeoutMs: number): Promise<
return await Promise.race([scan, timeout]);
} finally {
if (timer) clearTimeout(timer);
- scan.catch(() => {}); // swallow late rejection if the scan settles after the timeout fires
+ // wait for the aborted scan to actually stop before finalizing the run
+ await scan.catch(() => {});
}
};
@@ -212,6 +219,24 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
if (account.accountType !== expectedType) {
throw new BadRequestError({ message: `Credential account must be of type '${expectedType}'` });
}
+
+ // discovery transmits an SSH password to every scanned host, so a password account may only be used by an actor
+ // allowed to view its secret
+ if (account.accountType === PamAccountType.SSH) {
+ const { decryptor } = await getProjectCipher(projectId);
+ const { authMethod } = decryptToObject(account.encryptedCredentials, decryptor) as { authMethod?: string };
+ if (authMethod === PamSshAuthMethod.Password) {
+ await checkAccountAccess(
+ permissionService,
+ credentialAccountId,
+ account.folderId,
+ projectId,
+ ResourcePermissionPamResourceActions.ViewCredentials,
+ ctx
+ );
+ }
+ }
+
return account;
};
@@ -421,14 +446,22 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
gatewayV2Service
});
- const { accounts, machineErrors } = await withScanTimeout(provider.scan(), MAX_SCAN_DURATION_MS);
+ const controller = new AbortController();
+ const { accounts, machineErrors } = await withScanTimeout(
+ provider.scan(controller.signal),
+ controller,
+ MAX_SCAN_DURATION_MS
+ );
+ const upsertLimit = pLimit(DISCOVERED_UPSERT_CONCURRENCY);
const results = await Promise.all(
accounts.map((d) =>
- pamDiscoveredAccountDAL.upsertByFingerprint(sourceId, d.fingerprint, {
- accountType: d.accountType,
- name: d.name,
- encryptedDetails: encryptor({ plainText: Buffer.from(JSON.stringify(d.details)) }).cipherTextBlob
- })
+ upsertLimit(() =>
+ pamDiscoveredAccountDAL.upsertByFingerprint(sourceId, d.fingerprint, {
+ accountType: d.accountType,
+ name: d.name,
+ encryptedDetails: encryptor({ plainText: Buffer.from(JSON.stringify(d.details)) }).cipherTextBlob
+ })
+ )
)
);
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-types.ts b/backend/src/ee/services/pam-discovery/pam-discovery-types.ts
index 9320a8a3e4..1bddd6c515 100644
--- a/backend/src/ee/services/pam-discovery/pam-discovery-types.ts
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-types.ts
@@ -20,7 +20,7 @@ export type TDiscoveryScanResult = {
export type TPamDiscoveryProvider = {
validateConnection: () => Promise<void>;
- scan: () => Promise<TDiscoveryScanResult>;
+ scan: (signal: AbortSignal) => Promise<TDiscoveryScanResult>;
};
export type TDiscoveryCredentialAccount = {
diff --git a/backend/src/ee/services/pam-discovery/unix/unix-discovery-factory.ts b/backend/src/ee/services/pam-discovery/unix/unix-discovery-factory.ts
index ca3032bd90..2271b3d223 100644
--- a/backend/src/ee/services/pam-discovery/unix/unix-discovery-factory.ts
+++ b/backend/src/ee/services/pam-discovery/unix/unix-discovery-factory.ts
@@ -21,6 +21,9 @@ const SSH_EXEC_TIMEOUT_MS = 20 * 1000;
const SCAN_CONCURRENCY = 64;
const SWEEP_DIAL_TIMEOUT_MS = 3 * 1000;
const MAX_SWEEP_TARGETS = 65536;
+const MAX_ACCOUNTS_PER_HOST = 2000;
+const MAX_ACCOUNTS_PER_SCAN = 50000;
+const MAX_USERNAME_LENGTH = 64;
const PASSWD_MARKER = "__INFISICAL_PASSWD__";
const DEFAULT_UID_MIN = 1000;
const DEFAULT_UID_MAX = 60000;
@@ -97,8 +100,9 @@ const parseUnixUsernames = (output: string, includeSystemAccounts: boolean): str
const usernames = new Set<string>();
for (const line of passwdPart.split("\n")) {
+ if (usernames.size >= MAX_ACCOUNTS_PER_HOST) break;
const [name, , uidStr, , , , shell = ""] = line.trim().split(":");
- if (name) {
+ if (name && name.length <= MAX_USERNAME_LENGTH) {
if (name === "root" || includeSystemAccounts || isLoginAccount(name, uidStr, shell, uidMin, uidMax)) {
usernames.add(name);
}
@@ -122,7 +126,7 @@ export const unixDiscoveryFactory: TPamDiscoveryFactory = ({
...accounts.filter((a) => a.host !== host)
];
- const enumerateHost = (host: string, account: TUnixAccount) =>
+ const enumerateHost = (host: string, account: TUnixAccount, signal?: AbortSignal) =>
sshExecWithGateway(
host,
account.port,
@@ -130,13 +134,16 @@ export const unixDiscoveryFactory: TPamDiscoveryFactory = ({
gatewayV2Service,
ENUMERATION_COMMAND,
account.credentials,
- SSH_EXEC_TIMEOUT_MS
+ SSH_EXEC_TIMEOUT_MS,
+ signal
);
const scanHost = async (
host: string,
- open: Set<string>
+ open: Set<string>,
+ signal: AbortSignal
): Promise<{ accounts: TDiscoveredAccount[]; error?: TDiscoveryMachineError }> => {
+ if (signal.aborted) return { accounts: [] };
const isKnownHost = accounts.some((a) => a.host === host);
const candidates = orderAccountsForHost(host).filter(
(account) => isUsableAccount(account) && (isKnownHost || open.has(`${host}:${account.port}`))
@@ -146,7 +153,7 @@ export const unixDiscoveryFactory: TPamDiscoveryFactory = ({
for (const account of candidates) {
try {
// eslint-disable-next-line no-await-in-loop
- const output = await enumerateHost(host, account);
+ const output = await enumerateHost(host, account, signal);
return {
accounts: parseUnixUsernames(output, config.includeSystemAccounts ?? false).map((username) => ({
accountType: PamAccountType.SSH,
@@ -184,7 +191,7 @@ export const unixDiscoveryFactory: TPamDiscoveryFactory = ({
});
};
- const scan = async (): Promise<TDiscoveryScanResult> => {
+ const scan = async (signal: AbortSignal): Promise<TDiscoveryScanResult> => {
if (!accounts.some(isUsableAccount)) {
throw new BadRequestError({
message: "No credential account has usable authentication (password, private key, or certificate)"
@@ -200,7 +207,7 @@ export const unixDiscoveryFactory: TPamDiscoveryFactory = ({
message: `Scan expands to ${sweepTargets.length} host-port combinations, exceeding the limit of ${MAX_SWEEP_TARGETS}. Reduce the target ranges or the number of distinct credential ports.`
});
}
- const open = await sweepReachableTargets(sweepTargets, gatewayId, gatewayV2Service, SWEEP_DIAL_TIMEOUT_MS);
+ const open = await sweepReachableTargets(sweepTargets, gatewayId, gatewayV2Service, SWEEP_DIAL_TIMEOUT_MS, signal);
const hostsToScan = targets.filter(
(host) => accounts.some((a) => a.host === host) || usablePorts.some((port) => open.has(`${host}:${port}`))
@@ -214,10 +221,17 @@ export const unixDiscoveryFactory: TPamDiscoveryFactory = ({
}
const limit = pLimit(SCAN_CONCURRENCY);
- const results = await Promise.all(hostsToScan.map((host) => limit(() => scanHost(host, open))));
+ const results = await Promise.all(hostsToScan.map((host) => limit(() => scanHost(host, open, signal))));
+
+ const discovered = results.flatMap((r) => r.accounts);
+ if (discovered.length > MAX_ACCOUNTS_PER_SCAN) {
+ logger.warn(
+ `PAM Unix discovery truncating discovered accounts to the per-scan limit [found=${discovered.length}] [limit=${MAX_ACCOUNTS_PER_SCAN}]`
+ );
+ }
return {
- accounts: results.flatMap((r) => r.accounts),
+ accounts: discovered.slice(0, MAX_ACCOUNTS_PER_SCAN),
machineErrors: results.flatMap((r) => (r.error ? [r.error] : []))
};
};
diff --git a/backend/src/lib/gateway-v2/ssh-rpc.ts b/backend/src/lib/gateway-v2/ssh-rpc.ts
index 85d9cbcb5e..04ed7b6155 100644
--- a/backend/src/lib/gateway-v2/ssh-rpc.ts
+++ b/backend/src/lib/gateway-v2/ssh-rpc.ts
@@ -27,6 +27,7 @@ export const callSshExec = (args: {
command: string;
credentials: SshExecCredentials;
timeoutMs: number;
+ signal?: AbortSignal;
}): Promise<SshExecResponse> => {
const payload = JSON.stringify({ command: args.command, ...args.credentials, timeoutMs: args.timeoutMs });
return new Promise<SshExecResponse>((resolve, reject) => {
@@ -41,7 +42,8 @@ export const callSshExec = (args: {
"Content-Length": Buffer.byteLength(payload).toString(),
Connection: "close"
},
- timeout: SSH_EXEC_RPC_TIMEOUT_MS
+ timeout: SSH_EXEC_RPC_TIMEOUT_MS,
+ signal: args.signal
},
(res) => {
const chunks: Buffer[] = [];
@@ -105,6 +107,7 @@ export const callPortSweep = (args: {
targets: string[];
dialTimeoutMs: number;
responseTimeoutMs: number;
+ signal?: AbortSignal;
}): Promise<Set<string>> => {
const payload = JSON.stringify({ targets: args.targets, timeoutMs: args.dialTimeoutMs });
return new Promise<Set<string>>((resolve, reject) => {
@@ -119,7 +122,8 @@ export const callPortSweep = (args: {
"Content-Length": Buffer.byteLength(payload).toString(),
Connection: "close"
},
- timeout: args.responseTimeoutMs
+ timeout: args.responseTimeoutMs,
+ signal: args.signal
},
(res) => {
const chunks: Buffer[] = [];