Skip to content

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

dont allow cidr ranges for postgres discovery

Andrey06e1a639b648
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-targets.ts b/backend/src/ee/services/pam-discovery/pam-discovery-targets.ts
index 8296e5f1b7..0102126d0a 100644
--- a/backend/src/ee/services/pam-discovery/pam-discovery-targets.ts
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-targets.ts
@@ -18,8 +18,11 @@ const isValidIpv4Target = (value: string) => {
return net.isIPv4(base) && isValidIpOrCidr(value);
};
-const isValidTarget = (value: string) =>
- isValidIpv4Target(value) || (value.length <= 253 && HOSTNAME_REGEX.test(value));
+const isValidHostname = (value: string) => value.length <= 253 && HOSTNAME_REGEX.test(value);
+
+const isValidTarget = (value: string) => isValidIpv4Target(value) || isValidHostname(value);
+
+const isValidHost = (value: string) => (net.isIPv4(value) && isValidIpOrCidr(value)) || isValidHostname(value);
// expands cidr ranges / bare ips / hostnames into the deduped set of target hosts. Enforces IPv4-only CIDRs and the host cap
export const expandTargets = (cidrRanges: string[]): string[] => {
@@ -47,11 +50,14 @@ export const expandTargets = (cidrRanges: string[]): string[] => {
return [...hosts];
};
-// shared by every host-range discovery source: validates each entry, then that the set expands within the cap
-export const DiscoveryTargetsSchema = z
- .array(z.string().trim().min(1))
- .min(1)
- .max(50)
+const targetList = z.array(z.string().trim().min(1)).min(1).max(50);
+
+// for sources that name instances outright; a CIDR would spray the credential across hosts it can't authenticate on
+export const DiscoveryHostsSchema = targetList.refine((hosts) => hosts.every(isValidHost), {
+ message: "Each target must be a valid IPv4 address or hostname. CIDR ranges are not supported."
+});
+
+export const DiscoveryTargetsSchema = targetList
.refine((ranges) => ranges.every(isValidTarget), {
message: "Each target must be a valid IPv4 address, IPv4 CIDR range, or hostname"
})
diff --git a/backend/src/ee/services/pam-discovery/postgres/postgres-discovery-factory.ts b/backend/src/ee/services/pam-discovery/postgres/postgres-discovery-factory.ts
index c110609333..db6115f7cc 100644
--- a/backend/src/ee/services/pam-discovery/postgres/postgres-discovery-factory.ts
+++ b/backend/src/ee/services/pam-discovery/postgres/postgres-discovery-factory.ts
@@ -8,7 +8,6 @@ import { logger } from "@app/lib/logger";
import { PamAccountType, PamPostgresAuthMethod } from "../../pam/pam-enums";
import { executeWithGateway, sweepReachableTargets } from "../pam-discovery-fns";
-import { expandTargets } from "../pam-discovery-targets";
import {
TDiscoveredAccount,
TDiscoveryCredentialAccount,
@@ -20,7 +19,6 @@ import {
const QUERY_TIMEOUT_MS = 20 * 1000;
const SCAN_CONCURRENCY = 32;
const SWEEP_DIAL_TIMEOUT_MS = 3 * 1000;
-const MAX_SWEEP_TARGETS = 65536;
const MAX_ACCOUNTS_PER_HOST = 2000;
const MAX_ACCOUNTS_PER_SCAN = 50000;
@@ -89,7 +87,7 @@ const toPostgresAccount = (account: TDiscoveryCredentialAccount): TPostgresAccou
};
};
-// an IAM token is minted per host/port/user pair, which a sweep across arbitrary targets cannot do, so only password accounts can drive a scan
+// an IAM token is minted per host/port/user, so it can't be reused across targets
const isUsableAccount = (account: TPostgresAccount) => Boolean(account.password);
export const postgresDiscoveryFactory: TPamDiscoveryFactory = ({
@@ -99,7 +97,7 @@ export const postgresDiscoveryFactory: TPamDiscoveryFactory = ({
gatewayV2Service
}) => {
const accounts = credentialAccounts.map(toPostgresAccount);
- const config = configuration as { cidrRanges: string[] };
+ const config = configuration as { hosts: string[] };
const enumerateInstance = (host: string, port: number, account: TPostgresAccount) =>
executeWithGateway(host, port, gatewayId, gatewayV2Service, async (proxyPort) => {
@@ -225,26 +223,26 @@ export const postgresDiscoveryFactory: TPamDiscoveryFactory = ({
});
}
- const targets = expandTargets(config.cidrRanges);
+ const targets = [...new Set(config.hosts.map((host) => host.trim()).filter(Boolean))];
const usablePorts = [...new Set(accounts.filter(isUsableAccount).map((a) => a.port))];
+ const candidatePairs = targets.flatMap((host) => usablePorts.map((port) => ({ host, port })));
- const sweepTargets = targets.flatMap((host) => usablePorts.map((port) => ({ host, port })));
- if (sweepTargets.length > MAX_SWEEP_TARGETS) {
- throw new BadRequestError({
- 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, signal);
+ const open = await sweepReachableTargets(
+ candidatePairs,
+ gatewayId,
+ gatewayV2Service,
+ SWEEP_DIAL_TIMEOUT_MS,
+ signal
+ );
- // scan every reachable host:port pair, plus any pair a credential account names outright
- const instancesToScan = sweepTargets.filter(
+ const instancesToScan = candidatePairs.filter(
({ host, port }) => open.has(`${host}:${port}`) || accounts.some((a) => a.host === host && a.port === port)
);
if (!instancesToScan.length) {
throw new BadRequestError({
message:
- "No hosts were reachable on the credential ports in the target range. Check the targets, that the gateway can reach them, and that PostgreSQL is listening."
+ "None of the targets were reachable on the credential accounts' ports. Check the hosts, that the gateway can reach them, and that PostgreSQL is listening."
});
}
diff --git a/backend/src/ee/services/pam-discovery/postgres/postgres-discovery-schemas.ts b/backend/src/ee/services/pam-discovery/postgres/postgres-discovery-schemas.ts
index 38e3bc8fbf..8d30f9b565 100644
--- a/backend/src/ee/services/pam-discovery/postgres/postgres-discovery-schemas.ts
+++ b/backend/src/ee/services/pam-discovery/postgres/postgres-discovery-schemas.ts
@@ -1,8 +1,8 @@
import { z } from "zod";
-import { DiscoveryTargetsSchema } from "../pam-discovery-targets";
+import { DiscoveryHostsSchema } from "../pam-discovery-targets";
export const PostgresDiscoveryConfigSchema = z.object({
- cidrRanges: DiscoveryTargetsSchema,
+ hosts: DiscoveryHostsSchema,
credentialAccountIds: z.array(z.string().uuid()).min(1).max(50)
});
diff --git a/docs/documentation/platform/pam/discovery/postgres.mdx b/docs/documentation/platform/pam/discovery/postgres.mdx
index 45a889efcb..d58725c8c1 100644
--- a/docs/documentation/platform/pam/discovery/postgres.mdx
+++ b/docs/documentation/platform/pam/discovery/postgres.mdx
@@ -4,7 +4,7 @@ sidebarTitle: "PostgreSQL"
description: "Scan PostgreSQL instances for login roles and import them into PAM."
---
-PostgreSQL discovery scans a set of PostgreSQL instances, enumerates the roles that can log in, stages them for review, and lets you import them into PAM as [PostgreSQL accounts](/documentation/platform/pam/accounts/postgresql). You point a source at the instances to scan and the [PostgreSQL accounts](/documentation/platform/pam/accounts/postgresql) to scan with.
+PostgreSQL discovery scans a set of PostgreSQL instances, enumerates the roles that can log in, stages them for review, and lets you import them into PAM as [PostgreSQL accounts](/documentation/platform/pam/accounts/postgresql). You list the instances to scan and the [PostgreSQL accounts](/documentation/platform/pam/accounts/postgresql) to scan with.
All scan traffic is tunneled through an Infisical [Gateway](/documentation/platform/gateways/overview).
@@ -12,8 +12,8 @@ All scan traffic is tunneled through an Infisical [Gateway](/documentation/platf
A PostgreSQL scan connects entirely through the Gateway:
-1. Each **CIDR range** is expanded into a list of target hosts; individual IPs and hostnames are used as-is (hostnames are resolved by the gateway in the target network).
-2. Each host is probed on the ports of your credential accounts, so unreachable hosts are skipped before any login is attempted.
+1. Each target you list is one instance to scan. Hostnames are resolved by the gateway in the target network.
+2. Each target is probed on the ports of your credential accounts, so unreachable ones are skipped before any login is attempted.
3. For each reachable host, discovery picks a credential account: it first tries an account whose stored host matches the target, otherwise it tries each account in turn until one connects.
4. It reads the roles defined on the instance.
5. Each role that can log in is staged as a **PostgreSQL** account scoped to that instance. `postgres` on two instances becomes two separate staged accounts.
@@ -33,7 +33,7 @@ The scanning account needs no special grant or elevated privileges. Any role tha
</Note>
<Warning>
-Only password authentication can drive a scan. An AWS IAM account's token is minted for one host, port, and user, which a scan across a range of hosts cannot do, so IAM accounts are skipped as credential accounts.
+Only password authentication can drive a scan. An AWS IAM account's token is minted for one host, port, and user, so it cannot be reused across the instances a source scans. IAM accounts are skipped as credential accounts.
</Warning>
## Creating a source
@@ -49,7 +49,7 @@ Only password authentication can drive a scan. An AWS IAM account's token is min
| **Credential Accounts** | One or more [PostgreSQL accounts](/documentation/platform/pam/accounts/postgresql) used to connect and scan |
| **Gateway** | The [Gateway](/documentation/platform/gateways/overview) or Gateway pool that scan traffic tunnels through |
| **Scan Schedule** | How often to scan automatically: **Manual**, **Daily**, or **Weekly** |
- | **Targets** | IP addresses, IPv4 CIDR ranges, or hostnames to scan, one per line or comma-separated. Hostnames are resolved by the gateway in the target network |
+ | **Targets** | IP addresses or hostnames of the instances to scan, one per line or comma-separated. Hostnames are resolved by the gateway in the target network |
</Step>
<Step title="Save">
Click **Add Source**. The source appears in the Discovery table.
diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/AddDiscoverySourceSheet.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/AddDiscoverySourceSheet.tsx
index d25e92538d..eccc0c9bfe 100644
--- a/frontend/src/pages/pam/PamDiscoveryPage/components/AddDiscoverySourceSheet.tsx
+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/AddDiscoverySourceSheet.tsx
@@ -262,7 +262,7 @@ const HostRangeSourceForm = ({
name: data.name,
credentialAccountId: data.credentialAccountIds[0],
schedule: data.schedule,
- configuration: buildHostRangeDiscoveryConfiguration(data),
+ configuration: buildHostRangeDiscoveryConfiguration(discoveryType, data),
...(gateway.gatewayId ? { gatewayId: gateway.gatewayId } : {}),
...(gateway.gatewayPoolId ? { gatewayPoolId: gateway.gatewayPoolId } : {})
},
@@ -309,6 +309,7 @@ const HostRangeSourceForm = ({
/>
<HostRangeDiscoveryConfigFields
control={control as unknown as Control<THostRangeDiscoveryConfigFields>}
+ discoveryType={discoveryType}
/>
</FormShell>
</form>
diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryConfigFields.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryConfigFields.tsx
index b5289d93c8..3dffee0544 100644
--- a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryConfigFields.tsx
+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryConfigFields.tsx
@@ -166,19 +166,28 @@ export const DiscoveryConfigFields = ({
);
};
-// Sources that scan a host range with a set of credential accounts
export const HOST_RANGE_SOURCES = {
[PamDiscoveryType.Unix]: {
accountType: PamAccountType.SSH,
placeholder: "Select SSH accounts",
warning:
- "Password accounts send their password to every host scanned in the range, including hosts you don't control. We recommend a key or certificate account for scanning."
+ "Password accounts send their password to every host scanned in the range, including hosts you don't control. We recommend a key or certificate account for scanning.",
+ configKey: "cidrRanges",
+ allowCidr: true,
+ targetsPlaceholder: "10.0.0.0/24, 192.168.1.10, host.internal",
+ targetsDescription:
+ "IP addresses, IPv4 CIDR ranges, or hostnames, one per line or comma-separated."
},
[PamDiscoveryType.Postgres]: {
accountType: PamAccountType.Postgres,
placeholder: "Select PostgreSQL accounts",
warning:
- "The account password is sent to every host scanned in the range, including hosts you don't control. Only scan ranges you trust."
+ "The account password is sent to every instance scanned, including any you don't control. Only list hosts you trust.",
+ configKey: "hosts",
+ allowCidr: false,
+ targetsPlaceholder: "192.168.1.10, db-primary.internal",
+ targetsDescription:
+ "IP addresses or hostnames of the instances to scan, one per line or comma-separated. CIDR ranges are not supported."
}
} as const;
@@ -189,7 +198,7 @@ export const isHostRangeDiscoveryType = (
): type is THostRangeDiscoveryType => Boolean(type && type in HOST_RANGE_SOURCES);
export const hostRangeDiscoveryConfigFormShape = {
- cidrRanges: z.string().min(1, "At least one target is required"),
+ targets: z.string().min(1, "At least one target is required"),
credentialAccountIds: z.array(z.string()).min(1, "Select at least one account")
};
@@ -198,29 +207,34 @@ export type THostRangeDiscoveryConfigFields = z.infer<
>;
export const HOST_RANGE_DISCOVERY_CONFIG_DEFAULTS: THostRangeDiscoveryConfigFields = {
- cidrRanges: "",
+ targets: "",
credentialAccountIds: []
};
-const parseCidrRanges = (value: string): string[] =>
+const parseTargets = (value: string): string[] =>
value
.split(/[\n,]/)
.map((v) => v.trim())
.filter(Boolean);
export const hostRangeDiscoveryConfigFromSource = (
+ discoveryType: THostRangeDiscoveryType,
config: Record<string, unknown>
-): THostRangeDiscoveryConfigFields => ({
- cidrRanges: Array.isArray(config.cidrRanges) ? (config.cidrRanges as string[]).join("\n") : "",
- credentialAccountIds: Array.isArray(config.credentialAccountIds)
- ? (config.credentialAccountIds as string[])
- : []
-});
+): THostRangeDiscoveryConfigFields => {
+ const stored = config[HOST_RANGE_SOURCES[discoveryType].configKey];
+ return {
+ targets: Array.isArray(stored) ? (stored as string[]).join("\n") : "",
+ credentialAccountIds: Array.isArray(config.credentialAccountIds)
+ ? (config.credentialAccountIds as string[])
+ : []
+ };
+};
export const buildHostRangeDiscoveryConfiguration = (
+ discoveryType: THostRangeDiscoveryType,
data: THostRangeDiscoveryConfigFields
): Record<string, unknown> => ({
- cidrRanges: parseCidrRanges(data.cidrRanges),
+ [HOST_RANGE_SOURCES[discoveryType].configKey]: parseTargets(data.targets),
credentialAccountIds: data.credentialAccountIds
});
@@ -274,27 +288,37 @@ export const CredentialAccountsField = ({
};
export const HostRangeDiscoveryConfigFields = ({
- control
+ control,
+ discoveryType
}: {
control: Control<THostRangeDiscoveryConfigFields>;
-}) => (
- <Controller
- control={control}
- name="cidrRanges"
- render={({ field, fieldState }) => (
- <Field>
- <FieldLabel>Targets</FieldLabel>
- <FieldContent>
- <TextArea {...field} rows={3} placeholder="10.0.0.0/24, 192.168.1.10, host.internal" />
- <FieldDescription>
- IP addresses, IPv4 CIDR ranges, or hostnames, one per line or comma-separated.
- </FieldDescription>
- <FieldError>{fieldState.error?.message}</FieldError>
- </FieldContent>
- </Field>
- )}
- />
-);
+ discoveryType: THostRangeDiscoveryType;
+}) => {
+ const { allowCidr, targetsPlaceholder, targetsDescription } = HOST_RANGE_SOURCES[discoveryType];
+
+ return (
+ <Controller
+ control={control}
+ name="targets"
+ rules={{
+ validate: (value: string) =>
+ allowCidr || !parseTargets(value).some((t) => t.includes("/"))
+ ? true
+ : "CIDR ranges are not supported. List each instance by IP address or hostname."
+ }}
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>Targets</FieldLabel>
+ <FieldContent>
+ <TextArea {...field} rows={3} placeholder={targetsPlaceholder} />
+ <FieldDescription>{targetsDescription}</FieldDescription>
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ );
+};
// Shared credential-account + schedule fields, used by both the create modal and the edit tab.
export const CredentialAccountField = ({
diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx
index d8b4a618c4..e4710bc3f5 100644
--- a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx
+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx
@@ -256,7 +256,7 @@ const HostRangeConfigForm = ({
schedule: source.schedule,
gatewayId: source.gatewayId ?? null,
gatewayPoolId: source.gatewayPoolId ?? null,
- ...hostRangeDiscoveryConfigFromSource(source.discoveryConfiguration)
+ ...hostRangeDiscoveryConfigFromSource(discoveryType, source.discoveryConfiguration)
};
const {
@@ -288,7 +288,7 @@ const HostRangeConfigForm = ({
schedule: data.schedule,
gatewayId: data.gatewayId,
gatewayPoolId: data.gatewayPoolId,
- configuration: buildHostRangeDiscoveryConfiguration(data)
+ configuration: buildHostRangeDiscoveryConfiguration(discoveryType, data)
},
{ onSuccess: () => createNotification({ type: "success", text: "Discovery source updated" }) }
);
@@ -317,6 +317,7 @@ const HostRangeConfigForm = ({
/>
<HostRangeDiscoveryConfigFields
control={control as unknown as Control<THostRangeDiscoveryConfigFields>}
+ discoveryType={discoveryType}
/>
</ConfigCard>