Skip to content

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

feat(pki-discovery): windows server discovery

bernie-g263595ade73b
diff --git a/backend/src/ee/routes/v2/gateway-router.ts b/backend/src/ee/routes/v2/gateway-router.ts
index 7fa3945120..7abae74c44 100644
--- a/backend/src/ee/routes/v2/gateway-router.ts
+++ b/backend/src/ee/routes/v2/gateway-router.ts
@@ -140,6 +140,7 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
sessionLogMaskingBuiltInDetection: z.boolean().optional(),
clickhouseNativeProtocol: z.boolean().optional(),
certificateScan: z.boolean().optional(),
+ windowsCertificateScan: z.boolean().optional(),
supported_account_types: z.array(z.string().trim().max(64)).max(64).optional()
})
.optional()
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
index 0157562c71..2535a27669 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
@@ -1058,6 +1058,7 @@ export const gatewayV2ServiceFactory = ({
sessionLogMaskingBuiltInDetection?: boolean;
clickhouseNativeProtocol?: boolean;
certificateScan?: boolean;
+ windowsCertificateScan?: boolean;
supported_account_types?: string[];
};
}) => {
diff --git a/backend/src/ee/services/pki-discovery/CLAUDE.md b/backend/src/ee/services/pki-discovery/CLAUDE.md
index 3aca39d41d..3681ffd27c 100644
--- a/backend/src/ee/services/pki-discovery/CLAUDE.md
+++ b/backend/src/ee/services/pki-discovery/CLAUDE.md
@@ -3,15 +3,21 @@
Invariants for `pki-discovery-*` and `pki-installation-*` that the code doesn't state on its own.
- A discovery job (`pki_discovery_configs`) has a `discoveryType`: `network` (TLS handshakes, optional job
- gateway) or `linux-server` (files over SSH). Every type records
- its run through `pki-discovery-scan-run-fns.ts` and parses certificates with `parseCertificateDer`.
+ gateway), `linux-server` (files over SSH) or `windows-server` (the LocalMachine certificate store over
+ WinRM). Every type records its run through `pki-discovery-scan-run-fns.ts` and parses certificates with `parseCertificateDer`.
- Linux Server jobs never have their own gateway. Each SSH connection must use a gateway or pool, and the
gateway (`packages/gateway-v2/certscan/` in the CLI repo, RPC `/v1/scan-certificates`) lists, reads and parses
the files. Private keys never reach the backend. Old gateways lack `capabilities.certificateScan` and get an
"update the gateway" message.
+- Windows Server discovery follows the same rules over WinRM connections: RPC `/v1/scan-certificates` on the
+ WinRM ALPN, capability `windowsCertificateScan`. The gateway always reads `CA` and `Root` to build chains, but
+ only returns certificates from the requested stores. Installations are `os_store`, keyed on
+ `Cert:\LocalMachine\<store>\<thumbprint>` instead of a file path, and never take a password.
+- Both host types share `executeHostScan` in `pki-discovery-host-scan-fns.ts`; a new host type supplies a
+ `THostScanDefinition` and an entry in the service's `HOST_DISCOVERY_TYPES`.
- Host scans take a per-connection slot (`tryAdmitAppConnectionConcurrency`), shared with PKI syncs.
- Nothing raw reaches users: gateway, transport and file errors map to product messages; raw text is logged.
-- Installation identity is `hostIdentifier` (connection host, plus `:port` unless 22) + real path + gateway or
+- Installation identity is `hostIdentifier` (connection host, plus `:port` unless it is the protocol default: 22 for SSH, 5985 or 5986 for WinRM over HTTP or HTTPS) + real path + gateway or
pool id. The name is `<hostname>:<path>`, or `<hostIdentifier>:<path>` without a hostname, and never affects
identity.
- Scans only add or refresh certificate links, never remove them. A certificate that left a file keeps its old
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-host-fns.ts b/backend/src/ee/services/pki-discovery/pki-discovery-host-fns.ts
index 745d0273a4..95dd33f213 100644
--- a/backend/src/ee/services/pki-discovery/pki-discovery-host-fns.ts
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-host-fns.ts
@@ -111,14 +111,17 @@ export const planHostFileImport = (
export const sshConnectionWithoutGatewayMessage = (connectionName: string) =>
`SSH connection '${connectionName}' does not use a gateway. Linux Server discovery runs on the gateway, so assign one to the connection.`;
+export const windowsConnectionWithoutGatewayMessage = (connectionName: string) =>
+ `Windows (WinRM) connection '${connectionName}' does not use a gateway. Windows Server discovery runs on the gateway, so assign one to the connection.`;
+
export const buildHostInstallationName = (hostIdentifier: string, hostname: string | undefined, filePath: string) =>
truncateString(`${hostname?.trim() || hostIdentifier}:${filePath}`, DB_SHORT_VARCHAR_LIMIT);
const DEFAULT_SSH_PORT = 22;
-export const normalizeHostIdentifier = (host: string, port?: number) => {
+export const normalizeHostIdentifier = (host: string, port?: number, defaultPort = DEFAULT_SSH_PORT) => {
const normalized = host.trim().toLowerCase();
- if (!port || port === DEFAULT_SSH_PORT) return normalized;
+ if (!port || port === defaultPort) return normalized;
return net.isIPv6(normalized) ? `[${normalized}]:${port}` : `${normalized}:${port}`;
};
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-host-scan-fns.ts b/backend/src/ee/services/pki-discovery/pki-discovery-host-scan-fns.ts
index de92071e00..f680bd5a45 100644
--- a/backend/src/ee/services/pki-discovery/pki-discovery-host-scan-fns.ts
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-host-scan-fns.ts
@@ -111,8 +111,13 @@ type TKeystorePassword = TCertificateScanRequest["keystorePasswords"][number];
const derToPem = (der: Buffer) => new x509.X509Certificate(der).toString("pem");
-const canScanCertificates = (capabilities: unknown) =>
- (capabilities as Record<string, unknown> | null)?.certificateScan === true;
+export enum HostScanCapability {
+ CertificateScan = "certificateScan",
+ WindowsCertificateScan = "windowsCertificateScan"
+}
+
+const hasCapability = (capabilities: unknown, capability: HostScanCapability) =>
+ (capabilities as Record<string, unknown> | null)?.[capability] === true;
export const toHostScanErrorMessage = (error: unknown, logContext: string): string => {
if (error instanceof GatewayTransportError) {
@@ -127,7 +132,38 @@ export const toHostScanErrorMessage = (error: unknown, logContext: string): stri
return UNEXPECTED_HOST_SCAN_ERROR;
};
-type TAppConnectionRow = Awaited<ReturnType<THostScanDeps["appConnectionDAL"]["findById"]>>;
+export type TAppConnectionRow = Awaited<ReturnType<THostScanDeps["appConnectionDAL"]["findById"]>>;
+
+export type TScanGateway = { gatewayId: string; gatewayName: string; fingerprintGatewayKey: string };
+
+export const selectScanGateway = async (
+ connection: NonNullable<TAppConnectionRow>,
+ capability: HostScanCapability,
+ connectionKind: string,
+ deps: THostScanDeps
+): Promise<TScanGateway> => {
+ if (connection.gatewayPoolId) {
+ const selected = await deps.gatewayPoolService.selectGatewayFromPool({
+ poolId: connection.gatewayPoolId,
+ filter: (gateway) => hasCapability(gateway.capabilities, capability),
+ unavailableMessage:
+ "No healthy gateway in the connection's pool supports certificate scanning. Update the pool's gateways to the latest version."
+ });
+ return { gatewayId: selected.id, gatewayName: selected.name, fingerprintGatewayKey: connection.gatewayPoolId };
+ }
+ const gateway = await deps.gatewayV2DAL.findById(connection.gatewayId as string);
+ if (!gateway) {
+ throw new BadRequestError({
+ message: `The gateway of ${connectionKind} connection '${connection.name}' no longer exists`
+ });
+ }
+ if (!hasCapability(gateway.capabilities, capability)) {
+ throw new BadRequestError({
+ message: `Gateway '${gateway.name}' is too old for certificate scanning. Update it to the latest version.`
+ });
+ }
+ return { gatewayId: gateway.id, gatewayName: gateway.name, fingerprintGatewayKey: gateway.id };
+};
export const resolveHost = async (connection: TAppConnectionRow | undefined, orgId: string, deps: THostScanDeps) => {
if (!connection || connection.orgId !== orgId) {
@@ -153,30 +189,12 @@ export const resolveHost = async (connection: TAppConnectionRow | undefined, org
orgId: connection.orgId
} as TSshConnectionConfig;
- let gatewayId: string;
- let gatewayName: string;
- if (connection.gatewayPoolId) {
- const selected = await deps.gatewayPoolService.selectGatewayFromPool({
- poolId: connection.gatewayPoolId,
- filter: (gateway) => canScanCertificates(gateway.capabilities),
- unavailableMessage:
- "No healthy gateway in the connection's pool supports certificate scanning. Update the pool's gateways to the latest version."
- });
- gatewayId = selected.id;
- gatewayName = selected.name;
- } else {
- const gateway = await deps.gatewayV2DAL.findById(connection.gatewayId as string);
- if (!gateway) {
- throw new BadRequestError({ message: `The gateway of SSH connection '${connection.name}' no longer exists` });
- }
- if (!canScanCertificates(gateway.capabilities)) {
- throw new BadRequestError({
- message: `Gateway '${gateway.name}' is too old for certificate scanning. Update it to the latest version.`
- });
- }
- gatewayId = gateway.id;
- gatewayName = gateway.name;
- }
+ const { gatewayId, gatewayName, fingerprintGatewayKey } = await selectScanGateway(
+ connection,
+ HostScanCapability.CertificateScan,
+ "SSH",
+ deps
+ );
const [targetHost] = await verifyHostInputValidity({
host: credentials.host,
@@ -192,7 +210,7 @@ export const resolveHost = async (connection: TAppConnectionRow | undefined, org
targetPort: credentials.port,
gatewayId,
gatewayName,
- fingerprintGatewayKey: connection.gatewayPoolId ?? gatewayId,
+ fingerprintGatewayKey,
credentials: toSshExecCredentials(config)
} satisfies TResolvedHost;
};
@@ -288,24 +306,34 @@ const runCertificateScan = async (
return parsed.data;
};
-export const scanHost = async (
- host: TResolvedHost,
- request: TCertificateScanRequest,
- deps: THostScanDeps
-): Promise<TCertificateScanResponse> => {
- if (!(await admitConnectionScanSlot(host.connectionId, deps))) {
- throw new BadRequestError({ message: "The SSH connection is busy with other jobs. Try again later." });
+export const withConnectionScanSlot = async <T>(
+ connectionId: string,
+ connectionKind: string,
+ deps: THostScanDeps,
+ fn: () => Promise<T>
+): Promise<T> => {
+ if (!(await admitConnectionScanSlot(connectionId, deps))) {
+ throw new BadRequestError({
+ message: `The ${connectionKind} connection is busy with other jobs. Try again later.`
+ });
}
try {
- return await runCertificateScan(host, request, deps);
+ return await fn();
} finally {
- await releaseAppConnectionConcurrency(deps.keyStore, host.connectionId).catch((error: unknown) =>
- logger.error(error, `Failed to release the connection scan slot [connectionId=${host.connectionId}]`)
+ await releaseAppConnectionConcurrency(deps.keyStore, connectionId).catch((error: unknown) =>
+ logger.error(error, `Failed to release the connection scan slot [connectionId=${connectionId}]`)
);
}
};
-type TWriteContext = {
+export const scanHost = (
+ host: TResolvedHost,
+ request: TCertificateScanRequest,
+ deps: THostScanDeps
+): Promise<TCertificateScanResponse> =>
+ withConnectionScanSlot(host.connectionId, "SSH", deps, () => runCertificateScan(host, request, deps));
+
+export type TWriteContext = {
projectId: string;
discoveryId?: string;
scanTime: Date;
@@ -330,10 +358,9 @@ const buildHostLocationDetails = (host: TScannedHost, file: TCertificateScanFile
gatewayName: host.gatewayName
});
-const importCertificateChains = async (
- host: TScannedHost,
- file: TCertificateScanFile,
+export const importCertificateChains = async (
chains: Buffer[][],
+ discoveryMetadata: Record<string, string | undefined>,
ctx: TWriteContext,
deps: THostScanDeps
) => {
@@ -358,10 +385,7 @@ const importCertificateChains = async (
},
{
discoveredBy: ctx.discoveryId,
- hostIdentifier: host.hostIdentifier,
- hostname: host.hostname,
- filePath: file.realPath,
- format: file.format,
+ ...discoveryMetadata,
discoveredAt: ctx.scanTime.toISOString(),
issuerCommonName: parsed.issuerCommonName,
issuerOrganization: parsed.issuerOrganization
@@ -375,28 +399,28 @@ const importCertificateChains = async (
return certificateIds;
};
-const upsertInstallationWithLinks = async (
- host: TScannedHost,
- file: TCertificateScanFile,
+export const upsertInstallationWithLinks = async (
{
fingerprint,
locationType,
+ locationDetails,
+ name,
keystoreStatus,
certificateIds,
refreshOnly
}: {
fingerprint: string;
locationType: PkiInstallationLocationType;
+ locationDetails: TPkiInstallationLocationDetails;
+ name: string | null;
keystoreStatus?: PkiKeystoreStatus;
certificateIds: string[];
refreshOnly: boolean;
},
ctx: TWriteContext,
deps: THostScanDeps
-) => {
- const locationDetails = buildHostLocationDetails(host, file);
-
- return deps.pkiDiscoveryConfigDAL.transaction(async (tx) => {
+) =>
+ deps.pkiDiscoveryConfigDAL.transaction(async (tx) => {
let installation = await findTargetInstallation(ctx, fingerprint, deps, tx);
if (!installation && refreshOnly) return undefined;
const previousMetadata = (installation?.metadata as TPkiInstallationMetadata | null) ?? {};
@@ -421,7 +445,7 @@ const upsertInstallationWithLinks = async (
locationType,
locationDetails,
locationFingerprint: fingerprint,
- name: buildHostInstallationName(host.hostIdentifier, host.hostname, file.realPath),
+ name,
type: PkiInstallationType.Server,
metadata,
lastSeenAt: ctx.scanTime
@@ -468,7 +492,6 @@ const upsertInstallationWithLinks = async (
}
return installation.id;
});
-};
export const writeHostFile = async (
host: TScannedHost,
@@ -488,13 +511,23 @@ export const writeHostFile = async (
const certificateIds =
plan.action === HostFileImportAction.Refresh
? []
- : await importCertificateChains(host, file, plan.chainsToImport, ctx, deps);
+ : await importCertificateChains(
+ plan.chainsToImport,
+ {
+ hostIdentifier: host.hostIdentifier,
+ hostname: host.hostname,
+ filePath: file.realPath,
+ format: file.format
+ },
+ ctx,
+ deps
+ );
const installationId = await upsertInstallationWithLinks(
- host,
- file,
{
fingerprint,
locationType: plan.locationType,
+ locationDetails: buildHostLocationDetails(host, file),
+ name: buildHostInstallationName(host.hostIdentifier, host.hostname, file.realPath),
keystoreStatus: plan.keystoreStatus,
certificateIds,
refreshOnly: plan.action === HostFileImportAction.Refresh
@@ -519,23 +552,36 @@ export const buildScanRequest = (
keystorePasswords
});
-type TLinuxServerScanRun = {
+export type THostScanRun<TConfig> = {
discoveryId: string;
projectId: string;
orgId: string;
- targetConfig: TLinuxServerTargetConfig;
+ targetConfig: TConfig;
ctx: TWriteContext;
writeLimit: ReturnType<typeof pLimit>;
certificateIds: Set<string>;
installationIds: Set<string>;
};
-type THostScanOutcome = { issues: string[]; failure?: { label: string; message: string } };
+export type THostScanOutcome = { issues: string[]; failure?: { label: string; message: string } };
+
+type THostScanTargetConfig = { connectionIds: string[]; importStandaloneCaCertificates: boolean };
-const scanConnection = async (
+export type THostScanDefinition<TConfig extends THostScanTargetConfig> = {
+ discoveryType: PkiDiscoveryType;
+ label: string;
+ scanConnection: (
+ connection: TAppConnectionRow | undefined,
+ label: string,
+ run: THostScanRun<TConfig>,
+ deps: THostScanDeps
+ ) => Promise<THostScanOutcome>;
+};
+
+const scanLinuxConnection = async (
connection: TAppConnectionRow | undefined,
label: string,
- run: TLinuxServerScanRun,
+ run: THostScanRun<TLinuxServerTargetConfig>,
deps: THostScanDeps
): Promise<THostScanOutcome> => {
let hostLabel = label;
@@ -574,7 +620,11 @@ const scanConnection = async (
}
};
-export const executeLinuxServerScan = async (discoveryId: string, deps: THostScanDeps): Promise<void> => {
+export const executeHostScan = async <TConfig extends THostScanTargetConfig>(
+ discoveryId: string,
+ definition: THostScanDefinition<TConfig>,
+ deps: THostScanDeps
+): Promise<void> => {
const { pkiDiscoveryConfigDAL } = deps;
const startedAt = new Date();
let scanHistoryId: string | undefined;
@@ -585,10 +635,10 @@ export const executeLinuxServerScan = async (discoveryId: string, deps: THostSca
throw new Error(`Discovery config not found: ${discoveryId}`);
}
const project = await deps.projectDAL.findById(discoveryConfig.projectId);
- const targetConfig = discoveryConfig.targetConfig as TLinuxServerTargetConfig;
+ const targetConfig = discoveryConfig.targetConfig as TConfig;
logger.info(
- `Linux Server discovery scan starting [discoveryId=${discoveryId}] [projectId=${discoveryConfig.projectId}]`
+ `${definition.label} discovery scan starting [discoveryId=${discoveryId}] [projectId=${discoveryConfig.projectId}]`
);
const certificateKmsKeyId = await getProjectKmsCertificateKeyId({
@@ -601,7 +651,7 @@ export const executeLinuxServerScan = async (discoveryId: string, deps: THostSca
scanHistoryId = await startScanRun(discoveryId, startedAt, deps);
const hostLimit = pLimit(HOST_CONCURRENCY);
- const run: TLinuxServerScanRun = {
+ const run: THostScanRun<TConfig> = {
discoveryId,
projectId: discoveryConfig.projectId,
orgId: project.orgId,
@@ -629,7 +679,9 @@ export const executeLinuxServerScan = async (discoveryId: string, deps: THostSca
const outcomes = await Promise.all(
targetConfig.connectionIds.map((connectionId) => {
const connection = connectionsById.get(connectionId);
- return hostLimit(() => scanConnection(connection, connection?.name ?? "Deleted connection", run, deps));
+ return hostLimit(() =>
+ definition.scanConnection(connection, connection?.name ?? "Deleted connection", run, deps)
+ );
})
);
@@ -644,7 +696,7 @@ export const executeLinuxServerScan = async (discoveryId: string, deps: THostSca
const allHostsFailed = failedHosts > 0 && failedHosts === targetConfig.connectionIds.length;
const finalStatus = allHostsFailed ? PkiDiscoveryScanStatus.Failed : PkiDiscoveryScanStatus.Completed;
const failureIssues = [...hostFailures.entries()].map(([message, labels]) => `${labels.join(", ")}: ${message}`);
- const allIssues = [...failureIssues, ...outcomes.flatMap(({ issues }) => issues)];
+ const allIssues = [...new Set([...failureIssues, ...outcomes.flatMap(({ issues }) => issues)])];
const errorMessage = allIssues.length > 0 ? allIssues.join("; ") : null;
await finishScanRun(
@@ -663,7 +715,7 @@ export const executeLinuxServerScan = async (discoveryId: string, deps: THostSca
await sendScanCompletedTelemetry(deps.telemetryService, {
discoveryId,
- discoveryType: PkiDiscoveryType.LinuxServer,
+ discoveryType: definition.discoveryType,
projectId: run.projectId,
orgId: run.orgId,
status: finalStatus,
@@ -673,11 +725,21 @@ export const executeLinuxServerScan = async (discoveryId: string, deps: THostSca
});
logger.info(
- `Linux Server discovery scan finished [discoveryId=${discoveryId}] [status=${finalStatus}] [certificates=${run.certificateIds.size}] [installations=${run.installationIds.size}]`
+ `${definition.label} discovery scan finished [discoveryId=${discoveryId}] [status=${finalStatus}] [certificates=${run.certificateIds.size}] [installations=${run.installationIds.size}]`
);
} catch (error) {
- const message = toHostScanErrorMessage(error, `Linux Server discovery scan failed [discoveryId=${discoveryId}]`);
+ const message = toHostScanErrorMessage(
+ error,
+ `${definition.label} discovery scan failed [discoveryId=${discoveryId}]`
+ );
await failScanRun(discoveryId, scanHistoryId, new Error(message), deps);
throw error;
}
};
+
+export const executeLinuxServerScan = (discoveryId: string, deps: THostScanDeps): Promise<void> =>
+ executeHostScan<TLinuxServerTargetConfig>(
+ discoveryId,
+ { discoveryType: PkiDiscoveryType.LinuxServer, label: "Linux Server", scanConnection: scanLinuxConnection },
+ deps
+ );
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts b/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts
index 2e87354f06..7545ae6533 100644
--- a/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts
@@ -21,6 +21,7 @@ import { rescanInstallation } from "./pki-discovery-rescan-fns";
import { executeScan } from "./pki-discovery-scan-fns";
import { TPkiDiscoveryScanHistoryDALFactory } from "./pki-discovery-scan-history-dal";
import { PkiDiscoveryType } from "./pki-discovery-types";
+import { executeWindowsServerScan } from "./pki-discovery-windows-scan-fns";
type TPkiDiscoveryQueueFactoryDep = {
pkiDiscoveryConfigDAL: TPkiDiscoveryConfigDALFactory;
@@ -107,6 +108,9 @@ export const pkiDiscoveryQueueFactory = ({
case PkiDiscoveryType.LinuxServer:
await executeLinuxServerScan(discoveryId, scanDeps);
break;
+ case PkiDiscoveryType.WindowsServer:
+ await executeWindowsServerScan(discoveryId, scanDeps);
+ break;
default:
throw new Error(`Unsupported discovery type: ${discoveryType as string}`);
}
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-schemas.ts b/backend/src/ee/services/pki-discovery/pki-discovery-schemas.ts
index 5e5587b2f4..069a831eae 100644
--- a/backend/src/ee/services/pki-discovery/pki-discovery-schemas.ts
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-schemas.ts
@@ -2,6 +2,7 @@ import RE2 from "re2";
import { z } from "zod";
import { DEFAULT_TLS_PORTS } from "./pki-discovery-fns";
+import { WindowsCertificateStore } from "./pki-discovery-types";
const LINUX_SERVER_DEFAULT_MAX_FOLDER_DEPTH = 8;
const LINUX_SERVER_MAX_FOLDER_DEPTH = 20;
@@ -10,6 +11,12 @@ const LINUX_SERVER_MAX_FILE_SIZE_KB = 10240;
const LINUX_SERVER_MAX_CONNECTIONS = 100;
const LINUX_SERVER_MAX_SEARCH_FOLDERS = 20;
const LINUX_SERVER_MAX_SKIP_FOLDERS = 50;
+const WINDOWS_SERVER_MAX_CONNECTIONS = 100;
+
+export const DEFAULT_WINDOWS_CERTIFICATE_STORES = [
+ WindowsCertificateStore.Personal,
+ WindowsCertificateStore.WebHosting
+];
const FORBIDDEN_PATH_CHARACTERS = new RE2("[\\x00\\r\\n]");
const PARENT_SEGMENT = new RE2("(^|/)\\.\\.(/|$)");
@@ -70,10 +77,55 @@ export const LinuxServerTargetConfigSchema = z
})
.strict();
+export const WindowsServerTargetConfigSchema = z
+ .object({
+ connectionIds: z
+ .array(z.string().uuid())
+ .min(1, "Select at least one Windows (WinRM) connection")
+ .max(WINDOWS_SERVER_MAX_CONNECTIONS)
+ .refine((ids) => new Set(ids).size === ids.length, "Each Windows (WinRM) connection can be listed once")
+ .describe("IDs of the Windows (WinRM) connections to scan. Each connection must use a gateway."),
+ certificateStores: z
+ .array(z.nativeEnum(WindowsCertificateStore))
+ .min(1, "Select at least one certificate store")
+ .refine((stores) => new Set(stores).size === stores.length, "Each certificate store can be listed once")
+ .default(DEFAULT_WINDOWS_CERTIFICATE_STORES)
+ .describe("LocalMachine certificate stores to read."),
+ importStandaloneCaCertificates: z
+ .boolean()
+ .default(false)
+ .describe("Also import CA certificates on their own. Leaf certificates always bring their chain.")
+ })
+ .strict();
+
+// The type-specific schema re-validates on the service; this only keeps the router's shared fields neutral.
+const CA_ONLY_WINDOWS_STORES: string[] = [
+ WindowsCertificateStore.IntermediateCertificationAuthorities,
+ WindowsCertificateStore.TrustedRootCertificationAuthorities
+];
+
+export const importsNothingFromWindowsStores = (config: {
+ certificateStores: WindowsCertificateStore[];
+ importStandaloneCaCertificates: boolean;
+}) =>
+ !config.importStandaloneCaCertificates &&
+ config.certificateStores.every((store) => CA_ONLY_WINDOWS_STORES.includes(store));
+
export const DiscoveryTargetConfigInputSchema = NetworkTargetConfigSchema.partial()
.merge(LinuxServerTargetConfigSchema.partial())
+ .merge(WindowsServerTargetConfigSchema.partial())
+ .extend({
+ connectionIds: z
+ .array(z.string().uuid())
+ .min(1, "Select at least one connection")
+ .max(Math.max(LINUX_SERVER_MAX_CONNECTIONS, WINDOWS_SERVER_MAX_CONNECTIONS))
+ .optional()
+ .describe(
+ "SSH connections for Linux Server jobs or Windows (WinRM) connections for Windows Server jobs, one per server."
+ )
+ })
.describe(
- "Target configuration. Network jobs use domains, ipRanges and ports. Linux Server jobs use connectionIds, searchFolderPaths, skipFolderPaths, maxFolderDepth, maxFileSizeKb and importStandaloneCaCertificates."
+ "Target configuration. Network jobs use domains, ipRanges and ports. Linux Server jobs use connectionIds, searchFolderPaths, skipFolderPaths, maxFolderDepth, maxFileSizeKb and importStandaloneCaCertificates. Windows Server jobs use connectionIds, certificateStores and importStandaloneCaCertificates."
);
export const formatTargetConfigIssue = ({ path, message }: z.ZodIssue) =>
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-service.ts b/backend/src/ee/services/pki-discovery/pki-discovery-service.ts
index d513562b09..9128c3470c 100644
--- a/backend/src/ee/services/pki-discovery/pki-discovery-service.ts
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-service.ts
@@ -24,12 +24,14 @@ import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TGatewayV2DALFactory } from "../gateway-v2/gateway-v2-dal";
import { TPkiDiscoveryConfigDALFactory } from "./pki-discovery-config-dal";
import { validateTargetConfig } from "./pki-discovery-fns";
-import { sshConnectionWithoutGatewayMessage } from "./pki-discovery-host-fns";
+import { sshConnectionWithoutGatewayMessage, windowsConnectionWithoutGatewayMessage } from "./pki-discovery-host-fns";
import { TPkiDiscoveryScanHistoryDALFactory } from "./pki-discovery-scan-history-dal";
import {
formatTargetConfigIssue,
+ importsNothingFromWindowsStores,
LinuxServerTargetConfigSchema,
- NetworkTargetConfigSchema
+ NetworkTargetConfigSchema,
+ WindowsServerTargetConfigSchema
} from "./pki-discovery-schemas";
import {
PkiDiscoveryScanStatus,
@@ -44,13 +46,41 @@ import {
TNetworkTargetConfig,
TPkiDiscoveryTargetConfig,
TTriggerPkiDiscoveryScanDTO,
- TUpdatePkiDiscoveryDTO
+ TUpdatePkiDiscoveryDTO,
+ TWindowsServerTargetConfig
} from "./pki-discovery-types";
const MAX_CLOUD_DISCOVERIES = 10;
const SCAN_RATE_LIMIT_HOURS = 24;
const CONNECTION_VALIDATION_CONCURRENCY = 5;
+const HOST_DISCOVERY_TYPES = {
+ [PkiDiscoveryType.LinuxServer]: {
+ label: "Linux Server",
+ app: AppConnection.SSH,
+ connectionKind: "SSH",
+ schema: LinuxServerTargetConfigSchema,
+ withoutGatewayMessage: sshConnectionWithoutGatewayMessage
+ },
+ [PkiDiscoveryType.WindowsServer]: {
+ label: "Windows Server",
+ app: AppConnection.WinRM,
+ connectionKind: "Windows (WinRM)",
+ schema: WindowsServerTargetConfigSchema,
+ withoutGatewayMessage: windowsConnectionWithoutGatewayMessage
+ }
+} as const;
+
+type THostDiscoveryType = keyof typeof HOST_DISCOVERY_TYPES;
+
+const isHostDiscoveryType = (discoveryType: string): discoveryType is THostDiscoveryType =>
+ Object.hasOwn(HOST_DISCOVERY_TYPES, discoveryType);
+
+const hostConnectionIds = (discoveryType: string, targetConfig: unknown) =>
+ isHostDiscoveryType(discoveryType)
+ ? (targetConfig as TLinuxServerTargetConfig | TWindowsServerTargetConfig).connectionIds
+ : [];
+
type TPkiDiscoveryServiceFactoryDep = {
pkiDiscoveryConfigDAL: Pick<
TPkiDiscoveryConfigDALFactory,
@@ -110,37 +140,51 @@ export const pkiDiscoveryServiceFactory = ({
return config;
};
- const $validateLinuxServerTarget = async (
+ const $validateHostTarget = async (
+ discoveryType: THostDiscoveryType,
targetConfig: TPkiDiscoveryTargetConfig,
projectId: string,
actor: OrgServiceActor,
existingConnectionIds?: string[]
- ): Promise<TLinuxServerTargetConfig> => {
- const config = $parseTargetConfig<TLinuxServerTargetConfig>(LinuxServerTargetConfigSchema, targetConfig);
+ ): Promise<TLinuxServerTargetConfig | TWindowsServerTargetConfig> => {
+ const hostType = HOST_DISCOVERY_TYPES[discoveryType];
+ const config = $parseTargetConfig<TLinuxServerTargetConfig | TWindowsServerTargetConfig>(
+ hostType.schema,
+ targetConfig
+ );
const alreadyValidated = new Set(existingConnectionIds);
const newConnectionIds = config.connectionIds.filter((connectionId) => !alreadyValidated.has(connectionId));
const limit = pLimit(CONNECTION_VALIDATION_CONCURRENCY);
const connections = await Promise.all(
newConnectionIds.map((connectionId) =>
limit(() =>
- appConnectionService.validateAppConnectionUsageById(AppConnection.SSH, { connectionId, projectId }, actor)
+ appConnectionService.validateAppConnectionUsageById(hostType.app, { connectionId, projectId }, actor)
)
)
);
+ if (
+ discoveryType === PkiDiscoveryType.WindowsServer &&
+ importsNothingFromWindowsStores(config as TWindowsServerTargetConfig)
+ ) {
+ throw new BadRequestError({
+ message:
+ "The Intermediate and Trusted Root stores only hold CA certificates. Turn on importStandaloneCaCertificates or select another store."
+ });
+ }
const connectionWithoutGateway = connections.find(
(connection) => !connection.gatewayId && !connection.gatewayPoolId
);
if (connectionWithoutGateway) {
- throw new BadRequestError({ message: sshConnectionWithoutGatewayMessage(connectionWithoutGateway.name) });
+ throw new BadRequestError({ message: hostType.withoutGatewayMessage(connectionWithoutGateway.name) });
}
return config;
};
const $assertJobGatewayAllowed = (discoveryType: PkiDiscoveryType, hasJobGateway: boolean) => {
- if (discoveryType !== PkiDiscoveryType.Network && hasJobGateway) {
+ if (isHostDiscoveryType(discoveryType) && hasJobGateway) {
+ const hostType = HOST_DISCOVERY_TYPES[discoveryType];
throw new BadRequestError({
- message:
- "Linux Server discovery uses the gateway of each SSH connection, so a gateway or gateway pool cannot be set on the job"
+ message: `${hostType.label} discovery uses the gateway of each ${hostType.connectionKind} connection, so a gateway or gateway pool cannot be set on the job`
});
}
};
@@ -164,7 +208,8 @@ export const pkiDiscoveryServiceFactory = ({
case PkiDiscoveryType.Network:
return $validateNetworkTarget(targetConfig, hasGateway);
case PkiDiscoveryType.LinuxServer:
- return $validateLinuxServerTarget(targetConfig, projectId, actor, existingConnectionIds);
+ case PkiDiscoveryType.WindowsServer:
+ return $validateHostTarget(discoveryType, targetConfig, projectId, actor, existingConnectionIds);
default:
throw new BadRequestError({ message: `Unsupported discovery type: ${discoveryType as string}` });
}
@@ -334,10 +379,9 @@ export const pkiDiscoveryServiceFactory = ({
$assertJobGatewayAllowed(discoveryType, Boolean(gatewayId || gatewayPoolId));
- const existingConnectionIds =
- discoveryType === PkiDiscoveryType.LinuxServer
- ? (discovery.targetConfig as TLinuxServerTargetConfig).connectionIds
- : undefined;
+ const existingConnectionIds = isHostDiscoveryType(discoveryType)
+ ? hostConnectionIds(discoveryType, discovery.targetConfig)
+ : undefined;
const validatedTargetConfig = targetConfig
? await $validateTarget({
@@ -446,10 +490,7 @@ export const pkiDiscoveryServiceFactory = ({
discoveries: T[],
orgId: string
) => {
- const connectionIdsOf = (discovery: T) =>
- discovery.discoveryType === PkiDiscoveryType.LinuxServer
- ? (discovery.targetConfig as TLinuxServerTargetConfig).connectionIds
- : [];
+ const connectionIdsOf = (discovery: T) => hostConnectionIds(discovery.discoveryType, discovery.targetConfig);
const connectionIds = [...new Set(discoveries.flatMap(connectionIdsOf))];
const rows = connectionIds.length ? await appConnectionDAL.find({ $in: { id: connectionIds }, orgId }) : [];
const connectionsById = new Map(
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-types.ts b/backend/src/ee/services/pki-discovery/pki-discovery-types.ts
index 25da2d47be..8cb2f960df 100644
--- a/backend/src/ee/services/pki-discovery/pki-discovery-types.ts
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-types.ts
@@ -2,11 +2,20 @@ import { z } from "zod";
import { OrgServiceActor, TProjectPermission } from "@app/lib/types";
-import type { LinuxServerTargetConfigSchema } from "./pki-discovery-schemas";
+import type { LinuxServerTargetConfigSchema, WindowsServerTargetConfigSchema } from "./pki-discovery-schemas";
export enum PkiDiscoveryType {
Network = "network",
- LinuxServer = "linux-server"
+ LinuxServer = "linux-server",
+ WindowsServer = "windows-server"
+}
+
+export enum WindowsCertificateStore {
+ Personal = "My",
+ WebHosting = "WebHosting",
+ RemoteDesktop = "Remote Desktop",
+ IntermediateCertificationAuthorities = "CA",
+ TrustedRootCertificationAuthorities = "Root"
}
export enum PkiKeystoreStatus {
@@ -41,7 +50,8 @@ export enum HostScanTruncationReason {
FileList = "fileList",
MaxFiles = "maxFiles",
ResponseSize = "responseSize",
- TimeLimit = "timeLimit"
+ TimeLimit = "timeLimit",
+ Incomplete = "incomplete"
}
export enum PkiKeystorePasswordChange {
@@ -99,7 +109,9 @@ export type TNetworkTargetConfig = {
export type TLinuxServerTargetConfig = z.infer<typeof LinuxServerTargetConfigSchema>;
-export type TPkiDiscoveryTargetConfig = TNetworkTargetConfig | TLinuxServerTargetConfig;
+export type TWindowsServerTargetConfig = z.infer<typeof WindowsServerTargetConfigSchema>;
+
+export type TPkiDiscoveryTargetConfig = TNetworkTargetConfig | TLinuxServerTargetConfig | TWindowsServerTargetConfig;
export type TPkiInstallationLocationDetails = {
ipAddress?: string;
@@ -112,6 +124,10 @@ export type TPkiInstallationLocationDetails = {
hostname?: string;
connectionId?: string;
format?: PkiCertificateFileFormat;
+ storeLocation?: string;
+ storeName?: WindowsCertificateStore;
+ thumbprint?: string;
+ hasPrivateKey?: boolean;
};
export type TPkiInstallationMetadata = {
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-windows-scan-fns.test.ts b/backend/src/ee/services/pki-discovery/pki-discovery-windows-scan-fns.test.ts
new file mode 100644
index 0000000000..f350c90485
--- /dev/null
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-windows-scan-fns.test.ts
@@ -0,0 +1,196 @@
+import { computeLocationFingerprint } from "./pki-discovery-fns";
+import { normalizeHostIdentifier } from "./pki-discovery-host-fns";
+import { importsNothingFromWindowsStores, WindowsServerTargetConfigSchema } from "./pki-discovery-schemas";
+import {
+ HostCertificateChainKind,
+ HostCertificateFileStatus,
+ HostScanTruncationReason,
+ PkiInstallationLocationType,
+ WindowsCertificateStore
+} from "./pki-discovery-types";
+import {
+ resolveStoreChains,
+ storeCertificatePath,
+ summarizeWindowsScanIssues,
+ WindowsCertificateScanResponseSchema
+} from "./pki-discovery-windows-scan-fns";
+
+describe("WindowsServerTargetConfigSchema", () => {
+ const connectionId = "4b6f2c1e-8a5d-4c3b-9e7f-1a2b3c4d5e6f";
+
+ test("defaults to the Personal and Web Hosting stores", () => {
+ const parsed = WindowsServerTargetConfigSchema.parse({ connectionIds: [connectionId] });
+ expect(parsed.certificateStores).toEqual([WindowsCertificateStore.Personal, WindowsCertificateStore.WebHosting]);
+ expect(parsed.importStandaloneCaCertificates).toBe(false);
+ });
+
+ test("rejects unknown stores, duplicates and Linux fields", () => {
+ expect(
+ WindowsServerTargetConfigSchema.safeParse({ connectionIds: [connectionId], certificateStores: ["TrustedPeople"] })
+ .success
+ ).toBe(false);
+ expect(
+ WindowsServerTargetConfigSchema.safeParse({
+ connectionIds: [connectionId],
+ certificateStores: [WindowsCertificateStore.Personal, WindowsCertificateStore.Personal]
+ }).success
+ ).toBe(false);
+ expect(
+ WindowsServerTargetConfigSchema.safeParse({ connectionIds: [connectionId], searchPaths: ["/etc/ssl"] }).success
+ ).toBe(false);
+ });
+});
+
+describe("importsNothingFromWindowsStores", () => {
+ test("flags CA-only store selections without CA import", () => {
+ const caOnly = [
+ WindowsCertificateStore.IntermediateCertificationAuthorities,
+ WindowsCertificateStore.TrustedRootCertificationAuthorities
+ ];
+ expect(importsNothingFromWindowsStores({ certificateStores: caOnly, importStandaloneCaCertificates: false })).toBe(
+ true
+ );
+ expect(importsNothingFromWindowsStores({ certificateStores: caOnly, importStandaloneCaCertificates: true })).toBe(
+ false
+ );
+ expect(
+ importsNothingFromWindowsStores({
+ certificateStores: [WindowsCertificateStore.Personal, ...caOnly],
+ importStandaloneCaCertificates: false
+ })
+ ).toBe(false);
+ });
+});
+
+describe("WindowsCertificateScanResponseSchema", () => {
+ test("accepts a gateway response with null lists", () => {
+ const parsed = WindowsCertificateScanResponseSchema.parse({
+ host: { hostname: "web-01" },
+ certificates: null,
+ deniedStores: null
+ });
+ expect(parsed.certificates ?? []).toHaveLength(0);
+ });
+
+ test("keeps the rest of the scan when a newer gateway sends an unknown status or chain kind", () => {
+ const parsed = WindowsCertificateScanResponseSchema.parse({
+ host: { hostname: "web-01" },
+ pool: ["MA=="],
+ certificates: [
+ {
+ store: WindowsCertificateStore.Personal,
+ thumbprint: "AA",
+ hasPrivateKey: false,
+ status: "someNewStatus",
+ chains: [{ kind: "someNewKind", indexes: [0] }]
+ }
+ ]
+ });
+ expect(parsed.certificates?.[0].status).toBe(HostCertificateFileStatus.ReadFailed);
+ expect(parsed.certificates?.[0].chains?.[0].kind).toBe(HostCertificateChainKind.Ca);
+ });
+});
+
+describe("resolveStoreChains", () => {
+ const pool = [Buffer.from("leaf"), Buffer.from("issuer")];
+ const cert = (chains: { kind: HostCertificateChainKind; indexes: number[] }[]) => ({
+ store: WindowsCertificateStore.Personal,
+ thumbprint: "AA",
+ hasPrivateKey: true,
+ status: HostCertificateFileStatus.Ok,
+ chains
+ });
+
+ test("maps pool indexes to certificates, leaf first", () => {
+ expect(resolveStoreChains(cert([{ kind: HostCertificateChainKind.Leaf, indexes: [0, 1] }]), pool, false)).toEqual([
+ [pool[0], pool[1]]
+ ]);
+ });
+
+ test("skips CA chains unless CA certificates are included, and drops out-of-range indexes", () => {
+ expect(resolveStoreChains(cert([{ kind: HostCertificateChainKind.Ca, indexes: [1] }]), pool, false)).toEqual([]);
+ expect(resolveStoreChains(cert([{ kind: HostCertificateChainKind.Ca, indexes: [1] }]), pool, true)).toHaveLength(1);
+ expect(resolveStoreChains(cert([{ kind: HostCertificateChainKind.Leaf, indexes: [0, 7] }]), pool, true)).toEqual(
+ []
+ );
+ });
+});
+
+describe("Windows store installation identity", () => {
+ test("omits the default WinRM port from the host identifier", () => {
+ expect(normalizeHostIdentifier("WEB-01.corp.local", 5985, 5985)).toBe("web-01.corp.local");
+ expect(normalizeHostIdentifier("web-01.corp.local", 5986, 5985)).toBe("web-01.corp.local:5986");
+ expect(normalizeHostIdentifier("web-01.corp.local", 5986, 5986)).toBe("web-01.corp.local");
+ });
+
+ test("differs per store and per thumbprint", () => {
+ const fingerprint = (store: string, thumbprint: string) =>
+ computeLocationFingerprint(
+ PkiInstallationLocationType.OsStore,
+ { hostIdentifier: "web-01", filePath: storeCertificatePath(store, thumbprint) },
+ "gw"
+ );
+ expect(storeCertificatePath("My", "AB12")).toBe("Cert:\\LocalMachine\\My\\AB12");
+ expect(fingerprint("My", "AB12")).not.toBe(fingerprint("WebHosting", "AB12"));
+ expect(fingerprint("My", "AB12")).not.toBe(fingerprint("My", "CD34"));
+ });
+});
+
+describe("summarizeWindowsScanIssues", () => {
+ test("names denied stores, unreadable certificates and truncation", () => {
+ const issues = summarizeWindowsScanIssues("web-01", {
+ host: { hostname: "web-01" },
+ deniedStores: [WindowsCertificateStore.WebHosting],
+ certificates: [
+ {
+ store: WindowsCertificateStore.Personal,
+ thumbprint: "AA",
+ hasPrivateKey: true,
+ status: HostCertificateFileStatus.ParseError,
+ chains: []
+ },
+ {
+ store: WindowsCertificateStore.Personal,
+ thumbprint: "BB",
+ hasPrivateKey: false,
+ status: HostCertificateFileStatus.Ok,
+ chains: [{ kind: HostCertificateChainKind.Leaf, indexes: [0] }]
+ }
+ ],
+ truncatedReason: HostScanTruncationReason.MaxFiles
+ });
+ expect(issues).toEqual([
+ "web-01: The connection's user can't open these certificate stores: Web Hosting",
+ "web-01: These certificates could not be read: Personal (AA)",
+ "web-01: The scan stopped after 5,000 certificates"
+ ]);
+ });
+
+ test("tells the user to select fewer stores when the response was too large", () => {
+ expect(
+ summarizeWindowsScanIssues("web-01", {
+ host: { hostname: "web-01" },
+ certificates: [],
+ truncatedReason: HostScanTruncationReason.ResponseSize
+ })
+ ).toEqual(["web-01: The scan found more certificates than one scan can return. Select fewer certificate stores."]);
+ });
+
+ test("warns when an issuer store couldn't be opened and when the scan ran out of time", () => {
+ expect(
+ summarizeWindowsScanIssues("web-01", {
+ host: { hostname: "web-01" },
+ certificates: [],
+ unreadableIssuerStores: [WindowsCertificateStore.TrustedRootCertificationAuthorities],
+ truncatedReason: HostScanTruncationReason.TimeLimit
+ })
+ ).toEqual([
+ "web-01: The connection's user can't open Trusted Root Certification Authorities, so some certificate chains may be incomplete",
+ "web-01: The scan ran out of time, so some certificates were not checked. Select fewer certificate stores."
+ ]);
+ });
+
+ test("reports nothing for a clean scan", () => {
+ expect(summarizeWindowsScanIssues("web-01", { host: { hostname: "web-01" }, certificates: [] })).toEqual([]);
+ });
+});
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-windows-scan-fns.ts b/backend/src/ee/services/pki-discovery/pki-discovery-windows-scan-fns.ts
new file mode 100644
index 0000000000..5dfce135ea
--- /dev/null
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-windows-scan-fns.ts
@@ -0,0 +1,422 @@
+import net from "net";
+import { z } from "zod";
+
+import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";
+import { BadRequestError, GatewayTransportError, NotFoundError } from "@app/lib/errors";
+import { getMissingGatewayMessage } from "@app/lib/gateway-v2/gateway-errors";
+import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
+import {
+ callWinRmEndpoint,
+ WINRM_RPC_RESPONSE_TOO_LARGE_STATUS,
+ WinRmRpcEndpoint,
+ WinRmRpcResponse
+} from "@app/lib/gateway-v2/winrm-rpc";
+import { logger } from "@app/lib/logger";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import { decryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";
+import { TWinRMCredentials } from "@app/services/app-connection/winrm/winrm-connection-fns";
+
+import { computeLocationFingerprint } from "./pki-discovery-fns";
+import {
+ buildHostInstallationName,
+ normalizeHostIdentifier,
+ windowsConnectionWithoutGatewayMessage
+} from "./pki-discovery-host-fns";
+import {
+ executeHostScan,
+ HostScanCapability,
+ importCertificateChains,
+ selectScanGateway,
+ TAppConnectionRow,
+ THostScanDeps,
+ THostScanOutcome,
+ THostScanRun,
+ toHostScanErrorMessage,
+ TScanGateway,
+ TWriteContext,
+ upsertInstallationWithLinks,
+ withConnectionScanSlot
+} from "./pki-discovery-host-scan-fns";
+import {
+ HostCertificateChainKind,
+ HostCertificateFileStatus,
+ HostScanTruncationReason,
+ PkiDiscoveryType,
+ PkiInstallationLocationType,
+ TPkiInstallationLocationDetails,
+ TWindowsServerTargetConfig,
+ WindowsCertificateStore
+} from "./pki-discovery-types";
+
+const WINDOWS_STORE_LOCATION = "LocalMachine";
+const WINDOWS_CONNECTION_KIND = "Windows (WinRM)";
+const MAX_WINDOWS_SCAN_RESPONSE_BYTES = 24 * 1024 * 1024;
+const DEFAULT_WINRM_HTTP_PORT = 5985;
+const DEFAULT_WINRM_HTTPS_PORT = 5986;
+const MAX_WINDOWS_SCAN_CERTIFICATES = 5000;
+
+const WindowsStoreCertificateSchema = z.object({
+ store: z.string().max(64),
+ thumbprint: z.string().max(128),
+ hasPrivateKey: z.boolean(),
+ status: z.nativeEnum(HostCertificateFileStatus).catch(HostCertificateFileStatus.ReadFailed),
+ chains: z
+ .array(
+ z.object({
+ kind: z.nativeEnum(HostCertificateChainKind).catch(HostCertificateChainKind.Ca),
+ indexes: z.array(z.number().int().nonnegative())
+ })
+ )
+ .nullish()
+});
+
+export const WindowsCertificateScanResponseSchema = z.object({
+ host: z.object({ hostname: z.string().max(255).optional().default("") }),
+ pool: z.array(z.string()).nullish(),
+ certificates: z.array(WindowsStoreCertificateSchema).nullish(),
+ deniedStores: z.array(z.string()).nullish(),
+ unreadableIssuerStores: z.array(z.string()).nullish(),
+ truncatedReason: z.string().max(64).optional()
+});
+
+export type TWindowsCertificateScanResponse = z.infer<typeof WindowsCertificateScanResponseSchema>;
+type TWindowsStoreCertificate = z.infer<typeof WindowsStoreCertificateSchema>;
+
+type TResolvedWindowsHost = TScanGateway & {
+ connectionId: string;
+ hostIdentifier: string;
+ hostAddress: string;
+ targetHost: string;
+ targetPort: number;
+ credentials: TWinRMCredentials;
+};
+
+type TScannedWindowsHost = TResolvedWindowsHost & { hostname: string };
+
+export const resolveWindowsHost = async (
+ connection: TAppConnectionRow | undefined,
+ orgId: string,
+ deps: THostScanDeps
+): Promise<TResolvedWindowsHost> => {
+ if (!connection || connection.orgId !== orgId || connection.app !== AppConnection.WinRM) {
+ throw new BadRequestError({ message: "The Windows (WinRM) connection no longer exists" });
+ }
+ if (!connection.gatewayId && !connection.gatewayPoolId) {
+ throw new BadRequestError({ message: windowsConnectionWithoutGatewayMessage(connection.name) });
+ }
+
+ const credentials = (await decryptAppConnectionCredentials({
+ orgId: connection.orgId,
+ encryptedCredentials: connection.encryptedCredentials,
+ kmsService: deps.kmsService,
+ projectId: connection.projectId
+ })) as TWinRMCredentials;
+
+ const gateway = await selectScanGateway(
+ connection,
+ HostScanCapability.WindowsCertificateScan,
+ WINDOWS_CONNECTION_KIND,
+ deps
+ );
+
+ const [targetHost] = await verifyHostInputValidity({
+ host: credentials.host,
+ isGateway: true,
+ isDynamicSecret: false
+ });
+
+ return {
+ ...gateway,
+ connectionId: connection.id,
+ hostIdentifier: normalizeHostIdentifier(
+ credentials.host,
+ credentials.port,
+ credentials.sslEnabled ? DEFAULT_WINRM_HTTPS_PORT : DEFAULT_WINRM_HTTP_PORT
+ ),
+ hostAddress: credentials.host.trim().toLowerCase(),
+ targetHost,
+ targetPort: credentials.port,
+ credentials
+ };
+};
+
+const describeWindowsScanFailure = (
+ failure: Extract<WinRmRpcResponse<unknown>, { ok: false }>,
+ gatewayName: string
+): string => {
+ if (failure.status === 404) {
+ return `Gateway '${gatewayName}' is too old for certificate scanning. Update it to the latest version.`;
+ }
+ if (failure.status === WINRM_RPC_RESPONSE_TOO_LARGE_STATUS) {
+ return "The scan returned more certificates than one scan can hold. Select fewer certificate stores.";
+ }
+ if (failure.status === 503) {
+ return "The gateway is busy with other certificate scans. Try again later.";
+ }
+ if (failure.kind === "auth") {
+ return "The Windows host rejected the connection's credentials. Check the username and password on the connection.";
+ }
+ if (failure.kind === "transport") {
+ return "The gateway could not reach the Windows host over WinRM. Check the host, port and WinRM listener.";
+ }
+ return "The gateway could not read the certificate stores on the Windows host. Check the gateway logs for details.";
+};
+
+const runWindowsCertificateScan = async (
+ host: TResolvedWindowsHost,
+ stores: WindowsCertificateStore[],
+ deps: THostScanDeps
+): Promise<TWindowsCertificateScanResponse> => {
+ const connectionDetails = await deps.gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
+ gatewayId: host.gatewayId,
+ targetHost: host.targetHost,
+ targetPort: host.targetPort
+ });
+ if (!connectionDetails) {
+ throw new NotFoundError({ message: getMissingGatewayMessage(host.gatewayId) });
+ }
+
+ const { credentials } = host;
+ let response: WinRmRpcResponse<unknown>;
+ try {
+ response = await withGatewayV2Proxy(
+ (port) =>
+ callWinRmEndpoint<unknown>({
+ port,
+ endpoint: WinRmRpcEndpoint.ScanCertificates,
+ maxResponseBytes: MAX_WINDOWS_SCAN_RESPONSE_BYTES,
+ body: {
+ username: credentials.username,
+ password: credentials.password,
+ params: {
+ useHttps: credentials.sslEnabled ?? false,
+ insecure: credentials.sslEnabled ? credentials.sslRejectUnauthorized === false : false,
+ ...(credentials.sslEnabled && credentials.sslCertificate
+ ? { caCertificate: credentials.sslCertificate }
+ : {}),
+ stores,
+ maxCertificates: MAX_WINDOWS_SCAN_CERTIFICATES
+ }
+ }
+ }),
+ { protocol: GatewayProxyProtocol.WinRm, longLived: true, ...connectionDetails }
+ );
+ } catch (error) {
+ if (error instanceof GatewayTransportError) throw error;
+ const message = error instanceof Error ? error.message : String(error);
+ logger.warn(
+ `Windows certificate scan transport failed [connectionId=${host.connectionId}] [gatewayId=${host.gatewayId}] [error=${message}]`
+ );
+ throw new BadRequestError({
+ message:
+ "The connection to the gateway dropped during the scan. Check that the gateway and its relay are running, then try again."
+ });
+ }
+
+ if (!response.ok) {
+ logger.warn(
+ { errorMessage: response.errorMessage },
+ `Windows certificate scan RPC failed [connectionId=${host.connectionId}] [gatewayId=${host.gatewayId}] [status=${response.status}] [kind=${response.kind ?? "none"}]`
+ );
+ throw new BadRequestError({ message: describeWindowsScanFailure(response, host.gatewayName) });
+ }
+
+ const parsed = WindowsCertificateScanResponseSchema.safeParse(response.result);
+ if (!parsed.success) {
+ logger.warn(
+ { issues: parsed.error.issues },
+ `Windows certificate scan result did not match the expected shape [connectionId=${host.connectionId}]`
+ );
+ throw new BadRequestError({ message: "The gateway returned a scan result that could not be read" });
+ }
+ return parsed.data;
+};
+
+export const storeCertificatePath = (store: string, thumbprint: string) =>
+ `Cert:\\${WINDOWS_STORE_LOCATION}\\${store}\\${thumbprint}`;
+
+const buildStoreLocationDetails = (
+ host: TScannedWindowsHost,
+ cert: TWindowsStoreCertificate,
+ store: WindowsCertificateStore
+): TPkiInstallationLocationDetails => ({
+ hostIdentifier: host.hostIdentifier,
+ connectionId: host.connectionId,
+ ...(net.isIP(host.hostAddress) !== 0 && { ipAddress: host.hostAddress }),
+ ...(host.hostname && { hostname: host.hostname }),
+ storeLocation: WINDOWS_STORE_LOCATION,
+ storeName: store,
+ thumbprint: cert.thumbprint,
+ hasPrivateKey: cert.hasPrivateKey,
+ gatewayName: host.gatewayName
+});
+
+const isWindowsCertificateStore = (store: string): store is WindowsCertificateStore =>
+ (Object.values(WindowsCertificateStore) as string[]).includes(store);
+
+export const resolveStoreChains = (cert: TWindowsStoreCertificate, pool: Buffer[], importStandaloneCa: boolean) =>
+ (cert.chains ?? [])
+ .filter((chain) => chain.kind === HostCertificateChainKind.Leaf || importStandaloneCa)
+ .filter((chain) => chain.indexes.length > 0 && chain.indexes.every((idx) => idx < pool.length))
+ .map((chain) => chain.indexes.map((idx) => pool[idx]));
+
+export const writeStoreCertificate = async (
+ host: TScannedWindowsHost,
+ cert: TWindowsStoreCertificate,
+ pool: Buffer[],
+ ctx: TWriteContext,
+ deps: THostScanDeps
+): Promise<{ installationId?: string; certificateIds: string[] }> => {
+ if (cert.status !== HostCertificateFileStatus.Ok || !isWindowsCertificateStore(cert.store)) {
+ return { certificateIds: [] };
+ }
+ const chains = resolveStoreChains(cert, pool, ctx.importStandaloneCaCertificates);
+ if (chains.length === 0) return { certificateIds: [] };
+
+ const path = storeCertificatePath(cert.store, cert.thumbprint);
+ const fingerprint = computeLocationFingerprint(
+ PkiInstallationLocationType.OsStore,
+ { hostIdentifier: host.hostIdentifier, filePath: path },
+ host.fingerprintGatewayKey
+ );
+
+ const certificateIds = await importCertificateChains(
+ chains,
+ {
+ hostIdentifier: host.hostIdentifier,
+ hostname: host.hostname,
+ storeLocation: WINDOWS_STORE_LOCATION,
+ storeName: cert.store,
+ thumbprint: cert.thumbprint
+ },
+ ctx,
+ deps
+ );
+
+ const installationId = await upsertInstallationWithLinks(
+ {
+ fingerprint,
+ locationType: PkiInstallationLocationType.OsStore,
+ locationDetails: buildStoreLocationDetails(host, cert, cert.store),
+ name: buildHostInstallationName(host.hostIdentifier, host.hostname, path),
+ certificateIds,
+ refreshOnly: false
+ },
+ ctx,
+ deps
+ );
+ return { installationId, certificateIds };
+};
+
+const MAX_LISTED_UNREADABLE = 5;
+
+const STORE_NAMES: Record<string, string> = {
+ [WindowsCertificateStore.Personal]: "Personal",
+ [WindowsCertificateStore.WebHosting]: "Web Hosting",
+ [WindowsCertificateStore.RemoteDesktop]: "Remote Desktop",
+ [WindowsCertificateStore.IntermediateCertificationAuthorities]: "Intermediate Certification Authorities",
+ [WindowsCertificateStore.TrustedRootCertificationAuthorities]: "Trusted Root Certification Authorities"
+};
+
+export const summarizeWindowsScanIssues = (
+ hostIdentifier: string,
+ response: TWindowsCertificateScanResponse
+): string[] => {
+ const issues: string[] = [];
+ const denied = response.deniedStores ?? [];
+ if (denied.length > 0) {
+ issues.push(
+ `${hostIdentifier}: The connection's user can't open these certificate stores: ${denied
+ .map((store) => STORE_NAMES[store] ?? store)
+ .join(", ")}`
+ );
+ }
+ const unreadable = (response.certificates ?? []).filter((cert) => cert.status !== HostCertificateFileStatus.Ok);
+ if (unreadable.length > 0) {
+ const listed = unreadable
+ .slice(0, MAX_LISTED_UNREADABLE)
+ .map((cert) => `${STORE_NAMES[cert.store] ?? cert.store} (${cert.thumbprint})`);
+ const more = unreadable.length - listed.length;
+ issues.push(
+ `${hostIdentifier}: These certificates could not be read: ${listed.join(", ")}${more > 0 ? ` and ${more} more` : ""}`
+ );
+ }
+ const unreadableIssuers = response.unreadableIssuerStores ?? [];
+ if (unreadableIssuers.length > 0) {
+ issues.push(
+ `${hostIdentifier}: The connection's user can't open ${unreadableIssuers
+ .map((store) => STORE_NAMES[store] ?? store)
+ .join(", ")}, so some certificate chains may be incomplete`
+ );
+ }
+ if (response.truncatedReason === HostScanTruncationReason.MaxFiles) {
+ issues.push(
+ `${hostIdentifier}: The scan stopped after ${MAX_WINDOWS_SCAN_CERTIFICATES.toLocaleString("en-US")} certificates`
+ );
+ } else if (response.truncatedReason === HostScanTruncationReason.TimeLimit) {
+ issues.push(
+ `${hostIdentifier}: The scan ran out of time, so some certificates were not checked. Select fewer certificate stores.`
+ );
+ } else if (response.truncatedReason === HostScanTruncationReason.ResponseSize) {
+ issues.push(
+ `${hostIdentifier}: The scan found more certificates than one scan can return. Select fewer certificate stores.`
+ );
+ } else if (response.truncatedReason) {
+ issues.push(`${hostIdentifier}: The scan stopped early, so some certificates were not checked`);
+ }
+ return issues;
+};
+
+const scanWindowsConnection = async (
+ connection: TAppConnectionRow | undefined,
+ label: string,
+ run: THostScanRun<TWindowsServerTargetConfig>,
+ deps: THostScanDeps
+): Promise<THostScanOutcome> => {
+ let hostLabel = label;
+ const issues: string[] = [];
+ try {
+ const host = await resolveWindowsHost(connection, run.orgId, deps);
+ hostLabel = host.hostIdentifier;
+ const response = await withConnectionScanSlot(host.connectionId, WINDOWS_CONNECTION_KIND, deps, () =>
+ runWindowsCertificateScan(host, run.targetConfig.certificateStores, deps)
+ );
+ issues.push(...summarizeWindowsScanIssues(host.hostIdentifier, response));
+
+ const scannedHost = { ...host, hostname: response.host.hostname };
+ const pool = (response.pool ?? []).map((der) => Buffer.from(der, "base64"));
+ await run.writeLimit(async () => {
+ for (const cert of response.certificates ?? []) {
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ const result = await writeStoreCertificate(scannedHost, cert, pool, run.ctx, deps);
+ if (result.installationId) run.installationIds.add(result.installationId);
+ result.certificateIds.forEach((id) => run.certificateIds.add(id));
+ } catch (error) {
+ const message = toHostScanErrorMessage(
+ error,
+ `Windows Server discovery certificate import failed [discoveryId=${run.discoveryId}] [host=${host.hostIdentifier}] [store=${cert.store}] [thumbprint=${cert.thumbprint}]`
+ );
+ issues.push(
+ `${host.hostIdentifier} (${STORE_NAMES[cert.store] ?? cert.store} ${cert.thumbprint}): ${message}`
+ );
+ }
+ }
+ });
+ return { issues };
+ } catch (error) {
+ const message = toHostScanErrorMessage(
+ error,
+ `Windows Server discovery host failed [discoveryId=${run.discoveryId}] [connection=${label}]`
+ );
+ return { issues, failure: { label: hostLabel, message } };
+ }
+};
+
+export const executeWindowsServerScan = (discoveryId: string, deps: THostScanDeps): Promise<void> =>
+ executeHostScan<TWindowsServerTargetConfig>(
+ discoveryId,
+ { discoveryType: PkiDiscoveryType.WindowsServer, label: "Windows Server", scanConnection: scanWindowsConnection },
+ deps
+ );
diff --git a/backend/src/lib/gateway-v2/gateway-rpc.ts b/backend/src/lib/gateway-v2/gateway-rpc.ts
index 1c20f1b9a6..263c64acf1 100644
--- a/backend/src/lib/gateway-v2/gateway-rpc.ts
+++ b/backend/src/lib/gateway-v2/gateway-rpc.ts
@@ -4,6 +4,8 @@ import { logger } from "@app/lib/logger";
export type GatewayRpcRawResponse = { status: number; text: string };
+export class GatewayRpcResponseTooLargeError extends Error {}
+
// shared transport for the gateway RPCs sent over the local relay proxy
export const postGatewayRpc = (args: {
port: number;
@@ -47,7 +49,9 @@ export const postGatewayRpc = (args: {
received += chunk.length;
if (maxResponseBytes !== undefined && received > maxResponseBytes) {
req.destroy();
- finish(() => reject(new Error(`${label} RPC response exceeded ${maxResponseBytes} bytes`)));
+ finish(() =>
+ reject(new GatewayRpcResponseTooLargeError(`${label} RPC response exceeded ${maxResponseBytes} bytes`))
+ );
return;
}
chunks.push(chunk);
diff --git a/backend/src/lib/gateway-v2/winrm-rpc.ts b/backend/src/lib/gateway-v2/winrm-rpc.ts
index f2717736b7..2aec064eb5 100644
--- a/backend/src/lib/gateway-v2/winrm-rpc.ts
+++ b/backend/src/lib/gateway-v2/winrm-rpc.ts
@@ -1,4 +1,4 @@
-import { postGatewayRpc } from "./gateway-rpc";
+import { GatewayRpcResponseTooLargeError, postGatewayRpc } from "./gateway-rpc";
import { GatewayFailureKind } from "./test-connection-rpc";
export enum WinRmRpcEndpoint {
@@ -10,7 +10,8 @@ export enum WinRmRpcEndpoint {
EnumerateDependencies = "/v1/enumerate-dependencies",
RotateCredential = "/v1/rotate-credential",
SyncDependency = "/v1/sync-dependency",
- ValidateCredential = "/v1/validate-credential"
+ ValidateCredential = "/v1/validate-credential",
+ ScanCertificates = "/v1/scan-certificates"
}
export type WinRmTransportParams = {
@@ -51,20 +52,32 @@ export const WINRM_RPC_TIMEOUT_MS = 150_000;
const MAX_WINRM_RPC_RESPONSE_BYTES = 1024 * 1024;
+export const WINRM_RPC_RESPONSE_TOO_LARGE_STATUS = 413;
+
export const callWinRmEndpoint = async <T>(args: {
port: number;
endpoint: WinRmRpcEndpoint;
body: WinRmRpcRequestBody;
+ maxResponseBytes?: number;
}): Promise<WinRmRpcResponse<T>> => {
- const { status, text } = await postGatewayRpc({
- port: args.port,
- path: args.endpoint,
- payload: JSON.stringify(args.body),
- timeoutMs: WINRM_RPC_TIMEOUT_MS,
- deadlineMs: WINRM_RPC_TIMEOUT_MS,
- maxResponseBytes: MAX_WINRM_RPC_RESPONSE_BYTES,
- label: "WinRM"
- });
+ let raw: Awaited<ReturnType<typeof postGatewayRpc>>;
+ try {
+ raw = await postGatewayRpc({
+ port: args.port,
+ path: args.endpoint,
+ payload: JSON.stringify(args.body),
+ timeoutMs: WINRM_RPC_TIMEOUT_MS,
+ deadlineMs: WINRM_RPC_TIMEOUT_MS,
+ maxResponseBytes: args.maxResponseBytes ?? MAX_WINRM_RPC_RESPONSE_BYTES,
+ label: "WinRM"
+ });
+ } catch (error) {
+ if (error instanceof GatewayRpcResponseTooLargeError) {
+ return { ok: false, status: WINRM_RPC_RESPONSE_TOO_LARGE_STATUS, errorMessage: error.message, kind: null };
+ }
+ throw error;
+ }
+ const { status, text } = raw;
if (!text) {
return { ok: false, status, errorMessage: `Empty response body from Gateway (status ${status})` };
diff --git a/docs/docs.json b/docs/docs.json
index be2170dc18..0f3278965a 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -563,7 +563,8 @@
"root": "documentation/platform/pki/discovery/overview",
"pages": [
"documentation/platform/pki/discovery/network",
- "documentation/platform/pki/discovery/linux-server"
+ "documentation/platform/pki/discovery/linux-server",
+ "documentation/platform/pki/discovery/windows-server"
]
},
{
diff --git a/docs/documentation/platform/pki/discovery/overview.mdx b/docs/documentation/platform/pki/discovery/overview.mdx
index 64429f523c..361603e766 100644
--- a/docs/documentation/platform/pki/discovery/overview.mdx
+++ b/docs/documentation/platform/pki/discovery/overview.mdx
@@ -17,6 +17,9 @@ Discovery jobs scan your infrastructure and organize results as **installations*
<Card title="Linux Server" icon="terminal" href="/documentation/platform/pki/discovery/linux-server">
Find the certificates stored in files and keystores on your Linux servers, through an SSH connection and a gateway.
</Card>
+ <Card title="Windows Server" icon="monitor" href="/documentation/platform/pki/discovery/windows-server">
+ Find the certificates in the Windows certificate store on your Windows servers, through a WinRM connection and a gateway.
+ </Card>
</CardGroup>
## Installations
@@ -55,6 +58,9 @@ Discovered certificates are matched to your existing inventory by fingerprint. I
<Card title="Linux Server" icon="terminal" href="/documentation/platform/pki/discovery/linux-server">
Find certificate files and keystores on Linux servers.
</Card>
+ <Card title="Windows Server" icon="monitor" href="/documentation/platform/pki/discovery/windows-server">
+ Find certificates in the Windows certificate store.
+ </Card>
<Card title="Applications" icon="layout-grid" href="/documentation/platform/pki/applications/overview">
Issue and manage certificates for your services.
</Card>
diff --git a/docs/documentation/platform/pki/discovery/windows-server.mdx b/docs/documentation/platform/pki/discovery/windows-server.mdx
new file mode 100644
index 0000000000..fbc09bbdd0
--- /dev/null
+++ b/docs/documentation/platform/pki/discovery/windows-server.mdx
@@ -0,0 +1,84 @@
+---
+title: "Windows Server"
+description: "Find the certificates in the Windows certificate store on your Windows servers."
+---
+
+Windows Server discovery finds the certificates in the Local Machine certificate store on your Windows servers, such as the certificates that IIS, Remote Desktop, and SQL Server use. Scans reach each server through a [Windows (WinRM) connection](/integrations/app-connections/winrm) that uses an [Infisical Gateway](/documentation/platform/gateways/overview). Private keys aren't read or imported.
+
+## Prerequisites
+
+- A [gateway](/documentation/platform/gateways/overview) running the latest version, deployed where it can reach your servers over WinRM
+- A [Windows (WinRM) connection](/integrations/app-connections/winrm) for each server, configured to use a gateway or a [gateway pool](/documentation/platform/gateways/gateway-pools)
+- A Windows account for the connection that can open a WinRM session on each server, such as a member of the **Remote Management Users** group
+
+## Certificate stores
+
+Each certificate becomes an installation named after the server's hostname and the certificate's store path, for example `web-01:Cert:\LocalMachine\My\3A1F...`.
+
+You choose which stores to scan:
+
+| Store | Scanned by default | What it holds |
+| --- | --- | --- |
+| Personal | Yes | Server certificates for IIS, Remote Desktop, SQL Server, and most other applications |
+| Web Hosting | Yes | Certificates added for IIS sites |
+| Remote Desktop | No | The certificate Remote Desktop uses on the server |
+| Intermediate Certification Authorities | No | Intermediate CA certificates |
+| Trusted Root Certification Authorities | No | Root CAs the server trusts, including the public ones built into Windows |
+
+A leaf certificate is imported with its chain, built from the intermediate and root certificates on the server. CA certificates found on their own, such as the certificates in the two certification authority stores, are skipped unless you turn on **Include CA certificates**.
+
+If the connection's account can't open a store, the scan completes and the job lists the stores it couldn't open.
+
+## Create a Windows Server discovery job
+
+<Tabs>
+ <Tab title="Infisical UI">
+ <Steps>
+ <Step>
+ In **Certificate Manager**, go to **Discovery** and select **Add Job**, then select **Windows Server**.
+ </Step>
+ <Step>
+ In **Windows (WinRM) Connections**, select the connection for each server to scan.
+ </Step>
+ <Step>
+ In **Certificate Stores**, select the stores to scan. To also import CA certificates found on their own, turn on **Include CA certificates**.
+ </Step>
+ <Step>
+ Enter a **Name** and an optional **Description**. To run the job on a schedule, turn on **Scan on a Schedule** and pick a **Scan Interval**.
+ </Step>
+ <Step>
+ Review the job and select **Create Job**.
+ </Step>
+ <Step>
+ Open the job and select **Trigger Scan**, or wait for the next scheduled scan.
+ </Step>
+ </Steps>
+ </Tab>
+ <Tab title="API">
+ To create the job, call [the endpoint that creates a discovery job](/api-reference/endpoints/pki-discovery/create) with `discoveryType` set to `windows-server`. Set `certificateStores` to any of `My`, `WebHosting`, `Remote Desktop`, `CA`, and `Root` (defaults to `My` and `WebHosting`).
+
+ To start a scan, call [the endpoint that triggers a scan](/api-reference/endpoints/pki-discovery/trigger-scan).
+ </Tab>
+</Tabs>
+
+## FAQ
+
+<AccordionGroup>
+ <Accordion title="Why does the job show a warning after a scan?">
+ The scan completed, but some stores or certificates couldn't be read, or the scan stopped early. The job lists what happened. If a store couldn't be opened, check that the connection's account can read it on the server. If the scan stopped after 5,000 certificates, or found more certificates than one scan can return, select fewer stores.
+ </Accordion>
+ <Accordion title="Does the scan read files on disk, such as PFX files?">
+ No. Windows Server discovery only reads the certificate store.
+ </Accordion>
+</AccordionGroup>
+
+## What's next?
+
+<CardGroup cols={2}>
+ <Card title="Discovery overview" icon="radar" href="/documentation/platform/pki/discovery/overview">
+ Learn how installations and certificate matching work.
+ </Card>
+ <Card title="Linux Server" icon="terminal" href="/documentation/platform/pki/discovery/linux-server">
+ Find certificate files and keystores on Linux servers.
+ </Card>
+</CardGroup>
diff --git a/docs/integrations/app-connections/winrm.mdx b/docs/integrations/app-connections/winrm.mdx
index d8eb85ffc5..b53845de48 100644
--- a/docs/integrations/app-connections/winrm.mdx
+++ b/docs/integrations/app-connections/winrm.mdx
@@ -4,7 +4,7 @@ sidebarTitle: "Windows (WinRM)"
description: "Learn how to configure a Windows (WinRM) Connection for Infisical."
---
-Infisical supports connecting to Windows hosts over WinRM to deliver certificates. The connection always routes through an [Infisical Gateway](/documentation/platform/gateways/overview) inside your network, which reaches the host and runs the WinRM session on Infisical's behalf. By default it uses HTTP with NTLM message encryption, which keeps the certificate and key confidential without a server certificate. HTTPS is also supported.
+Infisical supports connecting to Windows hosts over WinRM to deliver certificates and to discover the certificates already installed on them. The connection always routes through an [Infisical Gateway](/documentation/platform/gateways/overview) inside your network, which reaches the host and runs the WinRM session on Infisical's behalf. By default it uses HTTP with NTLM message encryption, which keeps the certificate and key confidential without a server certificate. HTTPS is also supported.
## Setup
@@ -20,7 +20,7 @@ Infisical supports connecting to Windows hosts over WinRM to deliver certificate
- **Password**: The account password.
<Note>
- The account must be able to open a WinRM session and write to the destination directory used by the certificate sync. HTTP with NTLM message encryption works against the default WinRM listener with no extra setup. HTTPS additionally requires a WinRM HTTPS listener on the host.
+ The account must be able to open a WinRM session, for example as a member of the **Remote Management Users** group. A certificate sync also needs write access to its destination directory. Certificate discovery only reads the certificate stores. HTTP with NTLM message encryption works against the default WinRM listener with no extra setup. HTTPS additionally requires a WinRM HTTPS listener on the host.
</Note>
</Step>
<Step title="Navigate to App Connections">
@@ -42,7 +42,7 @@ Infisical supports connecting to Windows hosts over WinRM to deliver certificate
Click **Connect to Windows (WinRM)** to validate and save your connection.
</Step>
<Step title="Connection Created">
- Your Windows (WinRM) Connection is now available for use with the [Windows Server Certificate Sync](/documentation/platform/pki/applications/certificate-syncs/windows-server).
+ Your Windows (WinRM) Connection is now available for use with the [Windows Server Certificate Sync](/documentation/platform/pki/applications/certificate-syncs/windows-server) and [Windows Server certificate discovery](/documentation/platform/pki/discovery/windows-server).
</Step>
</Steps>
</Tab>
diff --git a/frontend/src/helpers/pkiDiscovery.ts b/frontend/src/helpers/pkiDiscovery.ts
index 1bb54457e1..031931a9bb 100644
--- a/frontend/src/helpers/pkiDiscovery.ts
+++ b/frontend/src/helpers/pkiDiscovery.ts
@@ -1,4 +1,4 @@
-import { PkiDiscoveryType } from "@app/hooks/api/pkiDiscovery/types";
+import { PkiDiscoveryType, WindowsCertificateStore } from "@app/hooks/api/pkiDiscovery/types";
export const PKI_DISCOVERY_TYPE_MAP: Record<
PkiDiscoveryType,
@@ -14,9 +14,20 @@ export const PKI_DISCOVERY_TYPE_MAP: Record<
category: "Infrastructure",
description: "Log in over SSH and read the certificate files on a Linux server.",
image: "SSH.png"
+ },
+ [PkiDiscoveryType.WindowsServer]: {
+ name: "Windows Server",
+ category: "Infrastructure",
+ description: "Connect over WinRM and read the certificates in the Windows certificate store.",
+ image: "Windows.png"
}
};
+export const DEFAULT_WINDOWS_CERTIFICATE_STORES = [
+ WindowsCertificateStore.Personal,
+ WindowsCertificateStore.WebHosting
+];
+
export const DEFAULT_LINUX_SEARCH_FOLDERS = [
"/etc/ssl",
"/etc/pki",
diff --git a/frontend/src/hooks/api/pkiDiscovery/types.ts b/frontend/src/hooks/api/pkiDiscovery/types.ts
index b34a3d9993..26f65fa5ab 100644
--- a/frontend/src/hooks/api/pkiDiscovery/types.ts
+++ b/frontend/src/hooks/api/pkiDiscovery/types.ts
@@ -1,8 +1,27 @@
export enum PkiDiscoveryType {
Network = "network",
- LinuxServer = "linux-server"
+ LinuxServer = "linux-server",
+ WindowsServer = "windows-server"
}
+export enum WindowsCertificateStore {
+ Personal = "My",
+ WebHosting = "WebHosting",
+ RemoteDesktop = "Remote Desktop",
+ IntermediateCertificationAuthorities = "CA",
+ TrustedRootCertificationAuthorities = "Root"
+}
+
+export const WindowsCertificateStoreLabels: Record<WindowsCertificateStore, string> = {
+ [WindowsCertificateStore.Personal]: "Personal",
+ [WindowsCertificateStore.WebHosting]: "Web Hosting",
+ [WindowsCertificateStore.RemoteDesktop]: "Remote Desktop",
+ [WindowsCertificateStore.IntermediateCertificationAuthorities]:
+ "Intermediate Certification Authorities",
+ [WindowsCertificateStore.TrustedRootCertificationAuthorities]:
+ "Trusted Root Certification Authorities"
+};
+
export enum PkiKeystoreStatus {
Locked = "locked",
Readable = "readable",
@@ -60,6 +79,7 @@ export type TPkiDiscoveryTargetConfig = {
skipFolderPaths?: string[];
maxFolderDepth?: number;
maxFileSizeKb?: number;
+ certificateStores?: WindowsCertificateStore[];
importStandaloneCaCertificates?: boolean;
};
@@ -105,6 +125,10 @@ export type TPkiInstallation = {
gatewayName?: string;
hostname?: string;
format?: PkiCertificateFileFormat;
+ storeLocation?: string;
+ storeName?: string;
+ thumbprint?: string;
+ hasPrivateKey?: boolean;
};
locationFingerprint: string;
name: string | null;
diff --git a/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryTargetSection.tsx b/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryTargetSection.tsx
index ad4967ff48..a6281f8394 100644
--- a/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryTargetSection.tsx
+++ b/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryTargetSection.tsx
@@ -12,6 +12,7 @@ import {
OverflowBadgeList
} from "@app/components/v3";
import { PkiDiscoveryType, TPkiDiscovery } from "@app/hooks/api";
+import { WindowsCertificateStoreLabels } from "@app/hooks/api/pkiDiscovery/types";
import { getItemLabel, parsePorts } from "@app/pages/cert-manager/pki-discovery-utils";
type Props = {
@@ -81,10 +82,61 @@ const LinuxServerTargetSection = ({ discovery }: Props) => {
);
};
+const WindowsServerTargetSection = ({ discovery }: Props) => {
+ const { targetConfig } = discovery;
+ const connectionsById = new Map((discovery.connections ?? []).map((c) => [c.id, c.name]));
+
+ return (
+ <Card>
+ <CardHeader className="border-b">
+ <CardTitle>Target Configuration</CardTitle>
+ <CardDescription>
+ Servers and certificate stores scanned by this discovery job
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <DetailGroup>
+ <Detail>
+ <DetailLabel>Windows (WinRM) Connections</DetailLabel>
+ <DetailValue>
+ <OverflowBadgeList
+ items={targetConfig.connectionIds ?? []}
+ getKey={(id) => id}
+ getLabel={(id) => connectionsById.get(id) ?? "Deleted connection"}
+ />
+ </DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Certificate Stores</DetailLabel>
+ <DetailValue>
+ <OverflowBadgeList
+ items={targetConfig.certificateStores ?? []}
+ getKey={(store) => store}
+ getLabel={(store) => WindowsCertificateStoreLabels[store] ?? store}
+ />
+ </DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Include CA certificates</DetailLabel>
+ <DetailValue>
+ <Badge variant={targetConfig.importStandaloneCaCertificates ? "success" : "neutral"}>
+ {targetConfig.importStandaloneCaCertificates ? "Enabled" : "Disabled"}
+ </Badge>
+ </DetailValue>
+ </Detail>
+ </DetailGroup>
+ </CardContent>
+ </Card>
+ );
+};
+
export const DiscoveryTargetSection = ({ discovery }: Props) => {
if (discovery.discoveryType === PkiDiscoveryType.LinuxServer) {
return <LinuxServerTargetSection discovery={discovery} />;
}
+ if (discovery.discoveryType === PkiDiscoveryType.WindowsServer) {
+ return <WindowsServerTargetSection discovery={discovery} />;
+ }
const { targetConfig } = discovery;
const { ports: portsStr } = targetConfig;
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobForm.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobForm.tsx
index d1afb4c6e1..5f8e9fe485 100644
--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobForm.tsx
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobForm.tsx
@@ -11,6 +11,7 @@ import {
} from "@app/components/v3";
import { getDiscoveryDocsUrl, PKI_DISCOVERY_TYPE_MAP } from "@app/helpers/pkiDiscovery";
import { useCreatePkiDiscovery, useUpdatePkiDiscovery } from "@app/hooks/api";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
import {
PkiDiscoveryType,
TPkiDiscovery,
@@ -25,10 +26,11 @@ import {
} from "./discovery-job-form-schema";
import { DiscoveryDetailsFields } from "./DiscoveryDetailsFields";
import { DiscoveryReviewFields } from "./DiscoveryReviewFields";
+import { HostConnectionsFields } from "./HostConnectionsFields";
import { LinuxServerFoldersFields } from "./LinuxServerFoldersFields";
-import { LinuxServerHostsFields } from "./LinuxServerHostsFields";
import { LinuxServerOptionsFields } from "./LinuxServerOptionsFields";
import { NetworkTargetFields } from "./NetworkTargetFields";
+import { WindowsServerStoresFields } from "./WindowsServerStoresFields";
type Props = {
discoveryType: PkiDiscoveryType;
@@ -43,7 +45,9 @@ type Props = {
enum DiscoveryJobStep {
Targets = "targets",
Hosts = "hosts",
+ WindowsHosts = "windows-hosts",
Folders = "folders",
+ Stores = "stores",
Options = "options",
Details = "details",
Review = "review"
@@ -67,6 +71,20 @@ const STEP_META: Record<
rightDescription:
"Each SSH connection is one server. The scan runs from the gateway on that connection.\n\nOnly SSH connections that use a gateway can be selected."
},
+ [DiscoveryJobStep.WindowsHosts]: {
+ name: "Hosts",
+ short: "Servers to scan",
+ subtitle: "Pick the Windows (WinRM) connections for the servers to scan.",
+ rightDescription:
+ "Each Windows (WinRM) connection is one server. The scan runs from the gateway on that connection.\n\nOnly connections that use a gateway can be selected."
+ },
+ [DiscoveryJobStep.Stores]: {
+ name: "Stores",
+ short: "Stores and CA certificates",
+ subtitle: "Choose the certificate stores to read and what to import.",
+ rightDescription:
+ "The scan reads the Local Machine certificate stores. Private keys aren't read or imported; the installation only records whether a certificate has one.\n\nStores the connection's user can't open are listed in the scan."
+ },
[DiscoveryJobStep.Folders]: {
name: "Where to Look",
short: "Folders to search",
@@ -98,24 +116,44 @@ const STEP_META: Record<
const STEP_FIELDS: Record<DiscoveryJobStep, FieldPath<TDiscoveryJobForm>[]> = {
[DiscoveryJobStep.Targets]: ["targets", "ports", "gatewayId", "gatewayPoolId"],
[DiscoveryJobStep.Hosts]: ["connections"],
+ [DiscoveryJobStep.WindowsHosts]: ["connections"],
[DiscoveryJobStep.Folders]: ["searchFolderPaths", "skipFolderPaths"],
+ [DiscoveryJobStep.Stores]: ["certificateStores", "importStandaloneCaCertificates"],
[DiscoveryJobStep.Options]: ["maxFolderDepth", "importStandaloneCaCertificates"],
[DiscoveryJobStep.Details]: ["name", "description", "isAutoScanEnabled", "scanIntervalDays"],
[DiscoveryJobStep.Review]: []
};
-const getSteps = (type: PkiDiscoveryType): DiscoveryJobStep[] =>
- type === PkiDiscoveryType.LinuxServer
- ? [
+const getSteps = (type: PkiDiscoveryType): DiscoveryJobStep[] => {
+ switch (type) {
+ case PkiDiscoveryType.LinuxServer:
+ return [
DiscoveryJobStep.Hosts,
DiscoveryJobStep.Folders,
DiscoveryJobStep.Options,
DiscoveryJobStep.Details,
DiscoveryJobStep.Review
- ]
- : [DiscoveryJobStep.Targets, DiscoveryJobStep.Details, DiscoveryJobStep.Review];
+ ];
+ case PkiDiscoveryType.WindowsServer:
+ return [
+ DiscoveryJobStep.WindowsHosts,
+ DiscoveryJobStep.Stores,
+ DiscoveryJobStep.Details,
+ DiscoveryJobStep.Review
+ ];
+ default:
+ return [DiscoveryJobStep.Targets, DiscoveryJobStep.Details, DiscoveryJobStep.Review];
+ }
+};
const buildTargetConfig = (form: TDiscoveryJobForm): TPkiDiscoveryTargetConfig => {
+ if (form.discoveryType === PkiDiscoveryType.WindowsServer) {
+ return {
+ connectionIds: form.connections.map((c) => c.id),
+ certificateStores: form.certificateStores,
+ importStandaloneCaCertificates: form.importStandaloneCaCertificates
+ };
+ }
if (form.discoveryType === PkiDiscoveryType.LinuxServer) {
return {
connectionIds: form.connections.map((c) => c.id),
@@ -273,7 +311,21 @@ export const DiscoveryJobForm = ({
<p className="mt-1 text-sm text-muted">{currentStep.subtitle}</p>
</div>
{currentKey === DiscoveryJobStep.Targets && <NetworkTargetFields />}
- {currentKey === DiscoveryJobStep.Hosts && <LinuxServerHostsFields />}
+ {currentKey === DiscoveryJobStep.Hosts && (
+ <HostConnectionsFields
+ app={AppConnection.SSH}
+ connectionLabel="SSH"
+ capability="certificateScan"
+ />
+ )}
+ {currentKey === DiscoveryJobStep.WindowsHosts && (
+ <HostConnectionsFields
+ app={AppConnection.WinRM}
+ connectionLabel="Windows (WinRM)"
+ capability="windowsCertificateScan"
+ />
+ )}
+ {currentKey === DiscoveryJobStep.Stores && <WindowsServerStoresFields />}
{currentKey === DiscoveryJobStep.Folders && <LinuxServerFoldersFields />}
{currentKey === DiscoveryJobStep.Options && <LinuxServerOptionsFields />}
{currentKey === DiscoveryJobStep.Details && <DiscoveryDetailsFields />}
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryReviewFields.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryReviewFields.tsx
index b5aaf607ba..cd12b8461f 100644
--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryReviewFields.tsx
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryReviewFields.tsx
@@ -14,7 +14,7 @@ import {
import { PKI_DISCOVERY_TYPE_MAP } from "@app/helpers/pkiDiscovery";
import { gatewayPoolsQueryKeys } from "@app/hooks/api/gateway-pools/queries";
import { gatewaysQueryKeys } from "@app/hooks/api/gateways/queries";
-import { PkiDiscoveryType } from "@app/hooks/api/pkiDiscovery/types";
+import { PkiDiscoveryType, WindowsCertificateStoreLabels } from "@app/hooks/api/pkiDiscovery/types";
import { getItemLabel } from "@app/pages/cert-manager/pki-discovery-utils";
import { parseTargets, TDiscoveryJobForm } from "./discovery-job-form-schema";
@@ -111,6 +111,27 @@ export const DiscoveryReviewFields = () => {
</ReviewGroup>
</>
)}
+ {values.discoveryType === PkiDiscoveryType.WindowsServer && (
+ <>
+ <ReviewGroup title="Hosts">
+ <ReviewBadgesDetail
+ label="Windows (WinRM) Connections"
+ items={values.connections.map((connection) => connection.name)}
+ />
+ </ReviewGroup>
+ <ReviewGroup title="Stores">
+ <ReviewBadgesDetail
+ label="Certificate Stores"
+ items={values.certificateStores.map((store) => WindowsCertificateStoreLabels[store])}
+ />
+ <ReviewDetail label="Include CA certificates">
+ <Badge variant={values.importStandaloneCaCertificates ? "success" : "neutral"}>
+ {values.importStandaloneCaCertificates ? "Enabled" : "Disabled"}
+ </Badge>
+ </ReviewDetail>
+ </ReviewGroup>
+ </>
+ )}
<ReviewGroup title="Details">
<ReviewDetail label="Type">
{PKI_DISCOVERY_TYPE_MAP[values.discoveryType].name}
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryTypeSelect.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryTypeSelect.tsx
index 6d48411c23..5055d930c5 100644
--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryTypeSelect.tsx
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryTypeSelect.tsx
@@ -8,7 +8,7 @@ type Props = {
};
export const DiscoveryTypeSelect = ({ onSelect }: Props) => (
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
{Object.values(PkiDiscoveryType).map((type) => {
const { name, category, description } = PKI_DISCOVERY_TYPE_MAP[type];
return (
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/LinuxServerHostsFields.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/HostConnectionsFields.tsx
similarity index 85%
rename from frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/LinuxServerHostsFields.tsx
rename to frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/HostConnectionsFields.tsx
index 642109fbb5..a255c3e5a6 100644
--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/LinuxServerHostsFields.tsx
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/HostConnectionsFields.tsx
@@ -25,21 +25,27 @@ import { AppConnection } from "@app/hooks/api/appConnections/enums";
import { gatewaysQueryKeys } from "@app/hooks/api/gateways/queries";
import { AddAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";
-import { TLinuxServerDiscoveryJobForm } from "./discovery-job-form-schema";
+import { THostDiscoveryJobForm } from "./discovery-job-form-schema";
type TConnectionOption = Pick<TAvailableAppConnection, "id" | "name"> &
Partial<TAvailableAppConnection>;
const CREATE_OPTION_ID = "_create";
-export const LinuxServerHostsFields = () => {
+type Props = {
+ app: AppConnection.SSH | AppConnection.WinRM;
+ connectionLabel: string;
+ capability: "certificateScan" | "windowsCertificateScan";
+};
+
+export const HostConnectionsFields = ({ app, connectionLabel, capability }: Props) => {
const { permission } = useProjectPermission();
const { currentProject } = useProject();
- const { control, getValues, setValue, setError } = useFormContext<TLinuxServerDiscoveryJobForm>();
+ const { control, getValues, setValue, setError } = useFormContext<THostDiscoveryJobForm>();
const { popUp, handlePopUpToggle, handlePopUpOpen } = usePopUp(["addConnection"] as const);
const { connections, isPending } = useListAvailableAppConnectionsForApps(
- [AppConnection.SSH],
+ [app],
currentProject.id
);
const { data: gateways } = useQuery(gatewaysQueryKeys.list());
@@ -51,7 +57,7 @@ export const LinuxServerHostsFields = () => {
const incapableGatewayIds = new Set(
(gateways ?? [])
- .filter((gateway) => gateway.capabilities?.certificateScan !== true)
+ .filter((gateway) => gateway.capabilities?.[capability] !== true)
.map((gateway) => gateway.id)
);
@@ -70,7 +76,9 @@ export const LinuxServerHostsFields = () => {
const isUnusable = (option: TConnectionOption) =>
isMissingGateway(option) || isGatewayOutdated(option);
const connectionOptions: TConnectionOption[] = [
- ...(canCreateConnection ? [{ id: CREATE_OPTION_ID, name: "Create SSH Connection" }] : []),
+ ...(canCreateConnection
+ ? [{ id: CREATE_OPTION_ID, name: `Create ${connectionLabel} Connection` }]
+ : []),
...connections.filter((connection) => !isUnusable(connection)),
...connections.filter(isUnusable)
];
@@ -82,7 +90,7 @@ export const LinuxServerHostsFields = () => {
name="connections"
render={({ field: { value, onChange }, fieldState: { error } }) => (
<Field className="mb-4">
- <FieldLabel>SSH Connections</FieldLabel>
+ <FieldLabel>{connectionLabel} Connections</FieldLabel>
<FieldContent>
<Combobox
multiple
@@ -106,8 +114,7 @@ export const LinuxServerHostsFields = () => {
let unusableHint: string | null = null;
if (isMissingGateway(option)) {
unusableLabel = "No gateway";
- unusableHint =
- "This SSH connection has no gateway. Add one to the connection to scan this server.";
+ unusableHint = `This ${connectionLabel} connection has no gateway. Add one to the connection to scan this server.`;
} else if (isGatewayOutdated(option)) {
unusableLabel = "Update gateway";
unusableHint =
@@ -116,7 +123,7 @@ export const LinuxServerHostsFields = () => {
return (
<AppConnectionOptionContent
data={resolveOption(option)}
- createLabel="Create SSH Connection"
+ createLabel={`Create ${connectionLabel} Connection`}
isOnlyOption={
option.id === CREATE_OPTION_ID && connectionOptions.length === 1
}
@@ -151,7 +158,8 @@ export const LinuxServerHostsFields = () => {
{!isPending && !connections.length && !canCreateConnection && (
<p className="mt-2 flex items-center gap-1.5 text-xs text-warning">
<Info className="size-3.5" />
- You do not have access to any SSH Connections. Contact an admin to create one.
+ You do not have access to any {connectionLabel} Connections. Contact an admin to create
+ one.
</p>
)}
<AddAppConnectionModal
@@ -159,13 +167,13 @@ export const LinuxServerHostsFields = () => {
onOpenChange={(isOpen) => handlePopUpToggle("addConnection", isOpen)}
projectType={currentProject.type}
projectId={currentProject.id}
- app={AppConnection.SSH}
+ app={app}
onComplete={(connection) => {
const existing = getValues("connections") ?? [];
if (existing.some((c) => c.id === connection.id)) return;
if (!connection.gatewayId && !connection.gatewayPoolId) {
setError("connections", {
- message: `SSH connection '${connection.name}' has no gateway. Add one to the connection to scan this server.`
+ message: `${connectionLabel} connection '${connection.name}' has no gateway. Add one to the connection to scan this server.`
});
return;
}
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/WindowsServerStoresFields.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/WindowsServerStoresFields.tsx
new file mode 100644
index 0000000000..86ba2f286e
--- /dev/null
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/WindowsServerStoresFields.tsx
@@ -0,0 +1,130 @@
+import { Controller, useFormContext } from "react-hook-form";
+
+import {
+ Checkbox,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ FieldLegend,
+ FieldSet,
+ Toggle
+} from "@app/components/v3";
+import {
+ WindowsCertificateStore,
+ WindowsCertificateStoreLabels
+} from "@app/hooks/api/pkiDiscovery/types";
+
+import { TWindowsServerDiscoveryJobForm } from "./discovery-job-form-schema";
+
+const STORE_DESCRIPTIONS: Record<WindowsCertificateStore, string> = {
+ [WindowsCertificateStore.Personal]:
+ "Server certificates for IIS, Remote Desktop, SQL Server and most other applications.",
+ [WindowsCertificateStore.WebHosting]: "Certificates added for IIS sites.",
+ [WindowsCertificateStore.RemoteDesktop]: "The certificate Remote Desktop uses on this server.",
+ [WindowsCertificateStore.IntermediateCertificationAuthorities]: "Intermediate CA certificates.",
+ [WindowsCertificateStore.TrustedRootCertificationAuthorities]:
+ "Root CAs this server trusts, including the public ones built into Windows."
+};
+
+const SERVER_STORES = [
+ WindowsCertificateStore.Personal,
+ WindowsCertificateStore.WebHosting,
+ WindowsCertificateStore.RemoteDesktop
+];
+
+const CA_STORES = [
+ WindowsCertificateStore.IntermediateCertificationAuthorities,
+ WindowsCertificateStore.TrustedRootCertificationAuthorities
+];
+
+type StoreOptionsProps = {
+ stores: WindowsCertificateStore[];
+ value: WindowsCertificateStore[];
+ onChange: (stores: WindowsCertificateStore[]) => void;
+};
+
+const StoreOptions = ({ stores, value, onChange }: StoreOptionsProps) => (
+ <FieldGroup data-slot="checkbox-group">
+ {stores.map((store) => {
+ const id = `certificate-store-${store.replace(" ", "-")}`;
+ return (
+ <Field key={store} orientation="horizontal">
+ <Checkbox
+ id={id}
+ variant="project"
+ isChecked={value.includes(store)}
+ onCheckedChange={(checked) =>
+ onChange(
+ Object.values(WindowsCertificateStore).filter((s) =>
+ s === store ? checked === true : value.includes(s)
+ )
+ )
+ }
+ />
+ <FieldContent>
+ <FieldLabel htmlFor={id} className="cursor-pointer text-sm font-medium text-foreground">
+ {WindowsCertificateStoreLabels[store]}
+ </FieldLabel>
+ <FieldDescription>{STORE_DESCRIPTIONS[store]}</FieldDescription>
+ </FieldContent>
+ </Field>
+ );
+ })}
+ </FieldGroup>
+);
+
+export const WindowsServerStoresFields = () => {
+ const { control, trigger } = useFormContext<TWindowsServerDiscoveryJobForm>();
+
+ return (
+ <Controller
+ control={control}
+ name="certificateStores"
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <div className="mb-4 flex flex-col gap-8">
+ <FieldSet>
+ <FieldLegend variant="label">Server Certificate Stores</FieldLegend>
+ <StoreOptions stores={SERVER_STORES} value={value} onChange={onChange} />
+ </FieldSet>
+ <FieldSet>
+ <FieldLegend variant="label">CA Certificate Stores</FieldLegend>
+ <StoreOptions stores={CA_STORES} value={value} onChange={onChange} />
+ <Controller
+ control={control}
+ name="importStandaloneCaCertificates"
+ render={({ field: { value: includeCa, onChange: setIncludeCa } }) => (
+ <Field orientation="horizontal" className="mt-2">
+ <FieldContent>
+ <FieldLabel
+ htmlFor="import-standalone-ca"
+ className="cursor-pointer text-sm font-medium text-foreground"
+ >
+ Include CA certificates
+ </FieldLabel>
+ <FieldDescription>
+ Import the CA certificates in the selected stores. A leaf certificate always
+ comes in with its chain.
+ </FieldDescription>
+ </FieldContent>
+ <Toggle
+ id="import-standalone-ca"
+ variant="project"
+ checked={includeCa}
+ onCheckedChange={(checked) => {
+ setIncludeCa(checked);
+ trigger("certificateStores");
+ }}
+ />
+ </Field>
+ )}
+ />
+ </FieldSet>
+ <FieldError errors={[error]} />
+ </div>
+ )}
+ />
+ );
+};
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/discovery-job-form-schema.ts b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/discovery-job-form-schema.ts
index 9424648f05..019e043a8c 100644
--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/discovery-job-form-schema.ts
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/discovery-job-form-schema.ts
@@ -4,10 +4,15 @@ import {
DEFAULT_LINUX_SEARCH_FOLDERS,
DEFAULT_MAX_FILE_SIZE_KB,
DEFAULT_MAX_FOLDER_DEPTH,
+ DEFAULT_WINDOWS_CERTIFICATE_STORES,
MAX_FILE_SIZE_KB,
MAX_FOLDER_DEPTH
} from "@app/helpers/pkiDiscovery";
-import { PkiDiscoveryType, TPkiDiscovery } from "@app/hooks/api/pkiDiscovery/types";
+import {
+ PkiDiscoveryType,
+ TPkiDiscovery,
+ WindowsCertificateStore
+} from "@app/hooks/api/pkiDiscovery/types";
import { slugSchema } from "@app/lib/schemas/slugSchema";
export const MAX_PORTS = 5;
@@ -15,7 +20,7 @@ export const MAX_IPS = 256;
export const MAX_DOMAINS = 20;
export const MIN_CIDR_PREFIX = 24;
export const DEFAULT_TLS_PORTS = "443,8443,636,993,995";
-const MAX_LINUX_CONNECTIONS = 100;
+const MAX_HOST_CONNECTIONS = 100;
export const MAX_SEARCH_FOLDERS = 20;
export const MAX_SKIP_FOLDERS = 50;
@@ -127,12 +132,18 @@ const NetworkSchema = BaseSchema.extend({
gatewayPoolId: z.string().nullable().optional()
});
+const hostConnectionsSchema = (connectionLabel: string) =>
+ z
+ .array(z.object({ id: z.string(), name: z.string() }))
+ .min(1, `Select at least one ${connectionLabel} connection`)
+ .max(
+ MAX_HOST_CONNECTIONS,
+ `Select up to ${MAX_HOST_CONNECTIONS} ${connectionLabel} connections`
+ );
+
const LinuxServerSchema = BaseSchema.extend({
discoveryType: z.literal(PkiDiscoveryType.LinuxServer),
- connections: z
- .array(z.object({ id: z.string(), name: z.string() }))
- .min(1, "Select at least one SSH connection")
- .max(MAX_LINUX_CONNECTIONS, `Select up to ${MAX_LINUX_CONNECTIONS} SSH connections`),
+ connections: hostConnectionsSchema("SSH"),
searchFolderPaths: z
.array(z.string())
.min(1, "Add at least one folder to search")
@@ -153,14 +164,43 @@ const LinuxServerSchema = BaseSchema.extend({
importStandaloneCaCertificates: z.boolean()
});
-export const DiscoveryJobFormSchema = z.discriminatedUnion("discoveryType", [
- NetworkSchema,
- LinuxServerSchema
-]);
+const WindowsServerSchema = BaseSchema.extend({
+ discoveryType: z.literal(PkiDiscoveryType.WindowsServer),
+ connections: hostConnectionsSchema("Windows (WinRM)"),
+ certificateStores: z
+ .array(z.nativeEnum(WindowsCertificateStore))
+ .min(1, "Select at least one certificate store"),
+ importStandaloneCaCertificates: z.boolean()
+});
+
+const CA_ONLY_STORES = [
+ WindowsCertificateStore.IntermediateCertificationAuthorities,
+ WindowsCertificateStore.TrustedRootCertificationAuthorities
+];
+
+export const DiscoveryJobFormSchema = z
+ .discriminatedUnion("discoveryType", [NetworkSchema, LinuxServerSchema, WindowsServerSchema])
+ .superRefine((form, ctx) => {
+ if (
+ form.discoveryType === PkiDiscoveryType.WindowsServer &&
+ !form.importStandaloneCaCertificates &&
+ form.certificateStores.length > 0 &&
+ form.certificateStores.every((store) => CA_ONLY_STORES.includes(store))
+ ) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["certificateStores"],
+ message:
+ "These stores only hold CA certificates. Turn on Include CA certificates or select another store."
+ });
+ }
+ });
export type TDiscoveryJobForm = z.infer<typeof DiscoveryJobFormSchema>;
export type TNetworkDiscoveryJobForm = z.infer<typeof NetworkSchema>;
export type TLinuxServerDiscoveryJobForm = z.infer<typeof LinuxServerSchema>;
+export type TWindowsServerDiscoveryJobForm = z.infer<typeof WindowsServerSchema>;
+export type THostDiscoveryJobForm = TLinuxServerDiscoveryJobForm | TWindowsServerDiscoveryJobForm;
export const getDefaultFormValues = (
type: PkiDiscoveryType,
@@ -173,6 +213,19 @@ export const getDefaultFormValues = (
scanIntervalDays: discovery?.scanIntervalDays ?? 7
};
+ if (type === PkiDiscoveryType.WindowsServer) {
+ const config = discovery?.targetConfig;
+ return {
+ ...base,
+ discoveryType: PkiDiscoveryType.WindowsServer,
+ connections: discovery?.connections ?? [],
+ certificateStores: Object.values(WindowsCertificateStore).filter((store) =>
+ (config?.certificateStores ?? DEFAULT_WINDOWS_CERTIFICATE_STORES).includes(store)
+ ),
+ importStandaloneCaCertificates: config?.importStandaloneCaCertificates ?? false
+ };
+ }
+
if (type === PkiDiscoveryType.LinuxServer) {
const config = discovery?.targetConfig;
return {
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobsTab.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobsTab.tsx
index 1fcb74b03e..42de8f3a20 100644
--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobsTab.tsx
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobsTab.tsx
@@ -53,6 +53,7 @@ import {
useListPkiDiscoveries,
useTriggerPkiDiscoveryScan
} from "@app/hooks/api";
+import { WindowsCertificateStoreLabels } from "@app/hooks/api/pkiDiscovery/types";
import { useDebounce } from "@app/hooks/useDebounce";
import { usePopUp } from "@app/hooks/usePopUp";
import {
@@ -72,6 +73,11 @@ type Props = {
const PAGE_SIZE = 25;
const getScopeItems = (discovery: TPkiDiscovery) => {
+ if (discovery.discoveryType === PkiDiscoveryType.WindowsServer) {
+ return (discovery.targetConfig.certificateStores ?? []).map(
+ (store) => WindowsCertificateStoreLabels[store] ?? store
+ );
+ }
if (discovery.discoveryType === PkiDiscoveryType.LinuxServer) {
return discovery.targetConfig.searchFolderPaths ?? [];
}
@@ -80,7 +86,10 @@ const getScopeItems = (discovery: TPkiDiscovery) => {
};
const getTargetItems = (discovery: TPkiDiscovery) => {
- if (discovery.discoveryType === PkiDiscoveryType.LinuxServer) {
+ if (
+ discovery.discoveryType === PkiDiscoveryType.LinuxServer ||
+ discovery.discoveryType === PkiDiscoveryType.WindowsServer
+ ) {
return (discovery.connections ?? []).map((connection) => connection.name);
}
return [...(discovery.targetConfig.domains ?? []), ...(discovery.targetConfig.ipRanges ?? [])];
@@ -149,8 +158,7 @@ export const DiscoveryJobsTab = ({ projectId }: Props) => {
<CardHeader>
<CardTitle>Discovery Jobs</CardTitle>
<CardDescription>
- Configure scans to find certificates served on your network or stored in files on your
- servers.
+ Configure scans to find certificates served on your network or stored on your servers.
</CardDescription>
<CardAction>
<ProjectPermissionCan
@@ -205,7 +213,7 @@ export const DiscoveryJobsTab = ({ projectId }: Props) => {
<TableHead>Name</TableHead>
<TableHead>Type</TableHead>
<TableHead>Target</TableHead>
- <TableHead>Ports / Folders</TableHead>
+ <TableHead>Scope</TableHead>
<TableHead>Status</TableHead>
<TableHead>Last Scan</TableHead>
<TableHead className="w-5" />
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/InstallationsTab.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/InstallationsTab.tsx
index 0b44d017d1..47f0913f53 100644
--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/InstallationsTab.tsx
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/InstallationsTab.tsx
@@ -41,15 +41,14 @@ import {
useDeletePkiInstallation,
useListPkiInstallations
} from "@app/hooks/api";
-import { PkiDiscoveryType } from "@app/hooks/api/pkiDiscovery/types";
import { useDebounce } from "@app/hooks/useDebounce";
import { usePopUp } from "@app/hooks/usePopUp";
import {
canSetKeystorePassword,
getEndpoint,
getGatewayLabel,
+ getInstallationDiscoveryType,
getKeystoreStatusBadge,
- isHostFileInstallation,
useCanRescanPkiInstallations
} from "@app/pages/cert-manager/pki-discovery-utils";
@@ -132,8 +131,8 @@ export const InstallationsTab = ({ projectId }: Props) => {
<CardHeader>
<CardTitle>Installations</CardTitle>
<CardDescription>
- Every place a certificate was found during a scan, identified by its host and port or its
- host and file path.
+ Every place a certificate was found during a scan, identified by its host and its port,
+ file path or certificate store.
</CardDescription>
</CardHeader>
<CardContent>
@@ -198,11 +197,7 @@ export const InstallationsTab = ({ projectId }: Props) => {
<TableCell>
<div className="flex items-center gap-2">
<DiscoveryTypeIcon
- type={
- isHostFileInstallation(installation)
- ? PkiDiscoveryType.LinuxServer
- : PkiDiscoveryType.Network
- }
+ type={getInstallationDiscoveryType(installation)}
className="size-4 shrink-0"
/>
<span className="truncate">
diff --git a/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/components/InstallationDetailsSection.tsx b/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/components/InstallationDetailsSection.tsx
index b9f64d1a87..b8403bbda2 100644
--- a/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/components/InstallationDetailsSection.tsx
+++ b/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/components/InstallationDetailsSection.tsx
@@ -17,9 +17,15 @@ import {
PkiInstallationLocationType,
TPkiInstallation
} from "@app/hooks/api";
+import {
+ WindowsCertificateStore,
+ WindowsCertificateStoreLabels
+} from "@app/hooks/api/pkiDiscovery/types";
import {
getKeystoreStatusBadge,
- isHostFileInstallation
+ getStorePath,
+ isHostFileInstallation,
+ isStoreInstallation
} from "@app/pages/cert-manager/pki-discovery-utils";
type Props = {
@@ -30,6 +36,7 @@ export const InstallationDetailsSection = ({ installation }: Props) => {
const { locationDetails } = installation;
const endpoint = locationDetails.fqdn || locationDetails.ipAddress;
const isHostFile = isHostFileInstallation(installation);
+ const isStore = isStoreInstallation(installation);
const isKeystore = installation.locationType === PkiInstallationLocationType.Keystore;
return (
@@ -47,6 +54,50 @@ export const InstallationDetailsSection = ({ installation }: Props) => {
{installation.name || <span className="text-muted">-</span>}
</DetailValue>
</Detail>
+ {isStore && (
+ <>
+ <Detail>
+ <DetailLabel>Host</DetailLabel>
+ <DetailValue>
+ {locationDetails.hostname || <span className="text-muted">-</span>}
+ </DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Address</DetailLabel>
+ <DetailValue>
+ {locationDetails.hostIdentifier || <span className="text-muted">-</span>}
+ </DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Certificate Store</DetailLabel>
+ <DetailValue>
+ {(locationDetails.storeName &&
+ WindowsCertificateStoreLabels[
+ locationDetails.storeName as WindowsCertificateStore
+ ]) ||
+ locationDetails.storeName}
+ </DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Path</DetailLabel>
+ <DetailValue className="font-mono break-all">
+ {getStorePath(installation)}
+ </DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Private Key</DetailLabel>
+ <DetailValue>
+ {locationDetails.hasPrivateKey ? "Present" : "Not present"}
+ </DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Connection</DetailLabel>
+ <DetailValue>
+ {installation.connection?.name || <span className="text-muted">-</span>}
+ </DetailValue>
+ </Detail>
+ </>
+ )}
{isHostFile && (
<>
<Detail>
@@ -96,7 +147,7 @@ export const InstallationDetailsSection = ({ installation }: Props) => {
</DetailValue>
</Detail>
)}
- {endpoint && !isHostFile && (
+ {endpoint && !isHostFile && !isStore && (
<Detail>
<DetailLabel>Endpoint</DetailLabel>
<DetailValue>
diff --git a/frontend/src/pages/cert-manager/pki-discovery-utils.tsx b/frontend/src/pages/cert-manager/pki-discovery-utils.tsx
index 50b09b9bca..8cfb07ba13 100644
--- a/frontend/src/pages/cert-manager/pki-discovery-utils.tsx
+++ b/frontend/src/pages/cert-manager/pki-discovery-utils.tsx
@@ -8,6 +8,7 @@ import {
import {
PkiCertificateFileFormat,
PkiDiscoveryScanStatus,
+ PkiDiscoveryType,
PkiInstallationLocationType,
PkiKeystoreStatus,
TPkiInstallation
@@ -22,8 +23,27 @@ export const isHostFileInstallation = (installation: TPkiInstallation) =>
installation.locationType === PkiInstallationLocationType.Filesystem ||
installation.locationType === PkiInstallationLocationType.Keystore;
+export const isStoreInstallation = (installation: TPkiInstallation) =>
+ installation.locationType === PkiInstallationLocationType.OsStore;
+
+export const getInstallationDiscoveryType = (installation: TPkiInstallation) => {
+ if (isHostFileInstallation(installation)) return PkiDiscoveryType.LinuxServer;
+ if (isStoreInstallation(installation)) return PkiDiscoveryType.WindowsServer;
+ return PkiDiscoveryType.Network;
+};
+
+export const getStorePath = (installation: TPkiInstallation) => {
+ const { storeLocation, storeName, thumbprint } = installation.locationDetails;
+ return `Cert:\\${storeLocation ?? "LocalMachine"}\\${storeName}\\${thumbprint}`;
+};
+
export const getEndpoint = (installation: TPkiInstallation): string => {
const { ipAddress, fqdn, port, hostIdentifier, filePath } = installation.locationDetails;
+ if (isStoreInstallation(installation)) {
+ return hostIdentifier
+ ? `${hostIdentifier}:${getStorePath(installation)}`
+ : getStorePath(installation);
+ }
if (isHostFileInstallation(installation) && filePath) {
return hostIdentifier ? `${hostIdentifier}:${filePath}` : filePath;
}