Skip to content

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

fix(pam): address dependency-detection and Windows-rotation review findings

bernie-g8ce47edbc136
diff --git a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.ts b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.ts
index 48aa8ac534..36af294ffe 100644
--- a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.ts
+++ b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.ts
@@ -21,7 +21,7 @@ import { TPamAccountDALFactory, TPamAccountDetail } from "../pam-account/pam-acc
import { validateConnectionDetails, validateCredentials } from "../pam-account/pam-account-schemas";
import { PamTemplateSettingsSchema } from "../pam-account-template/pam-account-template-schemas";
import { TPamAccountDependencyDALFactory } from "../pam-discovery/pam-account-dependency-dal";
-import { winrmRpcWithGateway } from "../pam-discovery/pam-discovery-fns";
+import { resolveHostsViaDcDns, winrmRpcWithGateway } from "../pam-discovery/pam-discovery-fns";
import {
TGetPamAccountRotationDTO,
TListPamRotationCandidatesDTO,
@@ -38,7 +38,12 @@ import {
redactRotationError,
ROTATION_FAILURE_RETRY_CAP_SECONDS
} from "./pam-rotation-fns";
-import { PAM_ROTATION_FACTORY_MAP } from "./pam-rotation-handlers";
+import {
+ PAM_ROTATION_FACTORY_MAP,
+ winrmConnectUsername,
+ winrmPortFromConn,
+ winrmTransportFromConn
+} from "./pam-rotation-handlers";
export const ROTATION_STATUS = { Success: "success", Failed: "failed" } as const;
@@ -150,8 +155,6 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
raw: Record<string, unknown>
): Record<string, unknown> => validateConnectionDetails(accountType, raw) as Record<string, unknown>;
- // Windows dependencies have no per-machine WinRM port; use the WinRM HTTP default like discovery/rotation.
- const WINRM_DEPENDENCY_SYNC_PORT = 5985;
const DEPENDENCY_SYNC_CONCURRENCY = 5;
// postRotate: push the new password into every service / scheduled task / IIS app pool that runs as the
@@ -161,6 +164,7 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
accountId,
projectId,
accountType,
+ connectionDetails,
targetUsername,
newPassword,
connectAuth,
@@ -170,14 +174,15 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
accountId: string;
projectId: string;
accountType: PamAccountType;
+ connectionDetails: Record<string, unknown>;
targetUsername: string;
newPassword: string;
connectAuth: { username: string; password: string };
gatewayId?: string | null;
gatewayPoolId?: string | null;
}) => {
- // Dependencies are detected only for domain accounts today.
- if (accountType !== PamAccountType.WindowsAd) return;
+ // Dependencies are detected for both domain (WindowsAd) and local (Windows) accounts.
+ if (!isWindowsRotatableType(accountType)) return;
const dependencies = await pamAccountDependencyDAL.findByAccountId(accountId);
if (!dependencies.length) return;
@@ -190,25 +195,44 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
return;
}
+ // Machines share the account's WinRM settings (HTTPS / port / CA), populated from the source on import.
+ const winrmPort = winrmPortFromConn(connectionDetails);
+ const winrmTransport = winrmTransportFromConn(connectionDetails);
+ // A domain rotator must connect as a UPN over WinRM (NTLM 401s on a bare name); local stays bare.
+ const connectUsername = winrmConnectUsername(accountType, connectionDetails, connectAuth.username);
+
+ // Re-resolve each machine via the DC's DNS at sync time so a scan-time IP that went stale (DHCP) can't
+ // target the wrong host. Domain accounts only (a local account has no DC); fall back to the scan-time IP.
+ const { dcAddress } = connectionDetails as { dcAddress?: string };
+ const freshIpByMachine =
+ accountType === PamAccountType.WindowsAd && dcAddress
+ ? await resolveHostsViaDcDns(
+ [...new Set(dependencies.map((d) => d.machine))],
+ dcAddress,
+ resolvedGatewayId,
+ gatewayV2Service
+ ).catch(() => new Map<string, string>())
+ : new Map<string, string>();
+
const { encryptor } = await getProjectCipher(projectId);
const limit = pLimit(DEPENDENCY_SYNC_CONCURRENCY);
await Promise.all(
dependencies.map((dep) =>
+ // Only terminal states are written: a crash mid-sync leaves the prior status (self-corrects on the next
+ // rotation) rather than a "pending" that could stick forever.
limit(async () => {
- await pamAccountDependencyDAL.updateById(dep.id, { rotationStatus: "pending" });
try {
const depData = dep.data as { runAsAccount?: string; resolvedIp?: string };
const runAsAccount = depData?.runAsAccount ?? targetUsername;
- // Prefer the IP resolved at scan time: the gateway can't always resolve AD hostnames directly.
- const targetHost = depData?.resolvedIp || dep.machine;
+ const targetHost = freshIpByMachine.get(dep.machine) || depData?.resolvedIp || dep.machine;
await winrmRpcWithGateway<{ ok: boolean }>({
targetHost,
- targetPort: WINRM_DEPENDENCY_SYNC_PORT,
+ targetPort: winrmPort,
gatewayId: resolvedGatewayId,
gatewayV2Service,
endpoint: WinRmRpcEndpoint.SyncDependency,
- credentials: { username: connectAuth.username, password: connectAuth.password },
+ credentials: { username: connectUsername, password: connectAuth.password, ...winrmTransport },
params: { type: dep.type, name: dep.name, runAsUsername: runAsAccount, newPassword }
});
await pamAccountDependencyDAL.updateById(dep.id, {
@@ -424,6 +448,7 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
accountId: account.id,
projectId,
accountType,
+ connectionDetails,
targetUsername,
newPassword,
// For self-rotation the account's old password is now dead, so connect with the new one; a delegated
diff --git a/backend/src/ee/services/pam-account-rotation/pam-rotation-handlers.ts b/backend/src/ee/services/pam-account-rotation/pam-rotation-handlers.ts
index 03a67b1072..977983ac26 100644
--- a/backend/src/ee/services/pam-account-rotation/pam-rotation-handlers.ts
+++ b/backend/src/ee/services/pam-account-rotation/pam-rotation-handlers.ts
@@ -99,11 +99,20 @@ const sqlRotationHandler: TPamRotationHandler = {
}
};
-// Windows accounts have no per-account WinRM port in their connection details, so use the WinRM HTTP default.
-const WINRM_ROTATION_PORT = 5985;
+// Default when an account carries no explicit WinRM port (e.g. an older imported/manual account).
+const DEFAULT_WINRM_PORT = 5985;
-type TWindowsConnDetails = { host?: string };
-type TWindowsAdConnDetails = {
+// WinRM connection settings live on the account's connection details, populated from the discovery source on
+// import (or set manually), so rotation and dependency sync honor HTTPS / a custom port / a pinned CA.
+type TWinrmConnSettings = {
+ winrmPort?: number;
+ useWinrmHttps?: boolean;
+ winrmRejectUnauthorized?: boolean;
+ winrmCaCert?: string;
+};
+
+type TWindowsConnDetails = TWinrmConnSettings & { host?: string };
+type TWindowsAdConnDetails = TWinrmConnSettings & {
domain?: string;
dcAddress?: string;
port?: number;
@@ -113,6 +122,21 @@ type TWindowsAdConnDetails = {
ldapTlsServerName?: string;
};
+export const winrmPortFromConn = (conn: Record<string, unknown>): number =>
+ typeof conn.winrmPort === "number" ? conn.winrmPort : DEFAULT_WINRM_PORT;
+
+export const winrmTransportFromConn = (
+ conn: Record<string, unknown>
+): { useHttps: boolean; insecure: boolean; caCertificate?: string } => {
+ const useHttps = Boolean(conn.useWinrmHttps);
+ return {
+ useHttps,
+ // insecure skips cert verification (HTTPS only); it maps from the account's reject-unauthorized flag
+ insecure: useHttps && conn.winrmRejectUnauthorized === false,
+ caCertificate: typeof conn.winrmCaCert === "string" ? conn.winrmCaCert : undefined
+ };
+};
+
// Local accounts rotate on their own host; domain accounts rotate on the DC (which has the AD tooling).
const winrmRotationTargetHost = (accountType: TRotatableType, connectionDetails: Record<string, unknown>): string => {
if (accountType === PamAccountType.WindowsAd) {
@@ -139,6 +163,27 @@ const resolveRotationGatewayId = async (
return resolved;
};
+// Set-ADAccountPassword -Identity and Set-LocalUser -Name want a bare sAMAccountName, not DOMAIN\user or a
+// UPN (both accepted by the account schema), so strip any domain qualifier before building the rotate script.
+const toBareAccountName = (username: string): string => {
+ if (username.includes("\\")) return username.split("\\").pop() ?? username;
+ if (username.includes("@")) return username.split("@")[0];
+ return username;
+};
+
+// The identity WinRM connects AS must be domain-qualified for a domain rotator: NTLM resolves a bare name
+// against the target's local SAM (and 401s), so qualify to a UPN. Local accounts stay bare.
+export const winrmConnectUsername = (
+ accountType: TRotatableType,
+ connectionDetails: Record<string, unknown>,
+ username: string
+): string => {
+ if (accountType !== PamAccountType.WindowsAd) return username;
+ if (username.includes("\\") || username.includes("@")) return username;
+ const { domain } = connectionDetails as TWindowsAdConnDetails;
+ return domain ? `${username}@${domain}` : username;
+};
+
const windowsRotationHandler: TPamRotationHandler = {
validateTarget: () => {
// Domain rotation needs a delegated admin (an account can't -Reset itself); AD enforces this at runtime.
@@ -152,14 +197,18 @@ const windowsRotationHandler: TPamRotationHandler = {
try {
await winrmRpcWithGateway<{ ok: boolean }>({
targetHost,
- targetPort: WINRM_ROTATION_PORT,
+ targetPort: winrmPortFromConn(connectionDetails),
gatewayId: resolvedGatewayId,
gatewayV2Service: deps.gatewayV2Service,
endpoint: WinRmRpcEndpoint.RotateCredential,
- credentials: { username: auth.username, password: auth.password },
+ credentials: {
+ username: winrmConnectUsername(accountType, connectionDetails, auth.username),
+ password: auth.password,
+ ...winrmTransportFromConn(connectionDetails)
+ },
params: {
kind: accountType === PamAccountType.WindowsAd ? "domain" : "local",
- targetUsername,
+ targetUsername: toBareAccountName(targetUsername),
newPassword
}
});
@@ -200,11 +249,11 @@ const windowsRotationHandler: TPamRotationHandler = {
// Local account: prove the credential over WinRM against its own host.
await winrmRpcWithGateway<{ ok: boolean }>({
targetHost: winrmRotationTargetHost(accountType, connectionDetails),
- targetPort: WINRM_ROTATION_PORT,
+ targetPort: winrmPortFromConn(connectionDetails),
gatewayId: resolvedGatewayId,
gatewayV2Service: deps.gatewayV2Service,
endpoint: WinRmRpcEndpoint.Test,
- credentials: { username: auth.username, password: auth.password }
+ credentials: { username: auth.username, password: auth.password, ...winrmTransportFromConn(connectionDetails) }
});
return true;
} catch {
diff --git a/backend/src/ee/services/pam-account/pam-account-schemas.ts b/backend/src/ee/services/pam-account/pam-account-schemas.ts
index fc0e058baf..fbbaf3328c 100644
--- a/backend/src/ee/services/pam-account/pam-account-schemas.ts
+++ b/backend/src/ee/services/pam-account/pam-account-schemas.ts
@@ -453,7 +453,11 @@ export const ACCOUNT_TYPE_CONFIGS = {
icon: "Windows.png",
connectionDetails: z.object({
host: z.string().trim().min(1).max(255),
- port: z.coerce.number().int().min(1).max(65535)
+ port: z.coerce.number().int().min(1).max(65535),
+ winrmPort: z.coerce.number().int().min(1).max(65535).default(5985),
+ useWinrmHttps: z.boolean().default(false),
+ winrmRejectUnauthorized: z.boolean().default(true),
+ winrmCaCert: optionalTrimmedString
}),
credentials: z.object({
username: z.string().trim().min(1).max(255),
@@ -463,7 +467,18 @@ export const ACCOUNT_TYPE_CONFIGS = {
username: z.string()
}),
ui: {
- port: { defaultValue: 3389 },
+ port: { label: "RDP Port", defaultValue: 3389 },
+ winrmPort: { label: "WinRM Port", defaultValue: 5985 },
+ useWinrmHttps: { label: "Use WinRM HTTPS" },
+ winrmRejectUnauthorized: {
+ label: "Reject Unauthorized (WinRM)",
+ showWhen: { field: "useWinrmHttps", equals: true }
+ },
+ winrmCaCert: {
+ label: "WinRM CA Certificate",
+ widget: PamFieldWidget.Textarea,
+ showWhen: { field: "useWinrmHttps", equals: true }
+ },
password: { widget: PamFieldWidget.Password, secret: true }
}
},
@@ -480,7 +495,11 @@ export const ACCOUNT_TYPE_CONFIGS = {
useLdaps: z.boolean(),
ldapRejectUnauthorized: z.boolean(),
ldapCaCert: optionalTrimmedString,
- ldapTlsServerName: optionalTrimmedString
+ ldapTlsServerName: optionalTrimmedString,
+ winrmPort: z.coerce.number().int().min(1).max(65535).default(5985),
+ useWinrmHttps: z.boolean().default(false),
+ winrmRejectUnauthorized: z.boolean().default(true),
+ winrmCaCert: optionalTrimmedString
}),
credentials: z.object({
username: z.string().trim().min(1).max(255),
@@ -517,6 +536,17 @@ export const ACCOUNT_TYPE_CONFIGS = {
label: "TLS Server Name",
showWhen: { field: "useLdaps", equals: true }
},
+ winrmPort: { label: "WinRM Port", defaultValue: 5985 },
+ useWinrmHttps: { label: "Use WinRM HTTPS" },
+ winrmRejectUnauthorized: {
+ label: "Reject Unauthorized (WinRM)",
+ showWhen: { field: "useWinrmHttps", equals: true }
+ },
+ winrmCaCert: {
+ label: "WinRM CA Certificate",
+ widget: PamFieldWidget.Textarea,
+ showWhen: { field: "useWinrmHttps", equals: true }
+ },
username: {
tooltip: "Use the DOMAIN\\username format for domain authentication (e.g. CORP\\Administrator)."
},
diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.test.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.test.ts
index df8f50f936..519b501b04 100644
--- a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.test.ts
+++ b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.test.ts
@@ -66,4 +66,29 @@ describe("resolveRunAsFingerprint", () => {
])("does not anchor a same-named account from another domain (%s)", (runAs) => {
expect(resolveRunAsFingerprint(runAs, domain, userGuidByName)).toBeNull();
});
+
+ test("accepts the real NetBIOS name when it differs from the DNS label", () => {
+ // Without the NetBIOS name, a CONTOSO\ run-as would be wrongly dropped (DNS label is "corp").
+ expect(resolveRunAsFingerprint("CONTOSO\\svc-sql", domain, userGuidByName)).toBeNull();
+ expect(resolveRunAsFingerprint("CONTOSO\\svc-sql", domain, userGuidByName, "CONTOSO")).toBe(
+ "corp.example.com:11111111-1111-1111-1111-111111111111"
+ );
+ });
+
+ const machine = { objectGUID: "99999999-9999-9999-9999-999999999999", name: "WEB01" };
+
+ test.each([[".\\localsvc"], ["WEB01\\localsvc"]])(
+ "anchors a local run-as (%s) to the machine's local account",
+ (runAs) => {
+ expect(resolveRunAsFingerprint(runAs, domain, userGuidByName, null, machine)).toBe(
+ `corp.example.com:${machine.objectGUID}:localsvc`
+ );
+ }
+ );
+
+ test("still anchors a domain run-as to the domain user when machine context is present", () => {
+ expect(resolveRunAsFingerprint("CORP\\svc-sql", domain, userGuidByName, null, machine)).toBe(
+ "corp.example.com:11111111-1111-1111-1111-111111111111"
+ );
+ });
});
diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts
index 4c74be4f7c..cb4dfc3fde 100644
--- a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts
+++ b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts
@@ -229,7 +229,10 @@ export const extractSamAccountName = (runAs: string): string | null => parseRunA
export const resolveRunAsFingerprint = (
runAs: string,
domain: string,
- userGuidByName: Map<string, string>
+ userGuidByName: Map<string, string>,
+ netbiosName?: string | null,
+ // The machine currently being swept; lets a local run-as anchor to that machine's local account.
+ machine?: { objectGUID: string; name: string }
): string | null => {
const parsed = parseRunAs(runAs);
if (!parsed) return null;
@@ -238,8 +241,18 @@ export const resolveRunAsFingerprint = (
if (parsed.domain !== null) {
const runAsDomain = parsed.domain.toLowerCase();
- const netbios = domain.split(".")[0]; // corp.example.com -> corp
- if (runAsDomain !== netbios && runAsDomain !== domain) return null;
+
+ // Local run-as (.\user or MACHINE\user for this machine) anchors to the machine's local account, whose
+ // fingerprint mirrors how enumerateLocalUsers mints it: domain:machineObjectGUID:username.
+ if (machine && (runAsDomain === "." || runAsDomain === machine.name.toLowerCase())) {
+ return `${domain}:${machine.objectGUID}:${account}`;
+ }
+
+ // Domain run-as: accept the DNS first label, the FQDN, or the real NetBIOS name (which can differ).
+ const accepted = [domain.split(".")[0], domain, netbiosName]
+ .filter((d): d is string => Boolean(d))
+ .map((d) => d.toLowerCase());
+ if (!accepted.includes(runAsDomain)) return null;
}
const guid = userGuidByName.get(account);
@@ -312,47 +325,68 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({
// Both local-account and dependency sweeps need the machine list from LDAP.
const enumerateComputers = Boolean(config.scanLocalAccounts || config.discoverDependencies);
- const { users, computers } = await runLdap<{ users: TLdapUser[]; computers: TLdapComputer[] }>(
- conn,
- credentials,
- gatewayId,
- gatewayV2Service,
- async (client) => {
- const userEntries = await ldapSearch(client, baseDN, "(&(objectClass=user)(objectCategory=person))", [
- "sAMAccountName",
- "objectGUID"
- ]);
- const parsedUsers = userEntries
- .map((entry) => ({
- sAMAccountName: getAttr(entry, "sAMAccountName"),
- objectGUID: parseObjectGUID(getAttrBuffer(entry, "objectGUID"))
- }))
- .filter((u) => u.sAMAccountName && u.objectGUID);
-
- if (!enumerateComputers) return { users: parsedUsers, computers: [] as TLdapComputer[] };
-
- const computerEntries = await ldapSearch(
+ const { users, computers, netbiosName } = await runLdap<{
+ users: TLdapUser[];
+ computers: TLdapComputer[];
+ netbiosName: string | null;
+ }>(conn, credentials, gatewayId, gatewayV2Service, async (client) => {
+ const userEntries = await ldapSearch(client, baseDN, "(&(objectClass=user)(objectCategory=person))", [
+ "sAMAccountName",
+ "objectGUID"
+ ]);
+ const parsedUsers = userEntries
+ .map((entry) => ({
+ sAMAccountName: getAttr(entry, "sAMAccountName"),
+ objectGUID: parseObjectGUID(getAttrBuffer(entry, "objectGUID"))
+ }))
+ .filter((u) => u.sAMAccountName && u.objectGUID);
+
+ if (!enumerateComputers) return { users: parsedUsers, computers: [] as TLdapComputer[], netbiosName: null };
+
+ const computerEntries = await ldapSearch(client, baseDN, "(&(objectClass=computer)(operatingSystem=*Server*))", [
+ "cn",
+ "dNSHostName",
+ "objectGUID"
+ ]);
+ const parsedComputers = computerEntries
+ .map((entry) => ({
+ cn: getAttr(entry, "cn"),
+ dNSHostName: getAttr(entry, "dNSHostName"),
+ objectGUID: parseObjectGUID(getAttrBuffer(entry, "objectGUID"))
+ }))
+ .filter((c) => (c.dNSHostName || c.cn) && c.objectGUID);
+
+ // The real NetBIOS domain name can differ from the DNS first label (renamed/legacy domains). Read it from
+ // the Partitions container so a NETBIOS\user run-as isn't wrongly rejected and its dependencies dropped.
+ let resolvedNetbios: string | null = null;
+ try {
+ const partitions = await ldapSearch(
client,
- baseDN,
- "(&(objectClass=computer)(operatingSystem=*Server*))",
- ["cn", "dNSHostName", "objectGUID"]
+ `CN=Partitions,CN=Configuration,${baseDN}`,
+ `(&(objectClass=crossRef)(nETBIOSName=*)(nCName=${baseDN}))`,
+ ["nETBIOSName"]
);
- const parsedComputers = computerEntries
- .map((entry) => ({
- cn: getAttr(entry, "cn"),
- dNSHostName: getAttr(entry, "dNSHostName"),
- objectGUID: parseObjectGUID(getAttrBuffer(entry, "objectGUID"))
- }))
- .filter((c) => (c.dNSHostName || c.cn) && c.objectGUID);
-
- return { users: parsedUsers, computers: parsedComputers };
+ resolvedNetbios = partitions.length ? getAttr(partitions[0], "nETBIOSName") || null : null;
+ } catch (err) {
+ logger.warn(err, `PAM AD discovery could not read the NetBIOS name; using the DNS label [domain=${domain}]`);
}
- );
+
+ return { users: parsedUsers, computers: parsedComputers, netbiosName: resolvedNetbios };
+ });
logger.info(
`PAM AD discovery enumerated ${users.length} domain accounts and ${computers.length} servers [domain=${domain}]`
);
+ // Carry the source's WinRM settings onto imported accounts so rotation and dependency sync honor HTTPS /
+ // a custom port / a pinned CA (the account connection schema has no separate WinRM discovery step).
+ const winrmConnDetails = {
+ winrmPort: config.winrmPort ?? 5985,
+ useWinrmHttps: config.useWinrmHttps ?? false,
+ winrmRejectUnauthorized: config.winrmRejectUnauthorized ?? true,
+ ...(config.winrmCaCert ? { winrmCaCert: config.winrmCaCert } : {})
+ };
+
// Domain accounts inherit the source's connection target; only the login user differs
const domainShortName = domain.split(".")[0];
const discovered: TDiscoveredAccount[] = users.map((u) => ({
@@ -361,11 +395,20 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({
.slice(0, 64)
.replace(TRAILING_HYPHENS_REGEX, ""),
fingerprint: `${domain}:${u.objectGUID}`,
- details: { connectionDetails, credentials: { username: u.sAMAccountName } }
+ details: {
+ connectionDetails: { ...connectionDetails, ...winrmConnDetails },
+ credentials: { username: u.sAMAccountName }
+ }
}));
if (enumerateComputers && computers.length > 0) {
- await resolveHostnamesViaDc(computers, conn, gatewayId, gatewayV2Service);
+ // A DC unreachable on TCP/53 must not abort the whole scan (account enumeration already succeeded);
+ // WinRM then falls back to the hostname, which resolves in environments where the gateway has DNS.
+ try {
+ await resolveHostnamesViaDc(computers, conn, gatewayId, gatewayV2Service);
+ } catch (err) {
+ logger.warn(err, `PAM AD discovery could not resolve hostnames via the DC; using hostnames [domain=${domain}]`);
+ }
const winrm: TWinrmConfig = {
port: config.winrmPort ?? 5985,
@@ -396,7 +439,7 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({
.replace(TRAILING_HYPHENS_REGEX, ""),
fingerprint: `${domain}:${computer.objectGUID}:${u.Name.toLowerCase()}`,
details: {
- connectionDetails: { host, port: connectionDetails.rdpPort },
+ connectionDetails: { host, port: connectionDetails.rdpPort, ...winrmConnDetails },
credentials: { username: u.Name }
}
});
@@ -421,8 +464,12 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({
);
for (const dep of machineDeps) {
- // built-in or non-domain run-as resolves to null: nothing to anchor to an account or rotate
- const fingerprint = resolveRunAsFingerprint(dep.runAs, domain, userGuidByName);
+ // built-in run-as resolves to null: nothing to anchor to an account or rotate. A local run-as
+ // anchors to this machine's local account; a domain run-as to the enumerated domain user.
+ const fingerprint = resolveRunAsFingerprint(dep.runAs, domain, userGuidByName, netbiosName, {
+ objectGUID: computer.objectGUID,
+ name: computer.cn
+ });
if (fingerprint) {
dependencies.push({
fingerprint,
diff --git a/backend/src/ee/services/pam-discovery/pam-account-dependency-dal.ts b/backend/src/ee/services/pam-discovery/pam-account-dependency-dal.ts
index 41b37defcc..f2cd84bc59 100644
--- a/backend/src/ee/services/pam-discovery/pam-account-dependency-dal.ts
+++ b/backend/src/ee/services/pam-discovery/pam-account-dependency-dal.ts
@@ -23,12 +23,24 @@ export const pamAccountDependencyDALFactory = (db: TDbClient) => {
// INSERT ... ON CONFLICT) so overlapping scans of the same machine can't race on the unique index. Discovery
// owns fingerprint / machine / type / name / data and the account linkage; on conflict only those are merged,
// so rotation-owned columns (rotationStatus, lastRotatedAt, encryptedLastRotationMessage) are never touched.
+ //
+ // Imported wins: a row already linked to a managed account (accountId set) is never demoted back to a staged
+ // link, so a second discovery source scanning the same machine can't silently break rotation sync for an
+ // account another source imported.
const upsertByIdentity = async (dep: TUpsertDependency, tx?: Knex): Promise<string> => {
+ const conn = tx || db;
const { fingerprint, machine, type, name, data, accountId, discoveredAccountId } = dep;
- const [row] = await (tx || db)(TableName.PamAccountDependency)
+ const [row] = await conn(TableName.PamAccountDependency)
.insert({ fingerprint, machine, type, name, data, accountId, discoveredAccountId })
.onConflict(["fingerprint", "machine", "type", "name"])
- .merge({ data, accountId, discoveredAccountId })
+ .merge({
+ data,
+ accountId: conn.raw(`COALESCE(??."accountId", EXCLUDED."accountId")`, [TableName.PamAccountDependency]),
+ discoveredAccountId: conn.raw(
+ `CASE WHEN ??."accountId" IS NOT NULL THEN NULL ELSE EXCLUDED."discoveredAccountId" END`,
+ [TableName.PamAccountDependency]
+ )
+ })
.returning("id");
return row.id;
};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts b/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
index 99e6ea164b..c6daa188a3 100644
--- a/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
@@ -8,6 +8,7 @@ import { callWinRmEndpoint, WinRmRpcEndpoint } from "@app/lib/gateway-v2/winrm-r
import { verifyHostInputValidity } from "../dynamic-secret/dynamic-secret-fns";
import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";
+import { resolveDnsTcp } from "./active-directory/dns-over-dc";
type TGatewayDep = Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
@@ -72,6 +73,31 @@ export const executeWithGateway = async <T>(
});
};
+// Resolve hostnames to IPs through the DC's DNS in one gateway session. Used at rotation-sync time so a
+// dependency's machine is targeted by a fresh IP (a scan-time snapshot can go stale via DHCP). Never throws;
+// unresolved hosts are simply absent from the map.
+export const resolveHostsViaDcDns = async (
+ hostnames: string[],
+ dcAddress: string,
+ gatewayId: string,
+ gatewayV2Service: TGatewayDep
+): Promise<Map<string, string>> => {
+ if (!hostnames.length) return new Map();
+ return executeWithGateway(dcAddress, 53, gatewayId, gatewayV2Service, async (proxyPort) => {
+ const resolved = new Map<string, string>();
+ for (const hostname of hostnames) {
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ const ip = await resolveDnsTcp(hostname, proxyPort);
+ if (ip) resolved.set(hostname, ip);
+ } catch {
+ // leave unresolved; the caller falls back to a stored IP or the hostname
+ }
+ }
+ return resolved;
+ });
+};
+
const LDAP_BIND_CHECK_TIMEOUT_MS = 15 * 1000;
// Confirms directory credentials by performing an LDAP simple bind through the gateway. Used to verify a