New-CertKitAppProxyIdentity.ps1
|
<#PSScriptInfo .VERSION 2.0.1 .GUID a9e0f308-5a4c-4ee6-a6f9-452dc867ee72 .AUTHOR Richard Hicks .COMPANYNAME Richard M. Hicks Consulting, Inc. .COPYRIGHT Copyright (C) 2026 Richard M. Hicks Consulting, Inc. All Rights Reserved. .LICENSE Licensed under the MIT License. See LICENSE file in the project root for full license information. .LICENSEURI https://github.com/richardhicks/certkit/blob/main/LICENSE .PROJECTURI https://github.com/richardhicks/certkit .TAGS CertKit, Entra, EntraID, AppProxy, ApplicationProxy, Certificate, TLS, SSL, MicrosoftGraph, Graph, ServicePrincipal, PIM, LeastPrivilege, TPM #> <# .SYNOPSIS Creates or configures a least-privilege Microsoft Entra identity for CertKit to deploy TLS certificates to Entra Application Proxy applications, using certificate, client secret, or managed identity authentication. .DESCRIPTION This script configures everything CertKit needs to deploy certificates to Microsoft Entra Application Proxy applications, following least privilege. It supports three authentication methods. Starting with version 2.0, certificate authentication is the default. Use -UseClientSecret for client secret authentication. Certificate authentication (default): - A dedicated app registration and service principal for CertKit. - A self-signed certificate (RSA 2048, SHA256) with the subject 'CN=CertKit App Proxy Agent' and no subject alternative names, created in the local computer's personal store (Cert:\LocalMachine\My). The private key is non-exportable and is created in the TPM when one is available, otherwise by the Microsoft Software Key Storage Provider. - The certificate has the Client Authentication EKU, or a custom EKU under your organization's IANA private enterprise number (PEN) when -CustomEku is specified. - The public certificate is uploaded to the app registration, named 'CertKit Agent - <computer name>' so each server's certificates can be told apart. - The script must run elevated on the server running the CertKit agent, because the private key can't leave the computer it was created on. Client secret authentication (-UseClientSecret): - A dedicated app registration and service principal for CertKit. - A client secret, which is copied to the clipboard and never displayed on screen. Managed identity authentication (-ManagedIdentityId): - Uses an existing user-assigned or system-assigned managed identity attached to the server running the CertKit agent. The script doesn't create the managed identity, which is an Azure resource. All methods: - A custom Entra role that can only read Application Proxy settings and update the Application Proxy SSL certificate. - The read-only Microsoft Graph application permission Application.Read.All, used by CertKit to find App Proxy applications. - A tenant-wide assignment of the custom role to the CertKit identity, made directly or through Privileged Identity Management (PIM). The script is safe to run more than once. Existing objects with the same names are reused, and existing role and permission assignments are not duplicated. A new certificate or client secret is created on every run. Expired certificates and client secrets are always removed from the app registration, and expired CertKit certificates are removed from the local computer's store. Use -RemoveExistingCertificates or -RemoveExistingSecrets to also remove older credentials that are still valid. .PARAMETER TenantId The tenant ID (GUID) or a verified domain name of the Microsoft Entra tenant to configure. Optional. If omitted, the script uses the tenant of the account you sign in with. Specify this parameter when your account has access to more than one tenant, such as a guest account in a customer tenant, or when the PowerShell session is already connected to Microsoft Graph in another tenant. .PARAMETER DisplayName The display name of the CertKit app registration. Certificate and client secret authentication only. The default is 'CertKit App Proxy Deployment'. .PARAMETER CertificateValidityDays The lifetime of the certificate in days: 30, 90, 180, or 365. Certificate authentication only. The default is 365. Shorter lifetimes are only practical when certificate rotation is automated. .PARAMETER CustomEku A custom enhanced key usage (EKU) object identifier to use instead of Client Authentication. Certificate authentication only. It must be under your organization's IANA private enterprise number, in the form 1.3.6.1.4.1.<PEN>.<arc>[.<arc>...], with at least one arc after the PEN and no leading zeros. Entra ID doesn't check the EKU. A custom EKU prevents the certificate from being used for general client authentication and documents its purpose. The script checks the format only. It can't confirm the PEN is assigned to your organization. .PARAMETER RequireTpm Fails instead of falling back to the software key storage provider when the private key can't be created in the TPM. Certificate authentication only. Without this switch, the TPM is used when available, and a warning is shown when the software key storage provider is used instead. .PARAMETER RemoveExistingCertificates Certificate authentication only. Removes the older certificates this server uploaded to the app registration, and deletes them and their private keys from the local computer's store, after the new certificate is uploaded. Certificates uploaded by other servers aren't removed. CertKit can't authenticate with a removed certificate, so update CertKit with the new certificate right away. .PARAMETER UseClientSecret Selects client secret authentication instead of the default certificate authentication. .PARAMETER SecretExpirationMonths The lifetime of the client secret in months, from 1 to 12. Client secret authentication only. The default is 12. .PARAMETER RemoveExistingSecrets Client secret authentication only. Removes all other client secrets from the app registration after the new client secret is created. Use this when rotating the secret or replacing a secret that was lost. CertKit can't authenticate with a removed secret, so update CertKit with the new secret right away. Without this switch, existing secrets that are still valid are kept and the script reports how many remain. .PARAMETER ManagedIdentityId The object (principal) ID or client ID of an existing managed identity to configure for CertKit. Selects managed identity authentication. The managed identity must already exist and be attached to the server running the CertKit agent. Both values are shown on the managed identity's Overview page in the Azure portal. .PARAMETER RoleName The display name of the custom Entra role. The default is 'App Proxy Certificate Manager'. .PARAMETER UsePim Assigns the custom role through Privileged Identity Management (PIM) as a permanent active assignment. Requires Microsoft Entra ID P2 or Microsoft Entra ID Governance. Without this switch, the role is assigned directly. When the custom role is newly created, PIM can take several minutes to recognize it, and the script waits up to 10 minutes. .INPUTS None. .OUTPUTS System.Management.Automation.PSCustomObject .EXAMPLE .\New-CertKitAppProxyIdentity.ps1 Run elevated on the CertKit agent server. Creates the CertKit identity with the default names and a one-year certificate with the Client Authentication EKU, stored in the TPM when available, and assigns the custom role directly. .EXAMPLE .\New-CertKitAppProxyIdentity.ps1 -CertificateValidityDays 90 -RequireTpm Creates a 90-day certificate and fails if the private key can't be created in the TPM. .EXAMPLE .\New-CertKitAppProxyIdentity.ps1 -CustomEku 1.3.6.1.4.1.32473.1.1 Creates a certificate with the custom EKU 1.3.6.1.4.1.32473.1.1 instead of Client Authentication. Replace 32473 (the PEN reserved for documentation) with your organization's PEN. .EXAMPLE .\New-CertKitAppProxyIdentity.ps1 -RemoveExistingCertificates Creates a new certificate for the existing CertKit identity, and removes the older certificates this server uploaded from the app registration and the local computer's store. .EXAMPLE .\New-CertKitAppProxyIdentity.ps1 -UseClientSecret -SecretExpirationMonths 6 -UsePim Creates the CertKit identity with a 6-month client secret, and assigns the custom role through PIM. .EXAMPLE .\New-CertKitAppProxyIdentity.ps1 -UseClientSecret -RemoveExistingSecrets Creates a new client secret for the existing CertKit identity and removes all older client secrets. .EXAMPLE .\New-CertKitAppProxyIdentity.ps1 -TenantId contoso.onmicrosoft.com Signs in to the contoso.onmicrosoft.com tenant and creates the CertKit identity there, regardless of the account's home tenant. .EXAMPLE .\New-CertKitAppProxyIdentity.ps1 -ManagedIdentityId e7ceec4e-6431-429a-8a17-c6127b14d3ef -UsePim Configures an existing managed identity for CertKit, identified by its client ID, and assigns the custom role through PIM. Enter the managed identity's client ID in the CertKit deployment. .LINK https://directaccess.richardhicks.com/ .NOTES Version: 2.0.1 Creation Date: November 14, 2026 Last Updated: December 1, 2026 Author: Richard Hicks Organization: Richard M. Hicks Consulting, Inc. Contact: rich@richardhicks.com Website: https://www.richardhicks.com/ Requirements: - Microsoft Entra ID P1 or higher (required for Application Proxy and custom roles). - The Microsoft.Graph.Authentication PowerShell module. - An account with at least the Privileged Role Administrator role. - For certificate authentication, run the script elevated on the Windows server running the CertKit agent. - For certificate and managed identity authentication, the Microsoft.Graph.Authentication module must also be installed for all users on the server running the CertKit agent, since the agent runs as Local System and signs in with Connect-MgGraph. With certificate authentication, the script warns when it isn't. Version 2.0 makes certificate authentication the default. Scripts that relied on client secret authentication by default must now add -UseClientSecret. The maximum client secret lifetime is now 12 months. #> #Requires -Version 5.1 #Requires -Modules @{ ModuleName = 'Microsoft.Graph.Authentication'; ModuleVersion = '2.0.0' } [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'Certificate')] Param ( [string]$TenantId, [Parameter(ParameterSetName = 'Certificate')] [Parameter(ParameterSetName = 'ClientSecret')] [string]$DisplayName = 'CertKit App Proxy Deployment', [Parameter(ParameterSetName = 'Certificate')] [ValidateSet(30, 90, 180, 365)] [int]$CertificateValidityDays = 365, [Parameter(ParameterSetName = 'Certificate')] [ValidateScript({ If ($_ -match '^1\.3\.6\.1\.4\.1\.[1-9]\d*(\.(0|[1-9]\d*))+$') { $true } Else { Throw "'$_' isn't a valid private enterprise number (PEN) OID. Use the form 1.3.6.1.4.1.<PEN>.<arc>[.<arc>...], with at least one arc after the PEN and no leading zeros." } })] [string]$CustomEku, [Parameter(ParameterSetName = 'Certificate')] [switch]$RequireTpm, [Parameter(ParameterSetName = 'Certificate')] [switch]$RemoveExistingCertificates, [Parameter(ParameterSetName = 'ClientSecret')] [switch]$UseClientSecret, [Parameter(ParameterSetName = 'ClientSecret')] [ValidateRange(1, 12)] [int]$SecretExpirationMonths = 12, [Parameter(ParameterSetName = 'ClientSecret')] [switch]$RemoveExistingSecrets, [Parameter(Mandatory, ParameterSetName = 'ManagedIdentity')] [ValidatePattern('^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$')] [string]$ManagedIdentityId, [string]$RoleName = 'App Proxy Certificate Manager', [switch]$UsePim ) #Region Logging # Start transcript, including -WhatIf runs $LogPath = Join-Path -Path $env:ProgramData -ChildPath 'RMHCI\PowerShell' $LogFile = Join-Path -Path $LogPath -ChildPath "New-CertKitAppProxyIdentity_$(Get-Date -Format 'yyyyMMdd-HHmmss').log" If (-not (Test-Path -Path $LogPath)) { New-Item -Path $LogPath -ItemType Directory -Force -WhatIf:$false -Confirm:$false | Out-Null } Start-Transcript -Path $LogFile -WhatIf:$false -Confirm:$false | Out-Null $ExitCode = 0 #EndRegion #Region Functions # Retry Graph requests that can fail while new objects replicate across Entra ID Function Invoke-GraphRequestWithRetry { [CmdletBinding()] Param ( [Parameter(Mandatory)] [hashtable]$Request, [int]$MaxAttempts = 6, [int]$DelaySeconds = 10 ) For ($Attempt = 1; $Attempt -le $MaxAttempts; $Attempt++) { Try { Return Invoke-MgGraphRequest @Request -ErrorAction Stop } Catch { # Retry only errors caused by replication delay, throttling, or service faults. Fail fast on anything else $StatusCode = $null If ($_.Exception.Response) { $StatusCode = [int]$_.Exception.Response.StatusCode } $ErrorText = "$($_.ErrorDetails.Message) $($_.Exception.Message)" $IsTransient = ($null -eq $StatusCode) -or ($StatusCode -in 404, 408, 429) -or ($StatusCode -ge 500) -or ($StatusCode -eq 400 -and $ErrorText -match 'not ?found|does ?not ?exist|does not reference a valid') If (-not $IsTransient -or $Attempt -eq $MaxAttempts) { Throw } Write-Verbose "Request failed with status $StatusCode (attempt $Attempt of $MaxAttempts). Retrying in $DelaySeconds seconds..." Start-Sleep -Seconds $DelaySeconds } } } # Return $true when an Entra credential's end date has passed Function Test-CredentialExpired { [CmdletBinding()] [OutputType([bool])] Param ( [Parameter(Mandatory)] $EndDateTime ) Return ([datetime]$EndDateTime).ToUniversalTime() -lt [datetime]::UtcNow } # Return $true when a local certificate is a self-signed CertKit certificate, optionally with one of the given EKUs Function Test-CertKitCertificate { [CmdletBinding()] [OutputType([bool])] Param ( [Parameter(Mandatory)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, [Parameter(Mandatory)] [string]$Subject, [string[]]$EkuOids ) If ($Certificate.Subject -ne $Subject -or $Certificate.Issuer -ne $Certificate.Subject) { Return $false } If (-not $EkuOids) { Return $true } $CertEkus = $Certificate.Extensions | Where-Object { $_ -is [System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension] } | ForEach-Object { $_.EnhancedKeyUsages } | ForEach-Object { $_.Value } Return [bool]($CertEkus | Where-Object { $_ -in $EkuOids }) } # Delete a certificate and its private key from the local computer's personal store Function Remove-LocalCertificate { [CmdletBinding()] Param ( [Parameter(Mandatory)] [string]$Thumbprint ) Remove-Item -Path "Cert:\LocalMachine\My\$Thumbprint" -DeleteKey -Confirm:$false -WhatIf:$false -ErrorAction Stop } #EndRegion # Track a certificate created by this run, so it can be removed if it never reaches Entra $NewCertThumbprint = $null $CertUploaded = $false Try { $GraphUri = 'https://graph.microsoft.com/v1.0' $UseManagedIdentity = $PSCmdlet.ParameterSetName -eq 'ManagedIdentity' $UseCertificate = $PSCmdlet.ParameterSetName -eq 'Certificate' # Application Proxy permissions granted by the custom role $RolePermissions = @( 'microsoft.directory/applications/applicationProxy/read' 'microsoft.directory/applications/applicationProxySslCertificate/update' 'microsoft.directory/connectorGroups/allProperties/read' ) # Certificate settings $CertSubject = 'CN=CertKit App Proxy Agent' $ClientAuthEku = '1.3.6.1.5.5.7.3.2' $CertEku = If ($CustomEku) { $CustomEku } Else { $ClientAuthEku } $CertKeyName = "CertKit Agent - $env:COMPUTERNAME" $TpmProvider = 'Microsoft Platform Crypto Provider' $SoftwareProvider = 'Microsoft Software Key Storage Provider' # Certificate authentication creates the private key on this computer, so it must be the CertKit agent server, running elevated If ($UseCertificate) { If ($PSVersionTable.PSEdition -eq 'Core' -and -not $IsWindows) { Throw 'Certificate authentication requires Windows. Run this script on the server running the CertKit agent.' } $Principal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent() If (-not $Principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { Throw 'Certificate authentication requires an elevated PowerShell session. Run this script as administrator on the server running the CertKit agent.' } Write-Information "Certificate authentication: the certificate will be created on this computer ($env:COMPUTERNAME). Run this script on the server running the CertKit agent." -InformationAction Continue # The CertKit agent runs as Local System and signs in with Connect-MgGraph, so it can only load the module from an all-users location $AllUsersModule = Get-Module -Name Microsoft.Graph.Authentication -ListAvailable | Where-Object { $_.ModuleBase -like "$env:ProgramFiles\*" -and $_.Version -ge [version]'2.0.0' } If (-not $AllUsersModule) { Write-Warning 'The Microsoft.Graph.Authentication module (2.0.0 or later) is not installed for all users on this computer. The CertKit agent runs as Local System and needs it to sign in with the certificate. Install it with: Install-Module -Name Microsoft.Graph.Authentication -Scope AllUsers' } } # Connect to Microsoft Graph Write-Verbose 'Connecting to Microsoft Graph...' # The managed identity path doesn't create an app registration, so it only needs to read applications $Scopes = If ($UseManagedIdentity) { 'Application.Read.All', 'AppRoleAssignment.ReadWrite.All', 'RoleManagement.ReadWrite.Directory' } Else { 'Application.ReadWrite.All', 'AppRoleAssignment.ReadWrite.All', 'RoleManagement.ReadWrite.Directory' } $ConnectParams = @{ Scopes = $Scopes NoWelcome = $true ErrorAction = 'Stop' } # Sign in to a specific tenant when one is specified If ($TenantId) { $ConnectParams['TenantId'] = $TenantId } Connect-MgGraph @ConnectParams $TenantId = (Get-MgContext).TenantId # Display the connected tenant so it's clear where objects will be created Try { $TenantName = (Invoke-MgGraphRequest -Method GET -Uri "$GraphUri/organization?`$select=displayName" -ErrorAction Stop).value[0].displayName } Catch { $TenantName = 'Unknown' } Write-Information "Connected to tenant '$TenantName' ($TenantId)." -InformationAction Continue # Build OData filters with apostrophes doubled and the expression URL-encoded, so any display name is safe $RoleFilter = [uri]::EscapeDataString("displayName eq '$($RoleName -replace "'", "''")'") $AppFilter = [uri]::EscapeDataString("displayName eq '$($DisplayName -replace "'", "''")'") # Find the custom role before making any changes. Never reuse a built-in role with the same name $MatchingRoles = @((Invoke-MgGraphRequest -Method GET -Uri "$GraphUri/roleManagement/directory/roleDefinitions?`$filter=$RoleFilter" -ErrorAction Stop).value) If ($MatchingRoles | Where-Object { $_.isBuiltIn }) { Throw "'$RoleName' is the name of a built-in Entra role. Specify a different name with -RoleName." } $Role = $MatchingRoles | Select-Object -First 1 #Region Create certificate # Create the certificate before changing anything in Entra, so a TPM failure with -RequireTpm leaves the tenant untouched $Cert = $null $KeyStorageProvider = $null $CertExpires = $null If ($UseCertificate) { $NotAfter = (Get-Date).AddDays($CertificateValidityDays) If ($PSCmdlet.ShouldProcess('Cert:\LocalMachine\My', "Create certificate '$CertSubject' with EKU $CertEku, expiring $($NotAfter.ToString('d'))")) { $CertParams = @{ Type = 'Custom' Subject = $CertSubject FriendlyName = 'CertKit App Proxy Agent' CertStoreLocation = 'Cert:\LocalMachine\My' KeyAlgorithm = 'RSA' KeyLength = 2048 HashAlgorithm = 'SHA256' KeyExportPolicy = 'NonExportable' KeyUsage = 'DigitalSignature' TextExtension = @("2.5.29.37={text}$CertEku") NotAfter = $NotAfter ErrorAction = 'Stop' WhatIf = $false Confirm = $false } Try { Write-Verbose "Creating the certificate with the $TpmProvider..." $NewCert = New-SelfSignedCertificate @CertParams -Provider $TpmProvider $KeyStorageProvider = $TpmProvider } Catch { If ($RequireTpm) { Throw "The private key couldn't be created in the TPM, and -RequireTpm was specified. No changes were made in Entra. $($_.Exception.Message)" } Write-Warning "TPM key creation failed: $($_.Exception.Message) The private key will be created by the $SoftwareProvider instead." $NewCert = New-SelfSignedCertificate @CertParams -Provider $SoftwareProvider $KeyStorageProvider = $SoftwareProvider } # Read the certificate back from the store. In PowerShell 7, New-SelfSignedCertificate can return a deserialized object $NewCertThumbprint = $NewCert.Thumbprint $Cert = Get-Item -Path "Cert:\LocalMachine\My\$NewCertThumbprint" -ErrorAction Stop $CertExpires = $Cert.NotAfter # Report the provider that actually holds the private key Try { $Rsa = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($Cert) If ($Rsa -is [System.Security.Cryptography.RSACng]) { $KeyStorageProvider = $Rsa.Key.Provider.Provider } $Rsa.Dispose() } Catch { Write-Verbose "Couldn't read the key storage provider from the private key: $($_.Exception.Message)" } Write-Verbose "Created certificate $NewCertThumbprint with the $KeyStorageProvider, expiring $($CertExpires.ToString('d'))." } } #EndRegion If ($UseManagedIdentity) { # Find the managed identity by object ID, then by client ID Try { $Sp = Invoke-MgGraphRequest -Method GET -Uri "$GraphUri/servicePrincipals/$($ManagedIdentityId)?`$select=id,appId,displayName,servicePrincipalType" -ErrorAction Stop } Catch { $Sp = (Invoke-MgGraphRequest -Method GET -Uri "$GraphUri/servicePrincipals?`$filter=appId eq '$ManagedIdentityId'&`$select=id,appId,displayName,servicePrincipalType" -ErrorAction Stop).value | Select-Object -First 1 } If (-not $Sp) { Throw "No managed identity with object ID or client ID '$ManagedIdentityId' was found in this tenant." } # Make sure the permissions are only ever granted to a managed identity If ($Sp.servicePrincipalType -ne 'ManagedIdentity') { Throw "'$($Sp.displayName)' ($ManagedIdentityId) is not a managed identity. Its service principal type is '$($Sp.servicePrincipalType)'." } $DisplayName = $Sp.displayName Write-Verbose "Using managed identity '$DisplayName' (client ID $($Sp.appId), object ID $($Sp.id))." } Else { # Create or reuse the app registration $App = (Invoke-MgGraphRequest -Method GET -Uri "$GraphUri/applications?`$filter=$AppFilter" -ErrorAction Stop).value | Select-Object -First 1 If ($App) { Write-Verbose "Using existing app registration '$DisplayName' ($($App.appId))." } ElseIf ($PSCmdlet.ShouldProcess($DisplayName, 'Create app registration')) { $AppBody = @{ displayName = $DisplayName signInAudience = 'AzureADMyOrg' } $App = Invoke-MgGraphRequest -Method POST -Uri "$GraphUri/applications" -Body $AppBody -ErrorAction Stop Write-Verbose "Created app registration '$DisplayName' ($($App.appId))." } # Create or reuse the service principal $Sp = (Invoke-MgGraphRequest -Method GET -Uri "$GraphUri/servicePrincipals?`$filter=appId eq '$($App.appId)'" -ErrorAction Stop).value | Select-Object -First 1 If ($Sp) { Write-Verbose "Using existing service principal ($($Sp.id))." } ElseIf ($PSCmdlet.ShouldProcess($DisplayName, 'Create service principal')) { $SpRequest = @{ Method = 'POST' Uri = "$GraphUri/servicePrincipals" Body = @{ appId = $App.appId } } $Sp = Invoke-GraphRequestWithRetry -Request $SpRequest Write-Verbose "Created service principal ($($Sp.id))." } } # Create or reuse the custom role $RoleCreated = $false If ($Role) { Write-Verbose "Using existing custom role '$RoleName' ($($Role.id))." } ElseIf ($PSCmdlet.ShouldProcess($RoleName, 'Create custom Entra role')) { $RoleBody = @{ displayName = $RoleName description = 'Can read Application Proxy settings and update the Application Proxy SSL certificate. Used by CertKit.' isEnabled = $true rolePermissions = @(@{ allowedResourceActions = $RolePermissions }) } $Role = Invoke-MgGraphRequest -Method POST -Uri "$GraphUri/roleManagement/directory/roleDefinitions" -Body $RoleBody -ErrorAction Stop $RoleCreated = $true Write-Verbose "Created custom role '$RoleName' ($($Role.id))." } # Grant the read-only Microsoft Graph application permission Application.Read.All $GraphSp = (Invoke-MgGraphRequest -Method GET -Uri "$GraphUri/servicePrincipals?`$filter=appId eq '00000003-0000-0000-c000-000000000000'&`$select=id,appRoles" -ErrorAction Stop).value[0] $AppRoleId = ($GraphSp.appRoles | Where-Object { $_.value -eq 'Application.Read.All' -and $_.allowedMemberTypes -contains 'Application' }).id # With -WhatIf, a service principal that doesn't exist yet has no grants to look up $ExistingGrant = $null If ($Sp) { $ExistingGrant = (Invoke-MgGraphRequest -Method GET -Uri "$GraphUri/servicePrincipals/$($Sp.id)/appRoleAssignments" -ErrorAction Stop).value | Where-Object { $_.appRoleId -eq $AppRoleId } } If ($ExistingGrant) { Write-Verbose 'Application.Read.All is already granted.' } ElseIf ($PSCmdlet.ShouldProcess($DisplayName, 'Grant Microsoft Graph application permission Application.Read.All')) { $GrantRequest = @{ Method = 'POST' Uri = "$GraphUri/servicePrincipals/$($Sp.id)/appRoleAssignments" Body = @{ principalId = $Sp.id; resourceId = $GraphSp.id; appRoleId = $AppRoleId } } Invoke-GraphRequestWithRetry -Request $GrantRequest | Out-Null Write-Verbose 'Granted Application.Read.All.' } # Assign the custom role tenant-wide, directly or through PIM # With -WhatIf, a service principal or role that doesn't exist yet has no assignments to look up $ExistingAssignment = $null $RoleAssigned = 'Not assigned' If ($Sp -and $Role) { $ExistingAssignment = (Invoke-MgGraphRequest -Method GET -Uri "$GraphUri/roleManagement/directory/roleAssignments?`$filter=principalId eq '$($Sp.id)' and roleDefinitionId eq '$($Role.id)'" -ErrorAction Stop).value } If ($ExistingAssignment) { $RoleAssigned = 'Already assigned' Write-Verbose "The '$RoleName' role is already assigned." } ElseIf ($UsePim) { If ($PSCmdlet.ShouldProcess($DisplayName, "Assign '$RoleName' role through PIM")) { $PimRequest = @{ Method = 'POST' Uri = "$GraphUri/roleManagement/directory/roleAssignmentScheduleRequests" Body = @{ action = 'adminAssign' justification = 'CertKit certificate deployment to Entra Application Proxy' roleDefinitionId = $Role.id directoryScopeId = '/' principalId = $Sp.id scheduleInfo = @{ startDateTime = (Get-Date).ToUniversalTime().ToString('o') expiration = @{ type = 'noExpiration' } } } } # PIM can take several minutes to recognize a newly created custom role, so allow up to 10 minutes If ($RoleCreated) { Write-Information 'Waiting for PIM to recognize the new custom role. This can take several minutes...' -InformationAction Continue } Invoke-GraphRequestWithRetry -Request $PimRequest -MaxAttempts 60 | Out-Null $RoleAssigned = 'Through PIM' Write-Verbose "Assigned the '$RoleName' role through PIM." } } ElseIf ($PSCmdlet.ShouldProcess($DisplayName, "Assign '$RoleName' role")) { $AssignmentRequest = @{ Method = 'POST' Uri = "$GraphUri/roleManagement/directory/roleAssignments" Body = @{ '@odata.type' = '#microsoft.graph.unifiedRoleAssignment' roleDefinitionId = $Role.id principalId = $Sp.id directoryScopeId = '/' } } Invoke-GraphRequestWithRetry -Request $AssignmentRequest | Out-Null $RoleAssigned = 'Directly' Write-Verbose "Assigned the '$RoleName' role." } #Region Upload certificate $OldCertificatesRemoved = 0 $ExpiredCertificatesRemoved = 0 $LocalCertificatesRemoved = 0 If ($UseCertificate) { $RemovedThumbprints = [System.Collections.Generic.List[string]]::new() # With -WhatIf, an app registration that doesn't exist yet has no certificates to look up If ($App.id) { # The certificate data (key) is only returned when keyCredentials is selected on a single application $KeyRequest = @{ Method = 'GET' Uri = "$GraphUri/applications/$($App.id)?`$select=keyCredentials" } $ExistingKeys = @((Invoke-GraphRequestWithRetry -Request $KeyRequest).keyCredentials | Where-Object { $_ }) # PATCH replaces the whole keyCredentials collection, so build the full list of certificates to keep $KeptKeys = [System.Collections.Generic.List[object]]::new() $PendingThumbprints = [System.Collections.Generic.List[string]]::new() $PendingOld = 0 $PendingExpired = 0 $OtherThisServer = 0 $OtherServers = 0 $Uploading = $false ForEach ($Key in $ExistingKeys) { # Never send a list that would silently drop a certificate that couldn't be read If (-not $Key.key) { Throw "Couldn't read certificate '$($Key.displayName)' ($($Key.keyId)) on the app registration. No certificates were changed in Entra." } $KeyThumbprint = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new([Convert]::FromBase64String($Key.key)).Thumbprint $KeyExpires = ([datetime]$Key.endDateTime).ToLocalTime().ToString('d') $IsExpired = Test-CredentialExpired -EndDateTime $Key.endDateTime $IsOldFromThisServer = $RemoveExistingCertificates -and $Key.displayName -eq $CertKeyName # Expired certificates are removed no matter which server uploaded them, since none of them work If ($IsExpired -and $PSCmdlet.ShouldProcess($DisplayName, "Remove expired certificate '$($Key.displayName)' ($KeyThumbprint), expired $KeyExpires")) { $PendingThumbprints.Add($KeyThumbprint) $PendingExpired++ Continue } If (-not $IsExpired -and $IsOldFromThisServer -and $PSCmdlet.ShouldProcess($DisplayName, "Remove certificate '$($Key.displayName)' ($KeyThumbprint), expiring $KeyExpires")) { $PendingThumbprints.Add($KeyThumbprint) $PendingOld++ Continue } # Keep the certificate by sending it back exactly as Entra returned it, including empty properties # Graph rejects any difference from the stored credential with KeyNotUpdatable, and fills in omitted properties with its own values $KeptKey = [ordered]@{} ForEach ($Property in 'customKeyIdentifier', 'displayName', 'endDateTime', 'key', 'keyId', 'startDateTime', 'type', 'usage') { $Value = $Key[$Property] # Send dates as ISO 8601 UTC with full precision. Windows PowerShell 5.1 would otherwise serialize them as /Date(...)/ If ($Value -is [datetime]) { If ($Value.Kind -eq [System.DateTimeKind]::Unspecified) { $Value = [datetime]::SpecifyKind($Value, [System.DateTimeKind]::Utc) } $Value = $Value.ToUniversalTime().ToString('o') } $KeptKey[$Property] = $Value } $KeptKeys.Add($KeptKey) If (-not $IsExpired) { If ($Key.displayName -eq $CertKeyName) { $OtherThisServer++ } Else { $OtherServers++ } } } # Add the new certificate If ($Cert -and $PSCmdlet.ShouldProcess($DisplayName, "Upload certificate '$CertKeyName' ($NewCertThumbprint), expiring $($CertExpires.ToString('d'))")) { $KeptKeys.Add([ordered]@{ type = 'AsymmetricX509Cert' usage = 'Verify' key = [Convert]::ToBase64String($Cert.RawData) displayName = $CertKeyName }) $Uploading = $true } If ($Uploading -or $PendingThumbprints.Count -gt 0) { $PatchRequest = @{ Method = 'PATCH' Uri = "$GraphUri/applications/$($App.id)" Body = @{ keyCredentials = $KeptKeys.ToArray() } | ConvertTo-Json -Depth 5 ContentType = 'application/json' } Invoke-GraphRequestWithRetry -Request $PatchRequest | Out-Null If ($Uploading) { $CertUploaded = $true Write-Verbose "Uploaded certificate $NewCertThumbprint to the app registration." } $RemovedThumbprints.AddRange($PendingThumbprints) $OldCertificatesRemoved = $PendingOld $ExpiredCertificatesRemoved = $PendingExpired } If ($OtherThisServer -gt 0) { Write-Warning "The app registration has $OtherThisServer older certificate(s) from this server ($env:COMPUTERNAME). Once CertKit is using the new certificate, delete them on the app registration's Certificates & secrets page in the Entra admin center. Running this script again with -RemoveExistingCertificates would also remove the certificate CertKit is now using." } If ($OtherServers -gt 0) { Write-Information "The app registration has $OtherServers valid certificate(s) from other servers or sources. They weren't changed." -InformationAction Continue } } # Delete certificates removed from Entra, and expired CertKit certificates, from the local computer's store $LocalEkus = @($ClientAuthEku, $CertEku) | Select-Object -Unique ForEach ($LocalCert in @(Get-ChildItem -Path 'Cert:\LocalMachine\My')) { If ($LocalCert.Thumbprint -eq $NewCertThumbprint) { Continue } $Reason = $null If ($LocalCert.Thumbprint -in $RemovedThumbprints -and (Test-CertKitCertificate -Certificate $LocalCert -Subject $CertSubject)) { $Reason = 'removed from Entra' } ElseIf ($LocalCert.NotAfter -lt (Get-Date) -and (Test-CertKitCertificate -Certificate $LocalCert -Subject $CertSubject -EkuOids $LocalEkus)) { $Reason = 'expired' } If ($Reason -and $PSCmdlet.ShouldProcess("Cert:\LocalMachine\My\$($LocalCert.Thumbprint)", "Delete certificate and private key ($Reason), expiring $($LocalCert.NotAfter.ToString('d'))")) { Try { Remove-LocalCertificate -Thumbprint $LocalCert.Thumbprint $LocalCertificatesRemoved++ Write-Verbose "Deleted local certificate $($LocalCert.Thumbprint) ($Reason)." } Catch { Write-Warning "Couldn't delete local certificate $($LocalCert.Thumbprint) ($Reason): $($_.Exception.Message)" } } } } #EndRegion #Region Client secrets $SecretExpires = $null $SecretsRemoved = 0 $ExpiredSecretsRemoved = 0 $NewSecretKeyId = $null # Create a client secret and copy it to the clipboard If ($PSCmdlet.ParameterSetName -eq 'ClientSecret') { $SecretExpires = (Get-Date).AddMonths($SecretExpirationMonths) If ($PSCmdlet.ShouldProcess($DisplayName, "Create client secret expiring $($SecretExpires.ToString('d'))")) { $SecretBody = @{ passwordCredential = @{ displayName = 'CertKit' endDateTime = $SecretExpires.ToUniversalTime().ToString('o') } } $Secret = Invoke-MgGraphRequest -Method POST -Uri "$GraphUri/applications/$($App.id)/addPassword" -Body $SecretBody -ErrorAction Stop $NewSecretKeyId = $Secret.keyId $Secret.secretText | Set-Clipboard Remove-Variable -Name Secret Write-Warning 'The client secret was copied to the clipboard. Paste it into CertKit now, then clear the clipboard with Set-Clipboard -Value $null.' } } # Remove expired client secrets, then remove or report the older secrets that are still valid If (-not $UseManagedIdentity -and $App.id) { $OldSecrets = @((Invoke-MgGraphRequest -Method GET -Uri "$GraphUri/applications/$($App.id)?`$select=passwordCredentials" -ErrorAction Stop).passwordCredentials | Where-Object { $_ -and $_.keyId -ne $NewSecretKeyId }) $ValidSecrets = @() ForEach ($OldSecret in $OldSecrets) { $SecretEnds = ([datetime]$OldSecret.endDateTime).ToLocalTime().ToString('d') If (Test-CredentialExpired -EndDateTime $OldSecret.endDateTime) { If ($PSCmdlet.ShouldProcess($DisplayName, "Remove expired client secret '$($OldSecret.displayName)' ($($OldSecret.hint)***), expired $SecretEnds")) { Invoke-MgGraphRequest -Method POST -Uri "$GraphUri/applications/$($App.id)/removePassword" -Body @{ keyId = $OldSecret.keyId } -ErrorAction Stop $ExpiredSecretsRemoved++ Write-Verbose "Removed expired client secret $($OldSecret.keyId)." } } Else { $ValidSecrets += $OldSecret } } # Remove older valid secrets only after a new secret was successfully created. With -WhatIf, preview the removals instead If ($ValidSecrets.Count -gt 0 -and $RemoveExistingSecrets -and ($NewSecretKeyId -or $WhatIfPreference)) { ForEach ($OldSecret in $ValidSecrets) { If ($PSCmdlet.ShouldProcess($DisplayName, "Remove client secret '$($OldSecret.displayName)' ($($OldSecret.hint)***), expiring $(([datetime]$OldSecret.endDateTime).ToString('d'))")) { Invoke-MgGraphRequest -Method POST -Uri "$GraphUri/applications/$($App.id)/removePassword" -Body @{ keyId = $OldSecret.keyId } -ErrorAction Stop $SecretsRemoved++ Write-Verbose "Removed client secret $($OldSecret.keyId)." } } } ElseIf ($ValidSecrets.Count -gt 0 -and $UseCertificate) { Write-Warning "The app registration still has $($ValidSecrets.Count) client secret(s). Once CertKit is using the certificate, delete them on the app registration's Certificates & secrets page in the Entra admin center." } ElseIf ($ValidSecrets.Count -gt 0) { Write-Warning "The app registration has $($ValidSecrets.Count) older client secret(s). Once CertKit is using the new secret, delete them on the app registration's Certificates & secrets page in the Entra admin center. Running this script again with -RemoveExistingSecrets would also remove the secret CertKit is now using." } } #EndRegion # Output the values CertKit needs If ($UseManagedIdentity) { [PSCustomObject]@{ TenantName = $TenantName TenantId = $TenantId ManagedIdentity = $DisplayName ClientId = $Sp.appId CustomRole = $RoleName RoleAssigned = $RoleAssigned } } ElseIf ($UseCertificate) { [PSCustomObject]@{ TenantName = $TenantName TenantId = $TenantId ClientId = $App.appId CertificateThumbprint = If ($CertUploaded) { $NewCertThumbprint } Else { $null } CertificateSubject = $CertSubject CertificateEku = $CertEku CertificateExpires = $CertExpires KeyStorageProvider = $KeyStorageProvider CustomRole = $RoleName RoleAssigned = $RoleAssigned OldCertificatesRemoved = $OldCertificatesRemoved ExpiredCertificatesRemoved = $ExpiredCertificatesRemoved LocalCertificatesRemoved = $LocalCertificatesRemoved ExpiredSecretsRemoved = $ExpiredSecretsRemoved } } Else { [PSCustomObject]@{ TenantName = $TenantName TenantId = $TenantId ClientId = $App.appId SecretExpires = $SecretExpires CustomRole = $RoleName RoleAssigned = $RoleAssigned OldSecretsRemoved = $SecretsRemoved ExpiredSecretsRemoved = $ExpiredSecretsRemoved } } } Catch { # Record the error in the transcript before logging stops $ErrorActionPreference = 'Continue' Write-Error -ErrorRecord $_ $ExitCode = 1 } Finally { # Don't leave behind a certificate this run created but never uploaded, such as after an error or a declined -Confirm prompt If ($NewCertThumbprint -and -not $CertUploaded) { Try { Remove-LocalCertificate -Thumbprint $NewCertThumbprint Write-Warning "Deleted the new certificate $NewCertThumbprint from this computer because it wasn't uploaded to Entra." } Catch { Write-Warning "The new certificate $NewCertThumbprint wasn't uploaded to Entra and couldn't be deleted from Cert:\LocalMachine\My. Delete it manually. $($_.Exception.Message)" } } # Stop-Transcript supports -WhatIf in PowerShell 7 but not in Windows PowerShell 5.1 $StopTranscriptParams = @{} If ((Get-Command -Name Stop-Transcript).Parameters.ContainsKey('WhatIf')) { $StopTranscriptParams = @{ WhatIf = $false; Confirm = $false } } Stop-Transcript @StopTranscriptParams | Out-Null } If ($ExitCode -ne 0) { Exit $ExitCode } |