Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(pam): certificate based auth for ssh
x0322051317edeb4578
diff --git a/backend/src/db/migrations/20251211120000_pam-ssh-resource-ca-keypair.ts b/backend/src/db/migrations/20251211120000_pam-ssh-resource-ca-keypair.tsnew file mode 100644index 0000000000..a3ea5e1df5--- /dev/null+++ b/backend/src/db/migrations/20251211120000_pam-ssh-resource-ca-keypair.ts@@ -0,0 +1,39 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasColumn(TableName.PamResource, "encryptedCaPrivateKey"))) {+ await knex.schema.alterTable(TableName.PamResource, (t) => {+ t.binary("encryptedCaPrivateKey").nullable();+ });+ }+ if (!(await knex.schema.hasColumn(TableName.PamResource, "caPublicKey"))) {+ await knex.schema.alterTable(TableName.PamResource, (t) => {+ t.text("caPublicKey").nullable();+ });+ }+ if (!(await knex.schema.hasColumn(TableName.PamResource, "caKeyAlgorithm"))) {+ await knex.schema.alterTable(TableName.PamResource, (t) => {+ t.string("caKeyAlgorithm").nullable();+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ if (await knex.schema.hasColumn(TableName.PamResource, "encryptedCaPrivateKey")) {+ await knex.schema.alterTable(TableName.PamResource, (t) => {+ t.dropColumn("encryptedCaPrivateKey");+ });+ }+ if (await knex.schema.hasColumn(TableName.PamResource, "caPublicKey")) {+ await knex.schema.alterTable(TableName.PamResource, (t) => {+ t.dropColumn("caPublicKey");+ });+ }+ if (await knex.schema.hasColumn(TableName.PamResource, "caKeyAlgorithm")) {+ await knex.schema.alterTable(TableName.PamResource, (t) => {+ t.dropColumn("caKeyAlgorithm");+ });+ }+}diff --git a/backend/src/db/schemas/pam-resources.ts b/backend/src/db/schemas/pam-resources.tsindex f59aae5d87..94311823e8 100644--- a/backend/src/db/schemas/pam-resources.ts+++ b/backend/src/db/schemas/pam-resources.ts@@ -18,7 +18,10 @@ export const PamResourcesSchema = z.object({encryptedConnectionDetails: zodBuffer,createdAt: z.date(),updatedAt: z.date(),- encryptedRotationAccountCredentials: zodBuffer.nullable().optional()+ encryptedRotationAccountCredentials: zodBuffer.nullable().optional(),+ encryptedCaPrivateKey: zodBuffer.nullable().optional(),+ caPublicKey: z.string().nullable().optional(),+ caKeyAlgorithm: z.string().nullable().optional()});export type TPamResources = z.infer<typeof PamResourcesSchema>;diff --git a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-endpoints.ts b/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-endpoints.tsindex e3803316ef..915e7df071 100644--- a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-endpoints.ts+++ b/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-endpoints.ts@@ -3,6 +3,7 @@ import { z } from "zod";import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";import { TPamResource } from "@app/ee/services/pam-resource/pam-resource-types";+import { BadRequestError } from "@app/lib/errors";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";@@ -197,4 +198,101 @@ export const registerPamResourceEndpoints = <T extends TPamResource>({return { resource };}});++ server.route({+ method: "GET",+ url: "/:resourceId/ssh-ca-setup",+ config: {+ rateLimit: readLimit+ },+ schema: {+ description: "Get PAM resource SSH CA setup script for configuring the target server to trust the CA",+ params: z.object({+ resourceId: z.string().uuid()+ }),+ response: {+ 200: z.string()+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req, reply) => {+ if (resourceType !== PamResource.SSH) {+ throw new BadRequestError({ message: "This endpoint is only available for SSH resources" });+ }++ const { caPublicKey } = await server.services.pamResource.getOrCreateSshCa(req.params.resourceId, req.permission);++ const setupScript = `#!/bin/bash+set -e++CA_PUBLIC_KEY="${caPublicKey}"+CA_FILE="/etc/ssh/infisical_ca.pub"+SSHD_CONFIG="/etc/ssh/sshd_config"++echo "==> Infisical SSH CA Setup"+echo ""++if [ "$(id -u)" -ne 0 ]; then+ echo "Error: This script must be run as root (use sudo)"+ exit 1+fi++echo "==> Writing CA public key to \${CA_FILE}..."+echo "\${CA_PUBLIC_KEY}" > "\${CA_FILE}"+chmod 644 "\${CA_FILE}"+echo " Done."++if grep -q "^TrustedUserCAKeys" "\${SSHD_CONFIG}"; then+ EXISTING_CA_FILE=$(grep "^TrustedUserCAKeys" "\${SSHD_CONFIG}" | awk '{print $2}')+ if [ "\${EXISTING_CA_FILE}" = "\${CA_FILE}" ]; then+ echo "==> TrustedUserCAKeys already configured for \${CA_FILE}"+ else+ echo "Warning: TrustedUserCAKeys is already set to \${EXISTING_CA_FILE}"+ echo " You may need to manually update sshd_config to use \${CA_FILE}"+ echo " or combine multiple CA keys into a single file."+ fi+else+ echo "==> Adding TrustedUserCAKeys to \${SSHD_CONFIG}..."+ echo "" >> "\${SSHD_CONFIG}"+ echo "# Infisical SSH CA - Added by setup script" >> "\${SSHD_CONFIG}"+ echo "TrustedUserCAKeys \${CA_FILE}" >> "\${SSHD_CONFIG}"+ echo " Done."+fi++echo "==> Validating SSH configuration..."+if sshd -t; then+ echo " Configuration is valid."+else+ echo "Error: SSH configuration is invalid. Please check \${SSHD_CONFIG}"+ exit 1+fi++echo "==> Restarting SSH service..."+if command -v systemctl &> /dev/null; then+ if systemctl cat sshd.service &>/dev/null; then+ systemctl restart sshd+ elif systemctl cat ssh.service &>/dev/null; then+ systemctl restart ssh+ else+ echo "Warning: Could not find SSH service. Please restart it manually."+ fi+elif command -v service &> /dev/null; then+ service sshd restart 2>/dev/null || service ssh restart+else+ echo "Warning: Could not detect init system. Please restart sshd manually."+fi+echo " Done."++echo ""+echo "==> Setup complete!"+echo ""+echo "Your SSH server is now configured to trust certificates signed by the Infisical CA."+echo "Users with valid certificates can now authenticate without passwords."+echo ""+`;++ void reply.header("Content-Type", "text/plain; charset=utf-8");+ return setupScript;+ }+ });};diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.tsindex ec8b37c365..8f62b07200 100644--- a/backend/src/ee/services/pam-account/pam-account-service.ts+++ b/backend/src/ee/services/pam-account/pam-account-service.ts@@ -10,12 +10,16 @@ import {} from "@app/ee/services/pam-resource/aws-iam";import { PAM_RESOURCE_FACTORY_MAP } from "@app/ee/services/pam-resource/pam-resource-factory";import { decryptResource, decryptResourceConnectionDetails } from "@app/ee/services/pam-resource/pam-resource-fns";+import { SSHAuthMethod } from "@app/ee/services/pam-resource/ssh/ssh-resource-enums";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import {ProjectPermissionActions,ProjectPermissionPamAccountActions,ProjectPermissionSub} from "@app/ee/services/permission/project-permission";+import { createSshCert, createSshKeyPair } from "@app/ee/services/ssh/ssh-certificate-authority-fns";+import { SshCertType } from "@app/ee/services/ssh/ssh-certificate-authority-types";+import { SshCertKeyAlgorithm } from "@app/ee/services/ssh-certificate/ssh-certificate-types";import { DatabaseErrorCode } from "@app/lib/error-codes";import {BadRequestError,@@ -857,6 +861,58 @@ export const pamAccountServiceFactory = ({sessionStarted = true;}+ // Handle SSH certificate-based authentication+ if (decryptedResource.resourceType === PamResource.SSH) {+ const accountCredentials = decryptedAccount.credentials as TSSHAccountCredentials;++ if (accountCredentials.authMethod === SSHAuthMethod.Certificate) {+ if (!resource.encryptedCaPrivateKey) {+ throw new BadRequestError({+ message: "SSH resource does not have a CA configured for certificate-based authentication"+ });+ }++ const { decryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId: session.projectId+ });++ const caPrivateKey = decryptor({+ cipherTextBlob: resource.encryptedCaPrivateKey+ }).toString("utf8");++ // Generate a new key pair for the user+ const keyAlgorithm = (resource.caKeyAlgorithm as SshCertKeyAlgorithm) || SshCertKeyAlgorithm.ED25519;+ const { publicKey, privateKey } = await createSshKeyPair(keyAlgorithm);++ // Calculate TTL from session expiry+ const ttlSeconds = Math.max(Math.floor((session.expiresAt.getTime() - Date.now()) / 1000), 60);++ // Sign the public key with the CA to create a certificate+ const { signedPublicKey } = await createSshCert({+ caPrivateKey,+ clientPublicKey: publicKey,+ keyId: `pam-session-${session.id}`,+ principals: [accountCredentials.username],+ requestedTtl: `${ttlSeconds}s`,+ certType: SshCertType.USER+ });++ return {+ credentials: {+ ...decryptedResource.connectionDetails,+ authMethod: SSHAuthMethod.Certificate,+ username: accountCredentials.username,+ privateKey,+ certificate: signedPublicKey+ },+ projectId: project.id,+ account,+ sessionStarted+ };+ }+ }+return {credentials: {...decryptedResource.connectionDetails,diff --git a/backend/src/ee/services/pam-resource/pam-resource-service.ts b/backend/src/ee/services/pam-resource/pam-resource-service.tsindex abbbf651b7..960f633eea 100644--- a/backend/src/ee/services/pam-resource/pam-resource-service.ts+++ b/backend/src/ee/services/pam-resource/pam-resource-service.ts@@ -3,10 +3,13 @@ import { ForbiddenError } from "@casl/ability";import { ActionProjectType, TPamResources } from "@app/db/schemas";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";+import { createSshKeyPair } from "@app/ee/services/ssh/ssh-certificate-authority-fns";+import { SshCertKeyAlgorithm } from "@app/ee/services/ssh-certificate/ssh-certificate-types";import { DatabaseErrorCode } from "@app/lib/error-codes";import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";import { OrgServiceActor } from "@app/lib/types";import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { KmsDataKey } from "@app/services/kms/kms-types";import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";import { TLicenseServiceFactory } from "../license/license-service";@@ -290,12 +293,57 @@ export const pamResourceServiceFactory = ({};};+ const getOrCreateSshCa = async (resourceId: string, actor: OrgServiceActor) => {+ const resource = await pamResourceDAL.findById(resourceId);+ if (!resource) throw new NotFoundError({ message: `Resource with ID '${resourceId}' not found` });++ if (resource.resourceType !== PamResource.SSH) {+ throw new BadRequestError({ message: "This operation is only available for SSH resources" });+ }++ const { permission } = await permissionService.getProjectPermission({+ actor: actor.type,+ actorAuthMethod: actor.authMethod,+ actorId: actor.id,+ actorOrgId: actor.orgId,+ projectId: resource.projectId,+ actionProjectType: ActionProjectType.PAM+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PamResources);++ if (resource.caPublicKey) {+ return { caPublicKey: resource.caPublicKey };+ }++ // Generate new CA key pair+ const keyAlgorithm = SshCertKeyAlgorithm.ED25519;+ const { publicKey, privateKey } = await createSshKeyPair(keyAlgorithm);++ const { encryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId: resource.projectId+ });++ const encryptedCaPrivateKey = encryptor({ plainText: Buffer.from(privateKey, "utf8") }).cipherTextBlob;+ const caPublicKey = publicKey.trim();++ await pamResourceDAL.updateById(resourceId, {+ encryptedCaPrivateKey,+ caPublicKey,+ caKeyAlgorithm: keyAlgorithm+ });++ return { caPublicKey };+ };+return {getById,create,updateById,deleteById,list,- listResourceOptions+ listResourceOptions,+ getOrCreateSshCa};};diff --git a/backend/src/ee/services/pam-resource/ssh/ssh-resource-factory.ts b/backend/src/ee/services/pam-resource/ssh/ssh-resource-factory.tsindex dfbb071e24..e871553630 100644--- a/backend/src/ee/services/pam-resource/ssh/ssh-resource-factory.ts+++ b/backend/src/ee/services/pam-resource/ssh/ssh-resource-factory.ts@@ -191,6 +191,15 @@ export const sshResourceFactory: TPamResourceFactory<TSSHResourceConnectionDetaitryKeyboard: false});break;+ case SSHAuthMethod.Certificate:+ // For certificate auth, we don't validate by connecting to the SSH server+ // The certificate will be issued on-demand when the session is accessed+ logger.info(+ { username: credentials.username },+ "[SSH Resource Factory] Certificate auth method selected - skipping SSH connection validation"+ );+ resolve();+ break;default:reject(new Error(`Unsupported SSH auth method: ${(credentials as TSSHAccountCredentials).authMethod}`));}diff --git a/backend/src/ee/services/pam-resource/ssh/ssh-resource-schemas.ts b/backend/src/ee/services/pam-resource/ssh/ssh-resource-schemas.tsindex 01b8ef2c06..ef79f864e0 100644--- a/backend/src/ee/services/pam-resource/ssh/ssh-resource-schemas.ts+++ b/backend/src/ee/services/pam-resource/ssh/ssh-resource-schemas.ts@@ -47,6 +47,16 @@ export const SSHAccountCredentialsSchema = z.discriminatedUnion("authMethod", [SSHCertificateCredentialsSchema]);+// Schema for session credentials - includes certificate with keys+export const SSHSessionAccountCredentialsSchema = z.discriminatedUnion("authMethod", [+ SSHPasswordCredentialsSchema,+ SSHPublicKeyCredentialsSchema,+ SSHCertificateCredentialsSchema.extend({+ privateKey: z.string().trim().max(5000),+ certificate: z.string().trim().max(5000)+ })+]);+export const SSHResourceSchema = BaseSSHResourceSchema.extend({connectionDetails: SSHResourceConnectionDetailsSchema,rotationAccountCredentials: SSHAccountCredentialsSchema.nullable().optional()@@ -114,4 +124,4 @@ export const SanitizedSSHAccountWithResourceSchema = BasePamAccountSchemaWithRes});// Sessions-export const SSHSessionCredentialsSchema = SSHResourceConnectionDetailsSchema.and(SSHAccountCredentialsSchema);+export const SSHSessionCredentialsSchema = SSHResourceConnectionDetailsSchema.and(SSHSessionAccountCredentialsSchema);diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/SSHResourceForm.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/SSHResourceForm.tsxindex 4e15f6f52f..9d430908ab 100644--- a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/SSHResourceForm.tsx+++ b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/SSHResourceForm.tsx@@ -1,9 +1,16 @@+import { useEffect, useState } from "react";import { Controller, FormProvider, useForm } from "react-hook-form";+import { faCopy } from "@fortawesome/free-regular-svg-icons";+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { zodResolver } from "@hookform/resolvers/zod";+import { ChevronDownIcon, ShieldIcon } from "lucide-react";+import { twMerge } from "tailwind-merge";import { z } from "zod";-import { Button, FormControl, Input, ModalClose } from "@app/components/v2";+import { createNotification } from "@app/components/notifications";+import { Button, FormControl, IconButton, Input, ModalClose } from "@app/components/v2";import { PamResourceType, TSSHResource } from "@app/hooks/api/pam";+import { getAuthToken } from "@app/hooks/api/reactQuery";import { GenericResourceFields, genericResourceFieldsSchema } from "./GenericResourceFields";@@ -25,8 +32,21 @@ const formSchema = genericResourceFieldsSchema.extend({type FormData = z.infer<typeof formSchema>;export const SSHResourceForm = ({ resource, onSubmit }: Props) => {+ const { protocol, hostname, port } = window.location;+ const portSuffix = port && port !== "80" ? `:${port}` : "";+ const siteURL = `${protocol}//${hostname}${portSuffix}`;+const isUpdate = Boolean(resource);+ const [setupSshCaCommand, setSetupSshCaCommand] = useState("");+ const [cmdOpen, setCmdOpen] = useState(false);++ useEffect(() => {+ setSetupSshCaCommand(+ `curl -H "Authorization: Bearer ${getAuthToken()}" "${siteURL}/api/v1/pam/resources/ssh/${resource?.id}/ssh-ca-setup" | sudo bash`+ );+ }, [getAuthToken, siteURL, resource]);+const form = useForm<FormData>({resolver: zodResolver(formSchema),defaultValues: resource ?? {@@ -48,7 +68,7 @@ export const SSHResourceForm = ({ resource, onSubmit }: Props) => {<FormProvider {...form}><form onSubmit={handleSubmit(onSubmit)}><GenericResourceFields />- <div className="mb-4 rounded-sm border border-mineshaft-600 bg-mineshaft-700/70 p-3">+ <div className="mb-4 rounded-sm border border-mineshaft-600 bg-mineshaft-700/70 p-3 pb-0"><div className="mt-[0.675rem] flex items-start gap-2"><Controllername="connectionDetails.host"@@ -80,6 +100,72 @@ export const SSHResourceForm = ({ resource, onSubmit }: Props) => {/></div></div>+ <button+ type="button"+ onClick={() => setCmdOpen(!cmdOpen)}+ className="mb-4 flex w-full cursor-pointer flex-col rounded-md border border-mineshaft-500 bg-mineshaft-700 p-3 text-sm hover:bg-mineshaft-600"+ >+ <div className="flex gap-2.5">+ <ShieldIcon className="mt-0.5 size-6 shrink-0 text-info" />+ <div className="flex w-full flex-col">+ <div className="flex justify-between gap-2 pr-1">+ <div className="flex flex-col text-left">+ <span className="text-base">Certificate-Based Authentication</span>+ <span className="text-sm text-mineshaft-300">+ Optional: Install CA certificate if you plan to use certificate authentication+ for user accounts+ </span>+ </div>+ <ChevronDownIcon+ className={twMerge(+ "shrink-0 text-mineshaft-400 transition-transform duration-200 ease-in-out",+ cmdOpen && "rotate-180"+ )}+ />+ </div>+ <div+ className={twMerge(+ "grid transition-all duration-200 ease-in-out",+ cmdOpen ? "mt-2 grid-rows-[1fr]" : "mt-0 grid-rows-[0fr]"+ )}+ >+ <div className="overflow-hidden">+ <div className="flex flex-col text-left">+ <span className="mt-2 text-sm text-mineshaft-300">+ Run this command on the target host:+ </span>+ <div className="mt-1 flex items-center gap-1">+ <Input value={setupSshCaCommand} isDisabled />+ <IconButton+ ariaLabel="copy"+ variant="plain"+ colorSchema="secondary"+ size="sm"+ onClick={(e) => {+ e.stopPropagation();+ navigator.clipboard.writeText(setupSshCaCommand);+ createNotification({+ text: "Command copied to clipboard",+ type: "info"+ });+ }}+ className="size-8 shrink-0"+ >+ <FontAwesomeIcon icon={faCopy} className="text-mineshaft-200" />+ </IconButton>+ </div>+ <div className="mt-4 flex flex-col gap-1 text-xs text-mineshaft-300">+ <span>This command will:</span>+ <span>• Install the resource CA certificate</span>+ <span>• Configure SSH to trust certificate-based authentication</span>+ <span>• Enable seamless access for authorized users</span>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+ </button><div className="mt-6 flex items-center"><ButtonclassName="mr-4"