diff --git a/.github/images/AppGwBin-custom-fields-store-type-dialog.png b/.github/images/AppGwBin-custom-fields-store-type-dialog.png deleted file mode 100644 index db09747..0000000 Binary files a/.github/images/AppGwBin-custom-fields-store-type-dialog.png and /dev/null differ diff --git a/.github/images/AzureAppGw-custom-fields-store-type-dialog.png b/.github/images/AzureAppGw-custom-fields-store-type-dialog.png deleted file mode 100644 index db09747..0000000 Binary files a/.github/images/AzureAppGw-custom-fields-store-type-dialog.png and /dev/null differ diff --git a/AzureAppGatewayOrchestrator.Tests/AzureAppGatewayOrchestrator_AzureAppGW.cs b/AzureAppGatewayOrchestrator.Tests/AzureAppGW.cs similarity index 98% rename from AzureAppGatewayOrchestrator.Tests/AzureAppGatewayOrchestrator_AzureAppGW.cs rename to AzureAppGatewayOrchestrator.Tests/AzureAppGW.cs index 6199a21..47c3351 100644 --- a/AzureAppGatewayOrchestrator.Tests/AzureAppGatewayOrchestrator_AzureAppGW.cs +++ b/AzureAppGatewayOrchestrator.Tests/AzureAppGW.cs @@ -24,15 +24,15 @@ namespace AzureAppGatewayOrchestrator.Tests; -public class AzureAppGatewayOrchestrator_AzureAppGw +public class AzureAppGw { ILogger _logger { get; set;} - public AzureAppGatewayOrchestrator_AzureAppGw() + public AzureAppGw() { ConfigureLogging(); - _logger = LogHandler.GetClassLogger(); + _logger = LogHandler.GetClassLogger(); } [IntegrationTestingFact] @@ -544,7 +544,7 @@ public void AzureAppGw_Management_IntegrationTest_ReturnSuccess() string certName = "GatewayTest" + Guid.NewGuid().ToString()[..6]; string password = "password"; - X509Certificate2 ssCert = AzureAppGatewayOrchestrator_Client.GetSelfSignedCert(testHostname); + X509Certificate2 ssCert = Client.GetSelfSignedCert(testHostname); string b64PfxSslCert = Convert.ToBase64String(ssCert.Export(X509ContentType.Pfx, password)); @@ -577,7 +577,7 @@ public void AzureAppGw_Management_IntegrationTest_ReturnSuccess() // Arrange - ssCert = AzureAppGatewayOrchestrator_Client.GetSelfSignedCert(testHostname); + ssCert = Client.GetSelfSignedCert(testHostname); b64PfxSslCert = Convert.ToBase64String(ssCert.Export(X509ContentType.Pfx, password)); diff --git a/AzureAppGatewayOrchestrator.Tests/AzureAppGatewayOrchestrator.Tests.csproj b/AzureAppGatewayOrchestrator.Tests/AzureAppGatewayOrchestrator.Tests.csproj index 675e50a..4fe114f 100644 --- a/AzureAppGatewayOrchestrator.Tests/AzureAppGatewayOrchestrator.Tests.csproj +++ b/AzureAppGatewayOrchestrator.Tests/AzureAppGatewayOrchestrator.Tests.csproj @@ -1,7 +1,7 @@ - net6.0 + net8.0 enable enable diff --git a/AzureAppGatewayOrchestrator.Tests/AzureAppGatewayOrchestrator_Client.cs b/AzureAppGatewayOrchestrator.Tests/AzureAppGatewayOrchestrator_Client.cs deleted file mode 100644 index 3398c2e..0000000 --- a/AzureAppGatewayOrchestrator.Tests/AzureAppGatewayOrchestrator_Client.cs +++ /dev/null @@ -1,283 +0,0 @@ -// Copyright 2024 Keyfactor -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using System.Security.Cryptography; -using System.Security.Cryptography.X509Certificates; -using Azure; -using Azure.Core; -using Azure.ResourceManager; -using Azure.ResourceManager.Network; -using Azure.ResourceManager.Network.Mocking; -using Azure.ResourceManager.Network.Models; -using Azure.ResourceManager.Resources; -using AzureApplicationGatewayOrchestratorExtension.Client; -using Keyfactor.Logging; -using Microsoft.Extensions.Logging; -using Moq; -using NLog.Extensions.Logging; - -namespace AzureAppGatewayOrchestrator.Tests; - -public class AzureAppGatewayOrchestrator_Client -{ - private ResourceIdentifier _appGatewayResourceId; - - public AzureAppGatewayOrchestrator_Client() - { - ConfigureLogging(); - - _appGatewayResourceId = new ResourceIdentifier("/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/testResourceGroup/providers/Microsoft.Network/applicationGateways/testAppGateway"); - } - - [IntegrationTestingFact] - public void AzureClientIntegrationTest() - { - // Arrange - string httpsListenerName = Environment.GetEnvironmentVariable("AZURE_APP_GATEWAY_HTTPS_LISTENER_NAME") ?? string.Empty; - - IAzureAppGatewayClient client = new GatewayClient.Builder() - .WithTenantId(Environment.GetEnvironmentVariable("AZURE_TENANT_ID") ?? string.Empty) - .WithApplicationId(Environment.GetEnvironmentVariable("AZURE_CLIENT_ID") ?? string.Empty) - .WithClientSecret(Environment.GetEnvironmentVariable("AZURE_CLIENT_SECRET") ?? string.Empty) - .WithResourceId(Environment.GetEnvironmentVariable("AZURE_APP_GATEWAY_RESOURCE_ID") ?? string.Empty) - .Build(); - - string certName = "GatewayTest" + Guid.NewGuid().ToString()[..6]; - string password = "password"; - - X509Certificate2 ssCert = GetSelfSignedCert(certName); - string b64PfxSslCert = Convert.ToBase64String(ssCert.Export(X509ContentType.Pfx, password)); - - // Step 1 - Add an App Gateway certificate - - // Act - ApplicationGatewaySslCertificate result = client.AddCertificate(certName, b64PfxSslCert, password); - - // Assert - Assert.NotNull(result); - Assert.Equal(certName, result.Name); - - // Step 2 - Update an HTTPS listener with the new certificate - - // Act - bool ex = false; - try - { - client.UpdateHttpsListenerCertificate(result, httpsListenerName); - } - catch (Exception) - { - ex = true; - } - - // Assert - Assert.False(ex); - - // Step 3 - Get the certificates that exist on the app gateway - - // Act - OperationResult> certs = client.GetAppGatewaySslCertificates(); - - // Assert - Assert.NotNull(certs.Result); - Assert.NotEmpty(certs.Result); - Assert.Contains(certs.Result, c => c.Alias == certName); - - // Step 4 - Try to remove the certificate from the app gateway, which should fail - // since it's bound to an HTTPS listener - - // Act - ex = false; - try - { - // Client should throw exception if certificate is bound to an HTTPS listener. - client.RemoveCertificate(certName); - } - catch (Exception) - { - ex = true; - } - - // Assert - Assert.True(ex); - - // Act - - // Step 5 - Remove the certificate from the HTTPS listener - - // Rebind the HTTPS listener with the original certificate, if there was only 1 certificate - // previously, otherwise bind it with the first certificate in the list. - - ApplicationGatewaySslCertificate replacement = client.GetAppGatewayCertificateByName(certs.Result.First(c => c.Alias != certName).Alias); - - client.UpdateHttpsListenerCertificate(replacement, httpsListenerName); - - client.RemoveCertificate(certName); - - // Act - - // Step 6 - Test the GetHttpsListenerCertificates method - - // boundCertificates in the form of - IDictionary boundCertificates = client.GetBoundHttpsListenerCertificates(); - } - - public static X509Certificate2 GetSelfSignedCert(string hostname) - { - RSA rsa = RSA.Create(2048); - CertificateRequest req = new CertificateRequest($"CN={hostname}", rsa, HashAlgorithmName.SHA256, - RSASignaturePadding.Pkcs1); - - SubjectAlternativeNameBuilder subjectAlternativeNameBuilder = new SubjectAlternativeNameBuilder(); - subjectAlternativeNameBuilder.AddDnsName(hostname); - req.CertificateExtensions.Add(subjectAlternativeNameBuilder.Build()); - req.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false)); - req.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new Oid("2.5.29.32.0"), new Oid("1.3.6.1.5.5.7.3.1") }, false)); - - X509Certificate2 selfSignedCert = req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5)); - Console.Write($"Created self-signed certificate for \"{hostname}\" with thumbprint {selfSignedCert.Thumbprint}\n"); - return selfSignedCert; - } - - static void ConfigureLogging() - { - var config = new NLog.Config.LoggingConfiguration(); - - // Targets where to log to: File and Console - var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); - logconsole.Layout = @"${date:format=HH\:mm\:ss} ${logger} [${level}] - ${message}"; - - // Rules for mapping loggers to targets - config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logconsole); - - // Apply config - NLog.LogManager.Configuration = config; - - LogHandler.Factory = LoggerFactory.Create(builder => - { - builder.AddNLog(); - }); - } - - public class MockArmClientBuilder - { - private Mock _armClientMock = new(); - private Mock _mockableNetworkArmClient = new(); - private Mock _appGatewayResourceMock = new(); - - public MockArmClientBuilder HookUpGetApplicationGatewayResource(ResourceIdentifier appGatewayResourceId, ApplicationGatewayData appGatewayData) - { - // Mock the ApplicationGatewayResource method - _appGatewayResourceMock.SetupGet(r => r.Data).Returns(appGatewayData); - - _mockableNetworkArmClient.Setup(client => client.GetApplicationGatewayResource(appGatewayResourceId)) - .Returns(_appGatewayResourceMock.Object); - - // Create a Response object to return from Get() - Response appGatewayResponseMock = Response.FromValue(_appGatewayResourceMock.Object, Mock.Of()); - - // Hook up the Get() method to return the mock response - _appGatewayResourceMock.Setup(resource => resource.Get(CancellationToken.None)) - .Returns(appGatewayResponseMock); - - return this; - } - - public MockArmClientBuilder HookUpGatewayCollectionGetter() - { - // Set up the ApplicationGatewayCollection operations so they can be hooked in later - var mockApplicationGatewayCollection = new Mock(); - - // Create a Mock ArmOperation that will be populated with the contents of the AppGateway the client - // is trying to update - var mockArmOperation = new Mock>(); - - mockApplicationGatewayCollection.Setup(c => c.CreateOrUpdate( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())) - .Callback((waitUntil, name, data, token) => - { - // Use 'data' to set up your mockArmOperation - var mockAppGatewayResource = new Mock(); - mockAppGatewayResource.SetupGet(r => r.Data).Returns(data); - - mockArmOperation.Setup(op => op.Value).Returns(mockAppGatewayResource.Object); - }) - .Returns(mockArmOperation.Object); - - var mockSubscriptionResource = new Mock(); - var mockableNetworkSubscriptionResource = new Mock(); - var mockResourceGroupResource = new Mock(); - var mockableNetworkResourceGroupResource = new Mock(); - - // Hook up the Mock SubscriptionResource to the Mock ArmClient - _armClientMock.Setup(client => client.GetSubscriptionResource(It.IsAny())) - .Returns(mockSubscriptionResource.Object); - - // Set up GetSubscriptionResource to return the mock subscription resource - mockableNetworkResourceGroupResource.Setup(rg => rg.GetApplicationGateways()) - .Returns(Mock.Of()); - - // Create a mock response for GetResourceGroup - var mockResourceGroupResponse = Response.FromValue(mockResourceGroupResource.Object, Mock.Of()); - - // Set up GetResourceGroup to return the mock response - mockSubscriptionResource.Setup(sr => sr.GetResourceGroup(It.IsAny(), CancellationToken.None)) - .Returns(mockResourceGroupResponse); - - // Hooking up MockableNetworkResourceGroupResource with ResourceGroupResource - mockResourceGroupResource.Setup(rg => rg.GetCachedClient( - It.IsAny>())) - .Returns(mockableNetworkResourceGroupResource.Object); - - // Similar setup for SubscriptionResource and MockableNetworkSubscriptionResource - mockSubscriptionResource.Setup(sr => sr.GetCachedClient( - It.IsAny>())) - .Returns(mockableNetworkSubscriptionResource.Object); - - return this; - } - - public Mock Build() - { - // Mock the GetCachedClient method on ArmClient - _armClientMock.Setup(client => client.GetCachedClient( - It.IsAny>())) - .Returns(_mockableNetworkArmClient.Object); - - return _armClientMock; - } - } - - private void WillFinishEventually() - { - // Arrange - string certificateName = "testCert"; - string b64Pkcs12Certificate = "base64CertificateData"; - string password = "testPassword"; - - ApplicationGatewayData appGatewayData = new ApplicationGatewayData(); - - GatewayClient client = new GatewayClient(new MockArmClientBuilder() - .HookUpGetApplicationGatewayResource(_appGatewayResourceId, appGatewayData) - .HookUpGatewayCollectionGetter() - .Build().Object); - client.AppGatewayResourceId = _appGatewayResourceId; - - ApplicationGatewaySslCertificate result = client.AddCertificate(certificateName, b64Pkcs12Certificate, password); - } -} - diff --git a/AzureAppGatewayOrchestrator.Tests/AzureAppGatewayOrchestrator_JobClientBuilder.cs b/AzureAppGatewayOrchestrator.Tests/AzureAppGatewayOrchestrator_JobClientBuilder.cs deleted file mode 100644 index 8bbad50..0000000 --- a/AzureAppGatewayOrchestrator.Tests/AzureAppGatewayOrchestrator_JobClientBuilder.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2024 Keyfactor -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using AzureAppGatewayOrchestrator.Tests; -using AzureApplicationGatewayOrchestratorExtension; -using AzureApplicationGatewayOrchestratorExtension.Client; -using Keyfactor.Logging; -using Keyfactor.Orchestrators.Extensions; -using Microsoft.Extensions.Logging; -using NLog.Extensions.Logging; - -public class AzureAppGatewayOrchestrator_JobClientBuilder -{ - ILogger _logger { get; set;} - - public AzureAppGatewayOrchestrator_JobClientBuilder() - { - ConfigureLogging(); - - _logger = LogHandler.GetClassLogger(); - } - - [Fact] - public void AppGatewayJobClientBuilder_ValidCertificateStoreConfig_BuildValidClient() - { - // Verify that the AppGatewayJobClientBuilder uses the certificate store configuration - // provided by Keyfactor Command/the Universal Orchestrator correctly as required - // by the IAzureAppGatewayClientBuilder interface. - - // Arrange - AppGatewayJobClientBuilder jobClientBuilderWithFakeBuilder = new(); - - // Set up the certificate store with names that correspond to how we expect them to be interpreted by - // the builder - CertificateStore fakeCertificateStoreDetails = new() - { - ClientMachine = "fake-tenant-id", - StorePath = "fake-azure-resource-id", - Properties = "{\"ServerUsername\":\"fake-azure-application-id\",\"ServerPassword\":\"fake-azure-client-secret\",\"AzureCloud\":\"fake-azure-cloud\"}" - }; - - // Act - IAzureAppGatewayClient fakeAppGatewayClient = jobClientBuilderWithFakeBuilder - .WithCertificateStoreDetails(fakeCertificateStoreDetails) - .Build(); - - // Assert - - // IAzureAppGatewayClient doesn't require any of the properties set by the builder to be exposed - // since the production Build() method creates an Azure Resource Manager client. - // But, our builder is fake and exposes the properties we need to test (via the FakeBuilder class). - Assert.Equal("fake-tenant-id", jobClientBuilderWithFakeBuilder._builder._tenantId); - Assert.Equal("fake-azure-resource-id", jobClientBuilderWithFakeBuilder._builder._resourceId); - Assert.Equal("fake-azure-application-id", jobClientBuilderWithFakeBuilder._builder._applicationId); - Assert.Equal("fake-azure-client-secret", jobClientBuilderWithFakeBuilder._builder._clientSecret); - Assert.Equal("fake-azure-cloud", jobClientBuilderWithFakeBuilder._builder._azureCloudEndpoint); - - _logger.LogInformation("AppGatewayJobClientBuilder_ValidCertificateStoreConfig_BuildValidClient - Success"); - } - - static void ConfigureLogging() - { - var config = new NLog.Config.LoggingConfiguration(); - - // Targets where to log to: File and Console - var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); - logconsole.Layout = @"${date:format=HH\:mm\:ss} ${logger} [${level}] - ${message}"; - - // Rules for mapping loggers to targets - config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logconsole); - - // Apply config - NLog.LogManager.Configuration = config; - - LogHandler.Factory = LoggerFactory.Create(builder => - { - builder.AddNLog(); - }); - } -} diff --git a/AzureAppGatewayOrchestrator.Tests/AzureAppGatewayOrchestrator_AzureAppGwBin.cs b/AzureAppGatewayOrchestrator.Tests/AzureAppGwBin.cs similarity index 97% rename from AzureAppGatewayOrchestrator.Tests/AzureAppGatewayOrchestrator_AzureAppGwBin.cs rename to AzureAppGatewayOrchestrator.Tests/AzureAppGwBin.cs index 22f4305..7207547 100644 --- a/AzureAppGatewayOrchestrator.Tests/AzureAppGatewayOrchestrator_AzureAppGwBin.cs +++ b/AzureAppGatewayOrchestrator.Tests/AzureAppGwBin.cs @@ -24,15 +24,15 @@ namespace AzureAppGatewayOrchestrator.Tests; -public class AzureAppGatewayOrchestrator_AzureAppGwBin +public class AzureAppGwBin { ILogger _logger { get; set;} - public AzureAppGatewayOrchestrator_AzureAppGwBin() + public AzureAppGwBin() { ConfigureLogging(); - _logger = LogHandler.GetClassLogger(); + _logger = LogHandler.GetClassLogger(); } [IntegrationTestingFact] @@ -329,7 +329,7 @@ public void AzureAppGwBin_Management_IntegrationTest_AddAndBindCertificate_Retur string certName = "GatewayTest" + Guid.NewGuid().ToString()[..6]; string password = "password"; - X509Certificate2 ssCert = AzureAppGatewayOrchestrator_Client.GetSelfSignedCert(testHostname); + X509Certificate2 ssCert = Client.GetSelfSignedCert(testHostname); string b64PfxSslCert = Convert.ToBase64String(ssCert.Export(X509ContentType.Pfx, password)); diff --git a/AzureAppGatewayOrchestrator.Tests/Client.cs b/AzureAppGatewayOrchestrator.Tests/Client.cs new file mode 100644 index 0000000..d2e3452 --- /dev/null +++ b/AzureAppGatewayOrchestrator.Tests/Client.cs @@ -0,0 +1,179 @@ +// Copyright 2024 Keyfactor +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using Azure.Core; +using Azure.ResourceManager.Network.Models; +using AzureApplicationGatewayOrchestratorExtension.Client; +using Keyfactor.Logging; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; + +namespace AzureAppGatewayOrchestrator.Tests; + +public class Client +{ + private ResourceIdentifier _appGatewayResourceId; + + public Client() + { + ConfigureLogging(); + + _appGatewayResourceId = new ResourceIdentifier("/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/testResourceGroup/providers/Microsoft.Network/applicationGateways/testAppGateway"); + } + + [IntegrationTestingTheory] + [InlineData("clientcert")] + [InlineData("clientsecret")] + public void AzureClientIntegrationTest(string testAuthMethod) + { + // Arrange + IntegrationTestingFact env = new(); + + IAzureAppGatewayClientBuilder clientBuilder = new GatewayClient.Builder() + .WithTenantId(env.TenantId) + .WithApplicationId(env.ApplicationId) + .WithResourceId(env.ResourceId); + + if (testAuthMethod == "clientcert") + { + clientBuilder.WithClientSecret(env.ClientSecret); + } + else + { + var cert = X509Certificate2.CreateFromPemFile(env.ClientCertificatePath); + clientBuilder.WithClientCertificate(cert); + } + + IAzureAppGatewayClient client = clientBuilder.Build(); + + string certName = "GatewayTest" + Guid.NewGuid().ToString()[..6]; + string password = "password"; + + X509Certificate2 ssCert = GetSelfSignedCert(certName); + string b64PfxSslCert = Convert.ToBase64String(ssCert.Export(X509ContentType.Pfx, password)); + + // Step 1 - Add an App Gateway certificate + + // Act + ApplicationGatewaySslCertificate result = client.AddCertificate(certName, b64PfxSslCert, password); + + // Assert + Assert.NotNull(result); + Assert.Equal(certName, result.Name); + + // Step 2 - Update an HTTPS listener with the new certificate + + // Act + bool ex = false; + try + { + client.UpdateHttpsListenerCertificate(result, env.HttpsListenerName); + } + catch (Exception) + { + ex = true; + } + + // Assert + Assert.False(ex); + + // Step 3 - Get the certificates that exist on the app gateway + + // Act + OperationResult> certs = client.GetAppGatewaySslCertificates(); + + // Assert + Assert.NotNull(certs.Result); + Assert.NotEmpty(certs.Result); + Assert.Contains(certs.Result, c => c.Alias == certName); + + // Step 4 - Try to remove the certificate from the app gateway, which should fail + // since it's bound to an HTTPS listener + + // Act + ex = false; + try + { + // Client should throw exception if certificate is bound to an HTTPS listener. + client.RemoveCertificate(certName); + } + catch (Exception) + { + ex = true; + } + + // Assert + Assert.True(ex); + + // Act + + // Step 5 - Remove the certificate from the HTTPS listener + + // Rebind the HTTPS listener with the original certificate, if there was only 1 certificate + // previously, otherwise bind it with the first certificate in the list. + + ApplicationGatewaySslCertificate replacement = client.GetAppGatewayCertificateByName(certs.Result.First(c => c.Alias != certName).Alias); + + client.UpdateHttpsListenerCertificate(replacement, env.HttpsListenerName); + + client.RemoveCertificate(certName); + + // Act + + // Step 6 - Test the GetHttpsListenerCertificates method + + // boundCertificates in the form of + IDictionary boundCertificates = client.GetBoundHttpsListenerCertificates(); + } + + public static X509Certificate2 GetSelfSignedCert(string hostname) + { + RSA rsa = RSA.Create(2048); + CertificateRequest req = new CertificateRequest($"CN={hostname}", rsa, HashAlgorithmName.SHA256, + RSASignaturePadding.Pkcs1); + + SubjectAlternativeNameBuilder subjectAlternativeNameBuilder = new SubjectAlternativeNameBuilder(); + subjectAlternativeNameBuilder.AddDnsName(hostname); + req.CertificateExtensions.Add(subjectAlternativeNameBuilder.Build()); + req.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false)); + req.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new Oid("2.5.29.32.0"), new Oid("1.3.6.1.5.5.7.3.1") }, false)); + + X509Certificate2 selfSignedCert = req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5)); + Console.Write($"Created self-signed certificate for \"{hostname}\" with thumbprint {selfSignedCert.Thumbprint}\n"); + return selfSignedCert; + } + + static void ConfigureLogging() + { + var config = new NLog.Config.LoggingConfiguration(); + + // Targets where to log to: File and Console + var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); + logconsole.Layout = @"${date:format=HH\:mm\:ss} ${logger} [${level}] - ${message}"; + + // Rules for mapping loggers to targets + config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logconsole); + + // Apply config + NLog.LogManager.Configuration = config; + + LogHandler.Factory = LoggerFactory.Create(builder => + { + builder.AddNLog(); + }); + } +} + diff --git a/AzureAppGatewayOrchestrator.Tests/AzureAppGatewayOrchestrator_FakeClient.cs b/AzureAppGatewayOrchestrator.Tests/FakeClient.cs similarity index 76% rename from AzureAppGatewayOrchestrator.Tests/AzureAppGatewayOrchestrator_FakeClient.cs rename to AzureAppGatewayOrchestrator.Tests/FakeClient.cs index 6115ed6..651fcb2 100644 --- a/AzureAppGatewayOrchestrator.Tests/AzureAppGatewayOrchestrator_FakeClient.cs +++ b/AzureAppGatewayOrchestrator.Tests/FakeClient.cs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System.Security.Cryptography.X509Certificates; using Azure.ResourceManager.Network.Models; using AzureApplicationGatewayOrchestratorExtension.Client; using Keyfactor.Logging; @@ -23,52 +24,59 @@ namespace AzureAppGatewayOrchestrator.Tests; public class FakeClient : IAzureAppGatewayClient { - public class FakeBuilder : IAzureAppGatewayClientBuilder - { - private FakeClient _client = new FakeClient(); + public class FakeBuilder : IAzureAppGatewayClientBuilder + { + private FakeClient _client = new FakeClient(); - public string _tenantId { get; set; } - public string _resourceId { get; set; } - public string _applicationId { get; set; } - public string _clientSecret { get; set; } - public string _azureCloudEndpoint { get; set; } + public string? _tenantId { get; set; } + public string? _resourceId { get; set; } + public string? _applicationId { get; set; } + public string? _clientSecret { get; set; } + public X509Certificate2? _clientCertificate { get; set; } + public string? _azureCloudEndpoint { get; set; } - public IAzureAppGatewayClientBuilder WithTenantId(string tenantId) - { - _tenantId = tenantId; - return this; - } + public IAzureAppGatewayClientBuilder WithTenantId(string tenantId) + { + _tenantId = tenantId; + return this; + } - public IAzureAppGatewayClientBuilder WithResourceId(string resourceId) - { - _resourceId = resourceId; - return this; - } + public IAzureAppGatewayClientBuilder WithResourceId(string resourceId) + { + _resourceId = resourceId; + return this; + } - public IAzureAppGatewayClientBuilder WithApplicationId(string applicationId) - { - _applicationId = applicationId; - return this; - } + public IAzureAppGatewayClientBuilder WithApplicationId(string applicationId) + { + _applicationId = applicationId; + return this; + } - public IAzureAppGatewayClientBuilder WithClientSecret(string clientSecret) - { - _clientSecret = clientSecret; - return this; - } + public IAzureAppGatewayClientBuilder WithClientSecret(string clientSecret) + { + _clientSecret = clientSecret; + return this; + } - public IAzureAppGatewayClientBuilder WithAzureCloud(string azureCloud) - { - _azureCloudEndpoint = azureCloud; - return this; - } + public IAzureAppGatewayClientBuilder WithClientCertificate(X509Certificate2 clientCertificate) + { + _clientCertificate = clientCertificate; + return this; + } - public IAzureAppGatewayClient Build() - { - return _client; - } + public IAzureAppGatewayClientBuilder WithAzureCloud(string azureCloud) + { + _azureCloudEndpoint = azureCloud; + return this; } + public IAzureAppGatewayClient Build() + { + return _client; + } + } + ILogger _logger = LogHandler.GetClassLogger(); public IEnumerable? AppGatewaysAvailableOnFakeTenant { get; set; } @@ -89,13 +97,13 @@ public OperationResult> GetAppGatewaySslCertif foreach (ApplicationGatewaySslCertificate cert in CertificatesAvailableOnFakeAppGateway.Values) { inventoryItems.Add(new CurrentInventoryItem - { - Alias = cert.Name, - PrivateKeyEntry = false, - ItemStatus = OrchestratorInventoryItemStatus.Unknown, - UseChainLevel = true, - Certificates = new List { cert.Name } - }); + { + Alias = cert.Name, + PrivateKeyEntry = false, + ItemStatus = OrchestratorInventoryItemStatus.Unknown, + UseChainLevel = true, + Certificates = new List { cert.Name } + }); } _logger.LogDebug($"Fake client has {inventoryItems.Count} certificates in inventory"); @@ -115,9 +123,9 @@ public ApplicationGatewaySslCertificate AddCertificate(string certificateName, s ApplicationGatewaySslCertificate cert = new ApplicationGatewaySslCertificate { Name = certificateName, - Data = BinaryData.FromObjectAsJson(certificateData), - // Reserve the Password field for tracking certificates bound to HTTPS listeners - Password = "" + Data = BinaryData.FromObjectAsJson(certificateData), + // Reserve the Password field for tracking certificates bound to HTTPS listeners + Password = "" }; _logger.LogDebug($"Adding certificate {certificateName} to fake app gateway"); diff --git a/AzureAppGatewayOrchestrator.Tests/IntegrationTestingFact.cs b/AzureAppGatewayOrchestrator.Tests/IntegrationTestingFact.cs index 53e1bf1..ce21f39 100644 --- a/AzureAppGatewayOrchestrator.Tests/IntegrationTestingFact.cs +++ b/AzureAppGatewayOrchestrator.Tests/IntegrationTestingFact.cs @@ -20,6 +20,7 @@ public sealed class IntegrationTestingFact : FactAttribute public string TenantId { get; private set; } public string ApplicationId { get; private set; } public string ClientSecret { get; private set; } + public string ClientCertificatePath { get; private set; } public string ResourceId { get; private set; } public IntegrationTestingFact() @@ -28,12 +29,37 @@ public IntegrationTestingFact() TenantId = Environment.GetEnvironmentVariable("AZURE_TENANT_ID") ?? string.Empty; ApplicationId = Environment.GetEnvironmentVariable("AZURE_CLIENT_ID") ?? string.Empty; ClientSecret = Environment.GetEnvironmentVariable("AZURE_CLIENT_SECRET") ?? string.Empty; + ClientCertificatePath = Environment.GetEnvironmentVariable("AZURE_PATH_TO_CLIENT_CERTIFICATE") ?? string.Empty; ResourceId = Environment.GetEnvironmentVariable("AZURE_APP_GATEWAY_RESOURCE_ID") ?? string.Empty; - if (string.IsNullOrEmpty(HttpsListenerName) || string.IsNullOrEmpty(TenantId) || string.IsNullOrEmpty(ApplicationId) || string.IsNullOrEmpty(ClientSecret) || string.IsNullOrEmpty(ResourceId)) + if (string.IsNullOrEmpty(HttpsListenerName) || string.IsNullOrEmpty(TenantId) || string.IsNullOrEmpty(ApplicationId) || string.IsNullOrEmpty(ClientSecret) || string.IsNullOrEmpty(ResourceId) || string.IsNullOrEmpty(ClientCertificatePath)) { Skip = "Integration testing environment variables are not set - Skipping test. Please run `make setup` to set the environment variables."; } } } +public sealed class IntegrationTestingTheory : TheoryAttribute +{ + public string HttpsListenerName { get; private set; } + public string TenantId { get; private set; } + public string ApplicationId { get; private set; } + public string ClientSecret { get; private set; } + public string ClientCertificatePath { get; private set; } + public string ResourceId { get; private set; } + + public IntegrationTestingTheory() + { + HttpsListenerName = Environment.GetEnvironmentVariable("AZURE_APP_GATEWAY_HTTPS_LISTENER_NAME") ?? string.Empty; + TenantId = Environment.GetEnvironmentVariable("AZURE_TENANT_ID") ?? string.Empty; + ApplicationId = Environment.GetEnvironmentVariable("AZURE_CLIENT_ID") ?? string.Empty; + ClientSecret = Environment.GetEnvironmentVariable("AZURE_CLIENT_SECRET") ?? string.Empty; + ClientCertificatePath = Environment.GetEnvironmentVariable("AZURE_PATH_TO_CLIENT_CERTIFICATE") ?? string.Empty; + ResourceId = Environment.GetEnvironmentVariable("AZURE_APP_GATEWAY_RESOURCE_ID") ?? string.Empty; + + if (string.IsNullOrEmpty(HttpsListenerName) || string.IsNullOrEmpty(TenantId) || string.IsNullOrEmpty(ApplicationId) || string.IsNullOrEmpty(ClientSecret) || string.IsNullOrEmpty(ResourceId) || string.IsNullOrEmpty(ClientCertificatePath)) + { + Skip = "Integration testing environment variables are not set - Skipping test. Please run `make setup` to set the environment variables."; + } + } +} diff --git a/AzureAppGatewayOrchestrator.Tests/JobClientBuilder.cs b/AzureAppGatewayOrchestrator.Tests/JobClientBuilder.cs new file mode 100644 index 0000000..f953d86 --- /dev/null +++ b/AzureAppGatewayOrchestrator.Tests/JobClientBuilder.cs @@ -0,0 +1,164 @@ +// Copyright 2024 Keyfactor +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using AzureAppGatewayOrchestrator.Tests; +using AzureApplicationGatewayOrchestratorExtension; +using AzureApplicationGatewayOrchestratorExtension.Client; +using Keyfactor.Logging; +using Keyfactor.Orchestrators.Extensions; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; + +public class JobClientBuilder +{ + ILogger _logger { get; set;} + + public JobClientBuilder() + { + ConfigureLogging(); + + _logger = LogHandler.GetClassLogger(); + } + + [Fact] + public void AppGatewayJobClientBuilder_ValidCertificateStoreConfigClientSecret_BuildValidClient() + { + // Verify that the AppGatewayJobClientBuilder uses the certificate store configuration + // provided by Keyfactor Command/the Universal Orchestrator correctly as required + // by the IAzureAppGatewayClientBuilder interface. + + // Arrange + AppGatewayJobClientBuilder jobClientBuilderWithFakeBuilder = new(); + + // Set up the certificate store with names that correspond to how we expect them to be interpreted by + // the builder + CertificateStore fakeCertificateStoreDetails = new() + { + ClientMachine = "fake-tenant-id", + StorePath = "fake-azure-resource-id", + Properties = "{\"ServerUsername\":\"fake-azure-application-id\",\"ServerPassword\":\"fake-azure-client-secret\",\"AzureCloud\":\"fake-azure-cloud\"}" + }; + + // Act + IAzureAppGatewayClient fakeAppGatewayClient = jobClientBuilderWithFakeBuilder + .WithCertificateStoreDetails(fakeCertificateStoreDetails) + .Build(); + + // Assert + + // IAzureAppGatewayClient doesn't require any of the properties set by the builder to be exposed + // since the production Build() method creates an Azure Resource Manager client. + // But, our builder is fake and exposes the properties we need to test (via the FakeBuilder class). + Assert.Equal("fake-tenant-id", jobClientBuilderWithFakeBuilder._builder._tenantId); + Assert.Equal("fake-azure-resource-id", jobClientBuilderWithFakeBuilder._builder._resourceId); + Assert.Equal("fake-azure-application-id", jobClientBuilderWithFakeBuilder._builder._applicationId); + Assert.Equal("fake-azure-client-secret", jobClientBuilderWithFakeBuilder._builder._clientSecret); + Assert.Equal("fake-azure-cloud", jobClientBuilderWithFakeBuilder._builder._azureCloudEndpoint); + + _logger.LogInformation("AppGatewayJobClientBuilder_ValidCertificateStoreConfigClientSecret_BuildValidClient - Success"); + } + + [IntegrationTestingTheory] + [InlineData("pkcs12")] + [InlineData("pem")] + [InlineData("encryptedPem")] + public void AppGatewayJobClientBuilder_ValidCertificateStoreConfigClientCertificate_BuildValidClient(string certificateFormat) + { + // Verify that the AppGatewayJobClientBuilder uses the certificate store configuration + // provided by Keyfactor Command/the Universal Orchestrator correctly as required + // by the IAzureGraphClientBuilder interface. + + // Arrange + AppGatewayJobClientBuilder jobClientBuilderWithFakeBuilder = new(); + + string password = "passwordpasswordpassword"; + string certName = "SPTest" + Guid.NewGuid().ToString()[..6]; + X509Certificate2 ssCert = Client.GetSelfSignedCert(certName); + + string b64ClientCertificate; + if (certificateFormat == "pkcs12") + { + b64ClientCertificate = Convert.ToBase64String(ssCert.Export(X509ContentType.Pfx, password)); + } + else if (certificateFormat == "pem") + { + string pemCert = ssCert.ExportCertificatePem(); + string keyPem = ssCert.GetRSAPrivateKey()!.ExportPkcs8PrivateKeyPem(); + b64ClientCertificate = Convert.ToBase64String(Encoding.UTF8.GetBytes(keyPem + '\n' + pemCert)); + password = ""; + } + else + { + PbeParameters pbeParameters = new PbeParameters( + PbeEncryptionAlgorithm.Aes256Cbc, + HashAlgorithmName.SHA384, + 300_000); + string pemCert = ssCert.ExportCertificatePem(); + string keyPem = ssCert.GetRSAPrivateKey()!.ExportEncryptedPkcs8PrivateKeyPem(password.ToCharArray(), pbeParameters); + b64ClientCertificate = Convert.ToBase64String(Encoding.UTF8.GetBytes(keyPem + '\n' + pemCert)); + } + + // Set up the certificate store with names that correspond to how we expect them to be interpreted by + // the builder + CertificateStore fakeCertificateStoreDetails = new() + { + ClientMachine = "fake-tenant-id", + StorePath = "fake-azure-resource-id", + Properties = $@"{{""ServerUsername"": ""fake-azure-application-id"",""ServerPassword"": ""{password}"",""ClientCertificate"": ""{b64ClientCertificate}"",""AzureCloud"": ""fake-azure-cloud""}}" + }; + + // Act + IAzureAppGatewayClient fakeAppGatewayClient = jobClientBuilderWithFakeBuilder + .WithCertificateStoreDetails(fakeCertificateStoreDetails) + .Build(); + + // Assert + + // IAzureAppGatewayClient doesn't require any of the properties set by the builder to be exposed + // since the production Build() method creates an Azure Resource Manager client. + // But, our builder is fake and exposes the properties we need to test (via the FakeBuilder class). + Assert.Equal("fake-tenant-id", jobClientBuilderWithFakeBuilder._builder._tenantId); + Assert.Equal("fake-azure-resource-id", jobClientBuilderWithFakeBuilder._builder._resourceId); + Assert.Equal("fake-azure-application-id", jobClientBuilderWithFakeBuilder._builder._applicationId); + Assert.Equal("fake-azure-cloud", jobClientBuilderWithFakeBuilder._builder._azureCloudEndpoint); + Assert.Equal(ssCert.GetCertHash(), jobClientBuilderWithFakeBuilder._builder._clientCertificate!.GetCertHash()); + Assert.NotNull(jobClientBuilderWithFakeBuilder._builder._clientCertificate!.GetRSAPrivateKey()); + Assert.Equal(jobClientBuilderWithFakeBuilder._builder._clientCertificate!.GetRSAPrivateKey()!.ExportRSAPrivateKeyPem(), ssCert.GetRSAPrivateKey()!.ExportRSAPrivateKeyPem()); + + _logger.LogInformation("AppGatewayJobClientBuilder_ValidCertificateStoreConfigClientCertificate_BuildValidClient - Success"); + } + + static void ConfigureLogging() + { + var config = new NLog.Config.LoggingConfiguration(); + + // Targets where to log to: File and Console + var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); + logconsole.Layout = @"${date:format=HH\:mm\:ss} ${logger} [${level}] - ${message}"; + + // Rules for mapping loggers to targets + config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logconsole); + + // Apply config + NLog.LogManager.Configuration = config; + + LogHandler.Factory = LoggerFactory.Create(builder => + { + builder.AddNLog(); + }); + } +} diff --git a/AzureAppGatewayOrchestrator/AppGatewayJobClientBuilder.cs b/AzureAppGatewayOrchestrator/AppGatewayJobClientBuilder.cs index b267930..dfc7a34 100644 --- a/AzureAppGatewayOrchestrator/AppGatewayJobClientBuilder.cs +++ b/AzureAppGatewayOrchestrator/AppGatewayJobClientBuilder.cs @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text; using AzureApplicationGatewayOrchestratorExtension.Client; using Keyfactor.Logging; using Keyfactor.Orchestrators.Extensions; @@ -29,6 +33,7 @@ public class CertificateStoreProperties { public string ServerUsername { get; set; } public string ServerPassword { get; set; } + public string ClientCertificate { get; init; } public string AzureCloud { get; set; } } @@ -47,10 +52,23 @@ public AppGatewayJobClientBuilder WithCertificateStoreDetails(Certific _builder .WithTenantId(details.ClientMachine) .WithApplicationId(properties.ServerUsername) - .WithClientSecret(properties.ServerPassword) .WithResourceId(details.StorePath) .WithAzureCloud(properties.AzureCloud); + if (string.IsNullOrWhiteSpace(properties.ClientCertificate)) + { + _logger.LogTrace($"Builder - ServerPassword => ClientSecret: {properties.ServerPassword}"); + _logger.LogDebug("Client certificate not present - Using Client Secret authentication"); + _builder.WithClientSecret(properties.ServerPassword); + } + else + { + _logger.LogTrace($"Builder - ServerPassword => ClientCertificateKeyPassword: {properties.ServerPassword}"); + _logger.LogDebug("Client certificate present - Using Client Certificate authentication"); + X509Certificate2 clientCert = SerializeClientCertificate(properties.ClientCertificate, properties.ServerPassword); + _builder.WithClientCertificate(clientCert); + } + return this; } @@ -72,4 +90,98 @@ public IAzureAppGatewayClient Build() { return _builder.Build(); } + + private X509Certificate2 SerializeClientCertificate(string clientCertificate, string password) + { + // clientCertificate is a Base64 encoded certificate that's either PEM or PKCS#12 encoded. + // We expect that it includes a private key compatible with the dotnet standard crypto libraries. + + byte[] rawCertBytes = Convert.FromBase64String(clientCertificate); + X509Certificate2 serializedCertificate = null; + + // Try to serialize the certificate without any special handling + try + { + serializedCertificate = new X509Certificate2(rawCertBytes, password, X509KeyStorageFlags.Exportable); + if (serializedCertificate.HasPrivateKey) { + _logger.LogTrace("Successfully serialized certificate using standard X509Certificate2"); + return serializedCertificate; + } + } + catch (CryptographicException e) + { + _logger.LogDebug($"Couldn't serialize certificate using X509Certificate2: {e.Message} - trying to serialize from PEM"); + } + + try + { + return SerializePemCertificateAndKey(clientCertificate, password); + } + catch (Exception e) + { + string message = $"Couldn't serialize certificate as PEM: {e.Message} - please ensure that the certificate is valid."; + _logger.LogError(message); + throw new CryptographicException(message); + } + } + + private X509Certificate2 SerializePemCertificateAndKey(string clientCertificate, string password) + { + _logger.LogDebug($"Attempting to serialize client certificate and private key from PEM encoding"); + ReadOnlySpan utf8Cert = Encoding.UTF8.GetChars(Convert.FromBase64String(clientCertificate)); + + _logger.LogTrace("Finding all PEM objects in ClientCertificate"); + + ReadOnlySpan certificate = new char[0]; + ReadOnlySpan key = new char[0]; + + int numberOfPemObjects = 0; + + while (PemEncoding.TryFind(utf8Cert, out PemFields field)) + { + numberOfPemObjects++; + string label = utf8Cert[field.Label].ToString(); + _logger.LogTrace($"Found PEM object with label {label} at location {field.Location}"); + + if (label == "CERTIFICATE") + { + _logger.LogTrace($"Storing {label} as certificate for serialization"); + certificate = utf8Cert[field.Location]; + } + else + { + _logger.LogTrace($"Storing {label} as private key for serialization"); + key = utf8Cert[field.Location]; + } + + // Reconstruct utf8Cert without the PEM object + Range objectRange = field.Location; + int start = objectRange.Start.Value; + int end = objectRange.End.Value; + char[] newUtf8Cert = new char[utf8Cert.Length - (end - start)]; + + _logger.LogTrace($"Trimming range {field.Location} [{end - start} bytes]"); + // Copy over the slice before the start of the range + utf8Cert.Slice(0, start).CopyTo(newUtf8Cert); + // Copy over the slice after the end of the range + utf8Cert.Slice(end).CopyTo(newUtf8Cert.AsSpan(start)); + + utf8Cert = newUtf8Cert; + } + + if (numberOfPemObjects != 2) + { + throw new CryptographicException($"Expected 2 PEM objects in ClientCertificate, found {numberOfPemObjects}"); + } + + _logger.LogDebug("Successfully extracted certificate and private key from PEM encoding - serializing certificate"); + if (string.IsNullOrEmpty(password)) + { + return X509Certificate2.CreateFromPem(certificate, key); + } + else + { + return X509Certificate2.CreateFromEncryptedPem(certificate, key, password); + } + } } diff --git a/AzureAppGatewayOrchestrator/AzureAppGatewayOrchestrator.csproj b/AzureAppGatewayOrchestrator/AzureAppGatewayOrchestrator.csproj index 5189ac8..5a55b12 100644 --- a/AzureAppGatewayOrchestrator/AzureAppGatewayOrchestrator.csproj +++ b/AzureAppGatewayOrchestrator/AzureAppGatewayOrchestrator.csproj @@ -1,7 +1,7 @@ - net6.0 + net8.0 AzureApplicationGatewayOrchestratorExtension AzureApplicationGatewayOrchestratorExtension false diff --git a/AzureAppGatewayOrchestrator/Client/GatewayClient.cs b/AzureAppGatewayOrchestrator/Client/GatewayClient.cs index e14b649..c810faf 100644 --- a/AzureAppGatewayOrchestrator/Client/GatewayClient.cs +++ b/AzureAppGatewayOrchestrator/Client/GatewayClient.cs @@ -65,6 +65,7 @@ public class Builder : IAzureAppGatewayClientBuilder private string _resourceId { get; set; } private string _applicationId { get; set; } private string _clientSecret { get; set; } + private X509Certificate2 _clientCertificate { get; set; } private Uri _azureCloudEndpoint { get; set; } public IAzureAppGatewayClientBuilder WithTenantId(string tenantId) @@ -91,6 +92,12 @@ public IAzureAppGatewayClientBuilder WithClientSecret(string clientSecret) return this; } + public IAzureAppGatewayClientBuilder WithClientCertificate(X509Certificate2 clientCertificate) + { + _clientCertificate = clientCertificate; + return this; + } + public IAzureAppGatewayClientBuilder WithAzureCloud(string azureCloud) { if (string.IsNullOrWhiteSpace(azureCloud)) @@ -129,9 +136,23 @@ public IAzureAppGatewayClient Build() AdditionallyAllowedTenants = { "*" } }; - TokenCredential credential = new ClientSecretCredential( - _tenantId, _applicationId, _clientSecret, credentialOptions - ); + TokenCredential credential; + if (!string.IsNullOrWhiteSpace(_clientSecret)) + { + credential = new ClientSecretCredential( + _tenantId, _applicationId, _clientSecret, credentialOptions + ); + } + else if (_clientCertificate != null) + { + credential = new ClientCertificateCredential( + _tenantId, _applicationId, _clientCertificate, credentialOptions + ); + } + else + { + throw new Exception("Client secret or client certificate must be provided."); + } // Creating Azure Resource Management client with the specified credentials. ArmClient armClient = new ArmClient(credential); @@ -159,14 +180,31 @@ private string RetrieveCertificateFromKeyVault(string vaultId) } }; - // vaultId in the form of https://.vault.azure.net/secrets/ + // vaultId in the form of https://.vault.azure.net/secrets/[/] Uri vaultUri = new Uri(vaultId); _logger.LogTrace($"Creating SecretClient object with URI {vaultUri.Scheme + "://" + vaultUri.Host}"); SecretClient client = new SecretClient(new Uri(vaultUri.Scheme + "://" + vaultUri.Host), _credential, options); - _logger.LogTrace($"Retrieving secret called \"{vaultUri.Segments.Last()}\" from Azure Key Vault"); - KeyVaultSecret secret = client.GetSecret(vaultUri.Segments.Last()); + string secretName = null; + string version = null; + if (vaultUri.Segments.Length == 3) + { + secretName = vaultUri.Segments.Last().TrimEnd('/'); + _logger.LogTrace($"Retrieving secret called \"{secretName}\" from Azure Key Vault"); + } + else if (vaultUri.Segments.Length == 4) + { + secretName = vaultUri.Segments[2].TrimEnd('/'); + version = vaultUri.Segments.Last().TrimEnd('/'); + _logger.LogTrace($"Retrieving secret called \"{secretName}\" with version \"{version}\" from Azure Key Vault"); + } + else + { + throw new Exception($"Invalid Azure Key Vault secret ID: {vaultId}"); + } + + KeyVaultSecret secret = client.GetSecret(secretName, version); if (String.IsNullOrWhiteSpace(secret.Properties.ContentType) || secret.Properties.ContentType != "application/x-pkcs12") { diff --git a/AzureAppGatewayOrchestrator/Client/IAzureAppGatewayClient.cs b/AzureAppGatewayOrchestrator/Client/IAzureAppGatewayClient.cs index efe872e..f1d8bbd 100644 --- a/AzureAppGatewayOrchestrator/Client/IAzureAppGatewayClient.cs +++ b/AzureAppGatewayOrchestrator/Client/IAzureAppGatewayClient.cs @@ -13,52 +13,53 @@ // limitations under the License. using System.Collections.Generic; +using System.Security.Cryptography.X509Certificates; using Azure.ResourceManager.Network.Models; using Keyfactor.Orchestrators.Extensions; -namespace AzureApplicationGatewayOrchestratorExtension.Client +namespace AzureApplicationGatewayOrchestratorExtension.Client; + +public interface IAzureAppGatewayClientBuilder +{ + public IAzureAppGatewayClientBuilder WithTenantId(string tenantId); + public IAzureAppGatewayClientBuilder WithResourceId(string resourceId); + public IAzureAppGatewayClientBuilder WithApplicationId(string applicationId); + public IAzureAppGatewayClientBuilder WithClientSecret(string clientSecret); + public IAzureAppGatewayClientBuilder WithClientCertificate(X509Certificate2 clientCertificate); + public IAzureAppGatewayClientBuilder WithAzureCloud(string azureCloud); + public IAzureAppGatewayClient Build(); +} + +public class OperationResult { - public interface IAzureAppGatewayClientBuilder + public T Result { get; set; } + public string ErrorSummary { get; set; } + public List Messages { get; set; } = new List(); + public bool Success => Messages.Count == 0; + + public OperationResult(T result) { - public IAzureAppGatewayClientBuilder WithTenantId(string tenantId); - public IAzureAppGatewayClientBuilder WithResourceId(string resourceId); - public IAzureAppGatewayClientBuilder WithApplicationId(string applicationId); - public IAzureAppGatewayClientBuilder WithClientSecret(string clientSecret); - public IAzureAppGatewayClientBuilder WithAzureCloud(string azureCloud); - public IAzureAppGatewayClient Build(); + Result = result; } - public class OperationResult + public void AddRuntimeErrorMessage(string message) { - public T Result { get; set; } - public string ErrorSummary { get; set; } - public List Messages { get; set; } = new List(); - public bool Success => Messages.Count == 0; - - public OperationResult(T result) - { - Result = result; - } - - public void AddRuntimeErrorMessage(string message) - { - Messages.Add(" - " + message); - } - - public string ErrorMessage => $"{ErrorSummary}\n{string.Join("\n", Messages)}"; + Messages.Add(" - " + message); } - public interface IAzureAppGatewayClient - { - public ApplicationGatewaySslCertificate AddCertificate(string certificateName, string certificateData, string certificatePassword); - public void RemoveCertificate(string certificateName); - public OperationResult> GetAppGatewaySslCertificates(); - public ApplicationGatewaySslCertificate GetAppGatewayCertificateByName(string certificateName); - public bool CertificateExists(string certificateName); - public IEnumerable DiscoverApplicationGateways(); + public string ErrorMessage => $"{ErrorSummary}\n{string.Join("\n", Messages)}"; +} - public bool CertificateIsBoundToHttpsListener(string certificateName); - public void UpdateHttpsListenerCertificate(ApplicationGatewaySslCertificate certificate, string listenerName); - public IDictionary GetBoundHttpsListenerCertificates(); - } +public interface IAzureAppGatewayClient +{ + public ApplicationGatewaySslCertificate AddCertificate(string certificateName, string certificateData, string certificatePassword); + public void RemoveCertificate(string certificateName); + public OperationResult> GetAppGatewaySslCertificates(); + public ApplicationGatewaySslCertificate GetAppGatewayCertificateByName(string certificateName); + public bool CertificateExists(string certificateName); + public IEnumerable DiscoverApplicationGateways(); + + public bool CertificateIsBoundToHttpsListener(string certificateName); + public void UpdateHttpsListenerCertificate(ApplicationGatewaySslCertificate certificate, string listenerName); + public IDictionary GetBoundHttpsListenerCertificates(); } diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a8a9df..1630d58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,3 +20,8 @@ - 2.1.0 - chore(client): Pass error back to Command if certificate download from AKV fails + +- 3.0.0 + - feat(certauth): Implement client certificate authentication as an alternative authentication mechanism. + - chore(docs): Update documentation to discuss the Key Vault Azure role-based access control permission model. + - fix(akv): Refactor Azure Key Vault certificate retrieval mechanism to recognize and appropriately handle secret versions. diff --git a/README.md b/README.md index fa9df4f..bfacc48 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,38 @@ The Keyfactor Universal Orchestrator may be installed on either Windows or Linux --- +

+ Azure Application Gateway Universal Orchestrator Extension +

+ +

+ +Integration Status: production +Release +Issues +GitHub Downloads (all assets, all releases) +

+ +

+ + + Support + + · + + Installation + + · + + License + + · + + Related Integrations + +

+ + ## Overview The Azure Application Gateway Orchestrator extension remotely manages certificates used by Azure Application Gateways. The extension supports two different store types - one that generally manages certificates stored in the Application Gateway, and one that manages the bindings of Application Gateway certificates to HTTPS/TLS Listeners. @@ -55,225 +87,246 @@ The Azure Application Gateway Orchestrator extension remotely manages certificat > > If the certificate management capabilities of Azure Key Vault are desired over direct management of certificates in Application Gateways, the Azure Key Vault orchestrator can be used in conjunction with this extension for accurate certificate location reporting via the inventory job type. This management strategy requires manual binding of certificates imported to an Application Gateway from AKV and can result in broken state in the Azure Application Gateway in the case that the secret is deleted in AKV. -### Azure Application Gateway Certificate store type - -The Azure Application Gateway Certificate store type, `AzureAppGw`, manages `ApplicationGatewaySslCertificate` objects owned by Azure Application Gateways. This store type collects inventory and manages all ApplicationGatewaySslCertificate objects associated with an Application Gateway. The store type is implemented primarily for Inventory and Management Remove operations, since the intended usage of ApplicationGatewaySslCertificates in Application Gateways is for serving TLS client traffic via TLS Listeners. Management Add and associated logic for certificate renewal is also supported for this certificate store type for completeness, but the primary intended functionality of this extension is implemented with the App Gateway Certificate Binding store type. - -> If an ApplicationGatewaySslCertificate is bound to a TLS Listener at the time of a Management Remove operation, the operation will fail since at least one certificate must be bound at all times. - -> If a renewal job is scheduled for an `AzureAppGw` certificate store, the extension will report a success and perform no action if the certificate being renewed is bound to a TLS Listener. This is because a certificate located in an `AzureAppGw` certificate store that is bound to a TLS Listener is logically the same as the same certificate located in an `AzureAppGwBin` store type. For this reason, it's expected that the certificate will be renewed and re-bound to the listener by the `AppGwBin` certificate operations. -> -> If the renewed certificate is not bound to a TLS Listener, the operation will be performed the same as any certificate renewal process that honors the Overwrite flag. -### Azure Application Gateway Certificate Binding store type +## Installation +Before installing the Azure Application Gateway Universal Orchestrator extension, it's recommended to install [kfutil](https://github.com/Keyfactor/kfutil). Kfutil is a command-line tool that simplifies the process of creating store types, installing extensions, and instantiating certificate stores in Keyfactor Command. -The Azure Application Gateway Certificate Binding store type, `AzureAppGwBin`, represents certificates bound to TLS Listeners on Azure App Gateways. The only supported operations on this store type are Management Add and Inventory. The Management Add operation for this store type creates and binds an ApplicationGatewaySslCertificate to a pre-existing TLS Listener on an Application Gateway. When the Add operation is configured in Keyfactor Command, the certificate Alias configures which TLS Listener the certificate will be bound to. If the HTTPS listener is already bound to a certificate with the same name, the Management Add operation will perform a replacement of the certificate, _**regardless of the existence of the Replace flag configured with renewal jobs**_. The replacement operation performs several API interactions with Azure since at least one certificate must be bound to a TLS listener at all times, and the name of ApplicationGatewaySslCertificates must be unique. For the sake of completeness, the following describes the mechanics of this replacement operation: - -1. Determine the name of the certificate currently bound to the HTTPS listener - Alias in 100% of cases if the certificate was originally added by the App Gateway Orchestrator Extension, or something else if the certificate was added by some other means (IE, the Azure Portal, or some other API client). -2. Create and bind a temporary certificate to the HTTPS listener with the same name as the Alias. -3. Delete the AppGatewayCertificate previously bound to the HTTPS listener called Alias. -4. Recreate and bind an AppGatewayCertificate with the same name as the HTTPS listener called Alias. If the Alias is called `listener1`, the new certificate will be called `listener1`, regardless of the name of the certificate that was previously bound to the listener. -5. Delete the temporary certificate. +The Azure Application Gateway Universal Orchestrator extension implements 2 Certificate Store Types. Depending on your use case, you may elect to install one, or all of these Certificate Store Types. An overview for each type is linked below: +* [Azure Application Gateway Certificate](docs/azureappgw.md) +* [Azure Application Gateway Certificate Binding](docs/appgwbin.md) -In the unlikely event that a failure occurs at any point in the replacement procedure, it's expected that the correct certificate will be served by the TLS Listener, since most of the mechanics are actually implemented to resolve the unique naming requirement. +
Azure Application Gateway Certificate -The Inventory job type for `AzureAppGwBin` reports only ApplicationGatewaySslCertificates that are bound to TLS Listeners. If the certificate was added with Keyfactor Command and this orchestrator extension, the name of the certificate in the Application Gateway will be the same as the TLS Listener. E.g., if the Alias configured in Command corresponds to a TLS Listener called `location-service-https-lstn1`, the certificate in the Application Gateway will also be called `location-service-https-lstn1`. However, if the certificate was added to the Application Gateway by other means (such as the Azure CLI, import from AKV, etc.), the Inventory job mechanics will still report the name of the TLS Listener in its report back to Command. -### Discovery Job +1. Follow the [requirements section](docs/azureappgw.md#requirements) to configure a Service Account and grant necessary API permissions. -Both `AzureAppGw` and `AzureAppGwBin` support the Discovery operation. The Discovery operation discovers all Azure Application Gateways in each resource group that the service principal has access to. The discovered Application Gateways are reported back to Command and can be easily added as certificate stores from the Locations tab. +
Requirements + + ### Azure Service Principal (Azure Resource Manager Authentication) -The Discovery operation uses the "Directories to search" field, and accepts input in one of the following formats: -- `*` - If the asterisk symbol `*` is used, the extension will search for Application Gateways in every resource group that the service principal has access to, but only in the tenant that the discovery job was configured for as specified by the "Client Machine" field in the certificate store configuration. -- `,,...` - If a comma-separated list of tenant IDs is used, the extension will search for Application Gateways in every resource group and tenant specified in the list. The tenant IDs should be the GUIDs associated with each tenant, and it's the user's responsibility to ensure that the service principal has access to the specified tenants. + The Azure Application Gateway Orchestrator extension uses an [Azure Service Principal](https://learn.microsoft.com/en-us/entra/identity-platform/app-objects-and-service-principals?tabs=browser) for authentication. Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/entra/identity-platform/howto-create-service-principal-portal) to create a service principal. -### Certificates Imported to Application Gateways from Azure Key Vault + #### Azure Application Gateway permissions -Natively, Azure Application Gateways support integration with Azure Key Vault for secret/certificate management. This integration works by creating a TLS Listener certificate with a reference to a secret in Azure Key Vault (specifically, a URI in the format `https://.vault.azure.net/secrets/`), authenticated using a Managed Identity. If the Application Gateway orchestrator extension is deployed to manage App Gateways with certificates imported from Azure Key Vault, the following truth table represents the possible operations and their result, specifically with respect to AKV. + For quick start and non-production environments, a Role Assignment should be created on _each resource group_ that own Application Gateways desiring management that grants the created Application/Service Principal the [Contributor (Privileged administrator) Role](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#contributor). For production environments, a custom role should be created that grants the following permissions: -| Store Type | Operation | Result | -|--------------|-----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `AzureAppGw` | Inventory | Certificate is downloaded from Azure Key Vault and reported back to Keyfactor Command. In Keyfactor Command, the certificate will show as being located in the AzureAppGw certificate store [in addition to the AKV, if AKV orchestrator extension is also deployed]. | -| `AzureAppGw` | Add | The Add operation will not create secrets in AKV; it creates ApplicationGatewaySslCertificates.

If an `AzureAppGw` Add operation is scheduled with the Replace flag, the _**link to the AKV certificate will be broken**_, and a native ApplicationGatewaySslCertificate will be created in its place - The secret in AKV will still exist. | -| `AzureAppGw` | Remove | The ApplicationGatewaySslCertificate is deleted from the Application Gateway, but the secret that the certificate referenced in AKV still exists. | -| `AzureAppGwBin` | Inventory | Certificate is downloaded from Azure Key Vault and reported back to Keyfactor Command. In Keyfactor Command, the certificate will show as present in both an `AzureAppGw` certificate store _and_ an `AppGwBin` certificate store [in addition to the AKV, if AKV orchestrator extension is also deployed]. | -| `AzureAppGwBin` | Add | The Add operation will not create secrets in AKV; it creates ApplicationGatewaySslCertificates.

If a certificate with the same name as the TLS Listener already exists, it will be _replaced_ by a new ApplicationGatewaySslCertificate.

If the certificate being replaced was imported from AKV, this binding will be broken and the secret will still exist in AKV. | + - `Microsoft.Resources/subscriptions/resourcegroups/read` - Read : Get Resource Group + - `Microsoft.Network/applicationGateways/read` - Read : Get Application Gateway + - `Microsoft.Network/applicationGateways/write` - Write : Create or Update Application Gateway + - `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action` - Other : RBAC action for assigning an existing user assigned identity to a resource + - `Microsoft.Network/virtualNetworks/subnets/join/action` - Other : Joins a virtual network. Not Alertable. -#### Mechanics of the Azure Key Vault Download Operation for Inventory Jobs that report certificates imported from AKV + > Note that even if the Service Principal has permission to perform the 'Microsoft.Network/applicationGateways/write' action over the scope of the required resource group, there may be other permissions that are required by the CreateOrUpdate operation depending on the complexity of the Application Gateway's configuration. As such, the list of permissions above should not be considered as comprehensive. -If an AzureApplicationSslCertificate references a secret in AKV (was imported to the App Gateway from AKV), the inventory job will create and use a `SecretClient` from the [`Azure.Security.KeyVault.Secrets.SecretClient` dotnet package](https://learn.microsoft.com/en-us/dotnet/api/azure.security.keyvault.secrets.secretclient?view=azure-dotnet). Authentication to AKV via this client is configured using the exact same `TokenCredential` provided by the [Azure Identity client library for .NET](https://learn.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme?view=azure-dotnet). This means that the Service Principal described in the [Azure Configuration](#azure-configuration) section must also have appropriate permissions to read secrets from the AKV that the App Gateway is integrated with. The secret referenced in the AzureApplicationSslCertificate will be accessed exactly as reported by Azure, regardless of whether it exists in AKV. + #### Azure Key Vault permissions -## Azure Configuration and Permissions + If the managed Application Gateway is integrated with Azure Key Vault per the discussion in the [Certificates Imported to Application Gateways from Azure Key Vault](#certificates-imported-to-application-gateways-from-azure-key-vault) section, perform one of the following actions for each Key Vault with certificates imported to App Gateways: + * **Azure role-based access control** - Create a Role Assignment that grants the Application/Service Principal the [Key Vault Secrets User](https://learn.microsoft.com/en-us/azure/key-vault/general/rbac-guide?tabs=azure-cli) built-in role. + * **Vault access policy** - [Create an Access Policy](https://learn.microsoft.com/en-us/azure/key-vault/general/assign-access-policy?tabs=azure-portal) that grants the Application/Service Principal the Get secret permission for each Azure Key Vault. -The Azure Application Gateway Orchestrator extension uses an [Azure Service Principal](https://learn.microsoft.com/en-us/entra/identity-platform/app-objects-and-service-principals?tabs=browser) for authentication. Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/azure/purview/create-service-principal-azure) to create a service principal. + #### Client Certificate or Client Secret -For quick start and non-production environments, a Role Assignment should be created on _each resource group_ that own Application Gateways desiring management that grants the created Application/Service Principal the [Contributor (Privileged administrator) Role](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#contributor). For production environments, a custom role should be created that grants the following permissions: + Beginning in version 3.0.0, the Azure Application Gateway Orchestrator extension supports both [client certificate authentication](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) and [client secret](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-2-add-a-client-secret) authentication. -- `Microsoft.Resources/subscriptions/resourcegroups/read` - Read : Get Resource Group -- `Microsoft.Network/applicationGateways/read` - Read : Get Application Gateway -- `Microsoft.Network/applicationGateways/write` - Write : Create or Update Application Gateway -- `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action` - Other : RBAC action for assigning an existing user assigned identity to a resource -- `Microsoft.Network/virtualNetworks/subnets/join/action` - Other : Joins a virtual network. Not Alertable. + * **Client Secret** - Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-2-add-a-client-secret) to create a Client Secret. This secret will be used as the **Server Password** field in the [Certificate Store Configuration](#certificate-store-configuration) section. + * **Client Certificate** - Create a client certificate key pair with the Client Authentication extended key usage. The client certificate will be used in the ClientCertificate field in the [Certificate Store Configuration](#certificate-store-configuration) section. If you have access to Keyfactor Command, the instructions in this section walk you through enrolling a certificate and ensuring that it's in the correct format. Once enrolled, follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) to add the _public key_ certificate (no private key) to the service principal used for authentication. -> Note that even if the Service Principal has permission to perform the 'Microsoft.Network/applicationGateways/write' action over the scope of the required resource group, there may be other permissions that are required by the CreateOrUpdate operation depending on the complexity of the Application Gateway's configuration. As such, the list of permissions above should not be considered as comprehensive. + The certificate can be in either of the following formats: + * Base64-encoded PKCS#12 (PFX) with a matching private key. + * Base64-encoded PEM-encoded certificate _and_ PEM-encoded PKCS8 private key. Make sure that the certificate and private key are separated with a newline. The order doesn't matter - the extension will determine which is which. -If the managed Application Gateway is integrated with Azure Key Vault per the discussion in the [Certificates Imported to Application Gateways from Azure Key Vault](#certificates-imported-to-application-gateways-from-azure-key-vault) section, an [Access policy must be created](https://learn.microsoft.com/en-us/azure/key-vault/general/assign-access-policy?tabs=azure-portal) that grants the Application/Service Principal the Get secret permission for the associated Azure Key Vault. + If the private key is encrypted, the encryption password will replace the **Server Password** field in the [Certificate Store Configuration](#certificate-store-configuration) section. -## Creating Store Types for the Azure Application Gateway Orchestrator -To get started with the Azure Application Gateway Orchestrator Extension, you'll need to create 2 store types in Keyfactor Command. The recommended and supported way to create store types is using the `kfutil` command line tool. Install [Kfutil](https://github.com/Keyfactor/kfutil) if it is not already installed. Once installed, use `kfutil login` to log into the target Command environment. + > **Creating and Formatting a Client Certificate using Keyfactor Command** + > + > To get started quickly, you can follow the instructions below to create and properly format a client certificate to authenticate to the Microsoft Graph API. + > + > 1. In Keyfactor Command, hover over **Enrollment** and select **PFX Enrollment**. + > 2. Select a **Template** that supports Client Authentication as an extended key usage. + > 3. Populate the certificate subject as appropriate for the Template. It may be sufficient to only populate the Common Name, but consult your IT policy to ensure that this certificate is compliant. + > 4. At the bottom of the page, uncheck the box for **Include Chain**, and select either **PFX** or **PEM** as the certificate Format. + > 5. Make a note of the password on the next page - it won't be shown again. + > 6. Prepare the certificate and private key for Azure and the Orchestrator extension: + > * If you downloaded the certificate in PEM format, use the commands below: + > + > ```shell + > # Verify that the certificate downloaded from Command contains the certificate and private key. They should be in the same file + > cat + > + > # Separate the certificate from the private key + > openssl x509 -in -out pubkeycert.pem + > + > # Base64 encode the certificate and private key + > cat | base64 > clientcertkeypair.pem.base64 + > ``` + > + > * If you downloaded the certificate in PFX format, use the commands below: + > + > ```shell + > # Export the certificate from the PFX file + > openssl pkcs12 -in -clcerts -nokeys -out pubkeycert.pem + > + > # Base64 encode the PFX file + > cat | base64 > clientcert.pfx.base64 + > ``` + > 7. Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) to add the public key certificate to the service principal used for authentication. + > + > You will use `clientcert.[pem|pfx].base64` as the **ClientCertificate** field in the [Certificate Store Configuration](#certificate-store-configuration) section. -Then, use the following commands to create the store types: -```shell -kfutil store-types create AzureAppGw -kfutil store-types create AppGwBin -``` +
-It is not required to create all store types. Only create the store types that are needed for the integration. +2. Create Certificate Store Types for the Azure Application Gateway Orchestrator extension. -If you prefer to create store types manually in the UI, navigate to your Command instance and follow the instructions below. -
AzureAppGw + * **Using kfutil**: -Create a store type called `AzureAppGw` with the attributes in the tables below: + ```shell + # Azure Application Gateway Certificate + kfutil store-types create AzureAppGw + ``` -### Basic Tab -| Attribute | Value | Description | -| --------- | ----- | ----- | -| Name | Azure Application Gateway Certificate | Display name for the store type (may be customized) | -| Short Name | AzureAppGw | Short display name for the store type | -| Capability | AzureAppGw | Store type name orchestrator will register with. Check the box to allow entry of value | -| Supported Job Types (check the box for each) | Add, Remove, Discovery, Inventory | Job types the extension supports | -| Needs Server | ✓ | Determines if a target server name is required when creating store | -| Blueprint Allowed | | Determines if store type may be included in an Orchestrator blueprint | -| Uses PowerShell | | Determines if underlying implementation is PowerShell | -| Requires Store Password | | Determines if a store password is required when configuring an individual store. | -| Supports Entry Password | | Determines if an individual entry within a store can have a password. | + * **Manually**: + * [Azure Application Gateway Certificate](docs/azureappgw.md#certificate-store-type-configuration) +3. Install the Azure Application Gateway Universal Orchestrator extension. + + * **Using kfutil**: On the server that that hosts the Universal Orchestrator, run the following command: -The Basic tab should look like this: + ```shell + # Windows Server + kfutil orchestrator extension -e azure-appgateway-orchestrator@latest --out "C:\Program Files\Keyfactor\Keyfactor Orchestrator\extensions" -![AzureAppGw Basic Tab](.github/images/AzureAppGw-basic-store-type-dialog.png) + # Linux + kfutil orchestrator extension -e azure-appgateway-orchestrator@latest --out "/opt/keyfactor/orchestrator/extensions" + ``` + + * **Manually**: Follow the [official Command documentation](https://software.keyfactor.com/Core-OnPrem/Current/Content/InstallingAgents/NetCoreOrchestrator/CustomExtensions.htm?Highlight=extensions) to install the latest [Azure Application Gateway Universal Orchestrator extension](https://github.com/Keyfactor/azure-appgateway-orchestrator/releases/latest). -### Advanced Tab -| Attribute | Value | Description | -| --------- | ----- | ----- | -| Supports Custom Alias | Required | Determines if an individual entry within a store can have a custom Alias. | -| Private Key Handling | Required | This determines if Keyfactor can send the private key associated with a certificate to the store. Required because IIS certificates without private keys would be invalid. | -| PFX Password Style | Default | 'Default' - PFX password is randomly generated, 'Custom' - PFX password may be specified when the enrollment job is created (Requires the Allow Custom Password application setting to be enabled.) | +4. Create new certificate stores in Keyfactor Command for the Sample Universal Orchestrator extension. + * [Azure Application Gateway Certificate](docs/azureappgw.md#certificate-store-configuration) +
+
Azure Application Gateway Certificate Binding -The Advanced tab should look like this: -![AzureAppGw Advanced Tab](.github/images/AzureAppGw-advanced-store-type-dialog.png) +1. Follow the [requirements section](docs/appgwbin.md#requirements) to configure a Service Account and grant necessary API permissions. -### Custom Fields Tab -Custom fields operate at the certificate store level and are used to control how the orchestrator connects to the remote target server containing the certificate store to be managed. The following custom fields should be added to the store type: +
Requirements -| Name | Display Name | Type | Default Value/Options | Required | Description | -| ---- | ------------ | ---- | --------------------- | -------- | ----------- | -| ServerUsername | Server Username | Secret | None | ✓ | Application ID of the service principal, representing the identity used for managing the Application Gateway. | -| ServerPassword | Server Password | Secret | None | ✓ | Secret of the service principal that will be used to manage the Application Gateway. | -| ServerUseSsl | Use SSL | Bool | true | | Indicates whether SSL usage is enabled for the connection. | -| AzureCloud | Azure Global Cloud Authority Host | MultipleChoice | public,china,germany,government | | Specifies the Azure Cloud instance used by the organization. | + ### Azure Service Principal (Azure Resource Manager Authentication) + The Azure Application Gateway Orchestrator extension uses an [Azure Service Principal](https://learn.microsoft.com/en-us/entra/identity-platform/app-objects-and-service-principals?tabs=browser) for authentication. Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/entra/identity-platform/howto-create-service-principal-portal) to create a service principal. -The Custom Fields tab should look like this: + #### Azure Application Gateway permissions -![AzureAppGw Custom Fields Tab](.github/images/AzureAppGw-custom-fields-store-type-dialog.png) + For quick start and non-production environments, a Role Assignment should be created on _each resource group_ that own Application Gateways desiring management that grants the created Application/Service Principal the [Contributor (Privileged administrator) Role](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#contributor). For production environments, a custom role should be created that grants the following permissions: -
+ - `Microsoft.Resources/subscriptions/resourcegroups/read` - Read : Get Resource Group + - `Microsoft.Network/applicationGateways/read` - Read : Get Application Gateway + - `Microsoft.Network/applicationGateways/write` - Write : Create or Update Application Gateway + - `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action` - Other : RBAC action for assigning an existing user assigned identity to a resource + - `Microsoft.Network/virtualNetworks/subnets/join/action` - Other : Joins a virtual network. Not Alertable. -
AppGwBin + > Note that even if the Service Principal has permission to perform the 'Microsoft.Network/applicationGateways/write' action over the scope of the required resource group, there may be other permissions that are required by the CreateOrUpdate operation depending on the complexity of the Application Gateway's configuration. As such, the list of permissions above should not be considered as comprehensive. -Create a store type called `AppGwBin` with the attributes in the tables below: + #### Azure Key Vault permissions -### Basic Tab -| Attribute | Value | Description | -| --------- | ----- | ----- | -| Name | Azure Application Gateway Certificate Binding | Display name for the store type (may be customized) | -| Short Name | AppGwBin | Short display name for the store type | -| Capability | AzureAppGwBin | Store type name orchestrator will register with. Check the box to allow entry of value | -| Supported Job Types (check the box for each) | Add, Discovery | Job types the extension supports | -| Needs Server | ✓ | Determines if a target server name is required when creating store | -| Blueprint Allowed | | Determines if store type may be included in an Orchestrator blueprint | -| Uses PowerShell | | Determines if underlying implementation is PowerShell | -| Requires Store Password | | Determines if a store password is required when configuring an individual store. | -| Supports Entry Password | | Determines if an individual entry within a store can have a password. | + If the managed Application Gateway is integrated with Azure Key Vault per the discussion in the [Certificates Imported to Application Gateways from Azure Key Vault](#certificates-imported-to-application-gateways-from-azure-key-vault) section, perform one of the following actions for each Key Vault with certificates imported to App Gateways: + * **Azure role-based access control** - Create a Role Assignment that grants the Application/Service Principal the [Key Vault Secrets User](https://learn.microsoft.com/en-us/azure/key-vault/general/rbac-guide?tabs=azure-cli) built-in role. + * **Vault access policy** - [Create an Access Policy](https://learn.microsoft.com/en-us/azure/key-vault/general/assign-access-policy?tabs=azure-portal) that grants the Application/Service Principal the Get secret permission for each Azure Key Vault. + #### Client Certificate or Client Secret -The Basic tab should look like this: + Beginning in version 3.0.0, the Azure Application Gateway Orchestrator extension supports both [client certificate authentication](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) and [client secret](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-2-add-a-client-secret) authentication. -![AppGwBin Basic Tab](.github/images/AppGwBin-basic-store-type-dialog.png) + * **Client Secret** - Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-2-add-a-client-secret) to create a Client Secret. This secret will be used as the **Server Password** field in the [Certificate Store Configuration](#certificate-store-configuration) section. + * **Client Certificate** - Create a client certificate key pair with the Client Authentication extended key usage. The client certificate will be used in the ClientCertificate field in the [Certificate Store Configuration](#certificate-store-configuration) section. If you have access to Keyfactor Command, the instructions in this section walk you through enrolling a certificate and ensuring that it's in the correct format. Once enrolled, follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) to add the _public key_ certificate (no private key) to the service principal used for authentication. -### Advanced Tab -| Attribute | Value | Description | -| --------- | ----- | ----- | -| Supports Custom Alias | Required | Determines if an individual entry within a store can have a custom Alias. | -| Private Key Handling | Required | This determines if Keyfactor can send the private key associated with a certificate to the store. Required because IIS certificates without private keys would be invalid. | -| PFX Password Style | Default | 'Default' - PFX password is randomly generated, 'Custom' - PFX password may be specified when the enrollment job is created (Requires the Allow Custom Password application setting to be enabled.) | + The certificate can be in either of the following formats: + * Base64-encoded PKCS#12 (PFX) with a matching private key. + * Base64-encoded PEM-encoded certificate _and_ PEM-encoded PKCS8 private key. Make sure that the certificate and private key are separated with a newline. The order doesn't matter - the extension will determine which is which. + If the private key is encrypted, the encryption password will replace the **Server Password** field in the [Certificate Store Configuration](#certificate-store-configuration) section. -The Advanced tab should look like this: + > **Creating and Formatting a Client Certificate using Keyfactor Command** + > + > To get started quickly, you can follow the instructions below to create and properly format a client certificate to authenticate to the Microsoft Graph API. + > + > 1. In Keyfactor Command, hover over **Enrollment** and select **PFX Enrollment**. + > 2. Select a **Template** that supports Client Authentication as an extended key usage. + > 3. Populate the certificate subject as appropriate for the Template. It may be sufficient to only populate the Common Name, but consult your IT policy to ensure that this certificate is compliant. + > 4. At the bottom of the page, uncheck the box for **Include Chain**, and select either **PFX** or **PEM** as the certificate Format. + > 5. Make a note of the password on the next page - it won't be shown again. + > 6. Prepare the certificate and private key for Azure and the Orchestrator extension: + > * If you downloaded the certificate in PEM format, use the commands below: + > + > ```shell + > # Verify that the certificate downloaded from Command contains the certificate and private key. They should be in the same file + > cat + > + > # Separate the certificate from the private key + > openssl x509 -in -out pubkeycert.pem + > + > # Base64 encode the certificate and private key + > cat | base64 > clientcertkeypair.pem.base64 + > ``` + > + > * If you downloaded the certificate in PFX format, use the commands below: + > + > ```shell + > # Export the certificate from the PFX file + > openssl pkcs12 -in -clcerts -nokeys -out pubkeycert.pem + > + > # Base64 encode the PFX file + > cat | base64 > clientcert.pfx.base64 + > ``` + > 7. Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) to add the public key certificate to the service principal used for authentication. + > + > You will use `clientcert.[pem|pfx].base64` as the **ClientCertificate** field in the [Certificate Store Configuration](#certificate-store-configuration) section. -![AppGwBin Advanced Tab](.github/images/AppGwBin-advanced-store-type-dialog.png) -### Custom Fields Tab -Custom fields operate at the certificate store level and are used to control how the orchestrator connects to the remote target server containing the certificate store to be managed. The following custom fields should be added to the store type: -| Name | Display Name | Type | Default Value/Options | Required | Description | -| ---- | ------------ | ---- | --------------------- | -------- | ----------- | -| ServerUsername | Server Username | Secret | None | | Application ID of the service principal, representing the identity used for managing the Application Gateway. | -| ServerPassword | Server Password | Secret | None | | Secret of the service principal that will be used to manage the Application Gateway. | -| ServerUseSsl | Use SSL | Bool | true | ✓ | Indicates whether SSL usage is enabled for the connection. | -| AzureCloud | Azure Global Cloud Authority Host | MultipleChoice | public,china,germany,government | | Specifies the Azure Cloud instance used by the organization. | +
+2. Create Certificate Store Types for the Azure Application Gateway Orchestrator extension. -The Custom Fields tab should look like this: + * **Using kfutil**: -![AppGwBin Custom Fields Tab](.github/images/AppGwBin-custom-fields-store-type-dialog.png) + ```shell + # Azure Application Gateway Certificate Binding + kfutil store-types create AppGwBin + ``` -
+ * **Manually**: + * [Azure Application Gateway Certificate Binding](docs/appgwbin.md#certificate-store-type-configuration) -## Instantiating New Azure Application Gateway Orchestrator Stores -Once the store types have been created, you can instantiate certificate stores for any of the 2 store types. This section describes how to instantiate a certificate store for each store type. Creating new certificate stores is how certificates in the remote platform are inventoried and managed by the orchestrator. -
AzureAppGw +3. Install the Azure Application Gateway Universal Orchestrator extension. + + * **Using kfutil**: On the server that that hosts the Universal Orchestrator, run the following command: -In Keyfactor Command, navigate to Certificate Stores from the Locations Menu. Click the Add button to create a new Certificate Store using the settings defined below. + ```shell + # Windows Server + kfutil orchestrator extension -e azure-appgateway-orchestrator@latest --out "C:\Program Files\Keyfactor\Keyfactor Orchestrator\extensions" -| Attribute | Description | -| --------- | ----------- | -| Category | Select Azure Application Gateway Certificate or the customized certificate store name from the previous step. | -| Container | Optional container to associate certificate store with. | -| Client Machine | The Azure Tenant ID of the service principal, representing the Tenant ID where the Application/Service Principal is managed. | -| Store Path | Azure resource ID of the application gateway, following the format: `/subscriptions//resourceGroups//providers/Microsoft.Network/applicationGateways/`. | -| Orchestrator | Select an approved orchestrator capable of managing AzureAppGw certificates. Specifically, one with the AzureAppGw capability. | -| Server Username | Application ID of the service principal, representing the identity used for managing the Application Gateway. | -| Server Password | Secret of the service principal that will be used to manage the Application Gateway. | -| Use SSL | Indicates whether SSL usage is enabled for the connection. | -| Azure Global Cloud Authority Host | Specifies the Azure Cloud instance used by the organization. | + # Linux + kfutil orchestrator extension -e azure-appgateway-orchestrator@latest --out "/opt/keyfactor/orchestrator/extensions" + ``` + * **Manually**: Follow the [official Command documentation](https://software.keyfactor.com/Core-OnPrem/Current/Content/InstallingAgents/NetCoreOrchestrator/CustomExtensions.htm?Highlight=extensions) to install the latest [Azure Application Gateway Universal Orchestrator extension](https://github.com/Keyfactor/azure-appgateway-orchestrator/releases/latest). +4. Create new certificate stores in Keyfactor Command for the Sample Universal Orchestrator extension. + * [Azure Application Gateway Certificate Binding](docs/appgwbin.md#certificate-store-configuration)
-
AppGwBin -In Keyfactor Command, navigate to Certificate Stores from the Locations Menu. Click the Add button to create a new Certificate Store using the settings defined below. +## License -| Attribute | Description | -| --------- | ----------- | -| Category | Select Azure Application Gateway Certificate Binding or the customized certificate store name from the previous step. | -| Container | Optional container to associate certificate store with. | -| Client Machine | The Azure Tenant ID of the service principal, representing the Tenant ID where the Application/Service Principal is managed. | -| Store Path | Azure resource ID of the application gateway, following the format: `/subscriptions//resourceGroups//providers/Microsoft.Network/applicationGateways/`. | -| Orchestrator | Select an approved orchestrator capable of managing AppGwBin certificates. Specifically, one with the AzureAppGwBin capability. | -| Server Username | Application ID of the service principal, representing the identity used for managing the Application Gateway. | -| Server Password | Secret of the service principal that will be used to manage the Application Gateway. | -| Use SSL | Indicates whether SSL usage is enabled for the connection. | -| Azure Global Cloud Authority Host | Specifies the Azure Cloud instance used by the organization. | +Apache License 2.0, see [LICENSE](LICENSE). +## Related Integrations -
+See all [Keyfactor Universal Orchestrator extensions](https://github.com/orgs/Keyfactor/repositories?q=orchestrator). When creating cert store type manually, that store property names and entry parameter names are case sensitive diff --git a/docs/appgwbin.md b/docs/appgwbin.md new file mode 100644 index 0000000..6f51835 --- /dev/null +++ b/docs/appgwbin.md @@ -0,0 +1,229 @@ +## Azure Application Gateway Certificate Binding + +The Azure Application Gateway Certificate Binding store type, `AzureAppGwBin`, represents certificates bound to TLS Listeners on Azure App Gateways. The only supported operations on this store type are Management Add and Inventory. The Management Add operation for this store type creates and binds an ApplicationGatewaySslCertificate to a pre-existing TLS Listener on an Application Gateway. When the Add operation is configured in Keyfactor Command, the certificate Alias configures which TLS Listener the certificate will be bound to. If the HTTPS listener is already bound to a certificate with the same name, the Management Add operation will perform a replacement of the certificate, _**regardless of the existence of the Replace flag configured with renewal jobs**_. The replacement operation performs several API interactions with Azure since at least one certificate must be bound to a TLS listener at all times, and the name of ApplicationGatewaySslCertificates must be unique. For the sake of completeness, the following describes the mechanics of this replacement operation: + +1. Determine the name of the certificate currently bound to the HTTPS listener - Alias in 100% of cases if the certificate was originally added by the App Gateway Orchestrator Extension, or something else if the certificate was added by some other means (IE, the Azure Portal, or some other API client). +2. Create and bind a temporary certificate to the HTTPS listener with the same name as the Alias. +3. Delete the AppGatewayCertificate previously bound to the HTTPS listener called Alias. +4. Recreate and bind an AppGatewayCertificate with the same name as the HTTPS listener called Alias. If the Alias is called `listener1`, the new certificate will be called `listener1`, regardless of the name of the certificate that was previously bound to the listener. +5. Delete the temporary certificate. + +In the unlikely event that a failure occurs at any point in the replacement procedure, it's expected that the correct certificate will be served by the TLS Listener, since most of the mechanics are actually implemented to resolve the unique naming requirement. + +The Inventory job type for `AzureAppGwBin` reports only ApplicationGatewaySslCertificates that are bound to TLS Listeners. If the certificate was added with Keyfactor Command and this orchestrator extension, the name of the certificate in the Application Gateway will be the same as the TLS Listener. E.g., if the Alias configured in Command corresponds to a TLS Listener called `location-service-https-lstn1`, the certificate in the Application Gateway will also be called `location-service-https-lstn1`. However, if the certificate was added to the Application Gateway by other means (such as the Azure CLI, import from AKV, etc.), the Inventory job mechanics will still report the name of the TLS Listener in its report back to Command. + + + +### Supported Job Types + +| Job Name | Supported | +| -------- | --------- | +| Inventory | ✅ | +| Management Add | ✅ | +| Management Remove | | +| Discovery | ✅ | +| Create | | +| Reenrollment | | + +## Requirements + +### Azure Service Principal (Azure Resource Manager Authentication) + +The Azure Application Gateway Orchestrator extension uses an [Azure Service Principal](https://learn.microsoft.com/en-us/entra/identity-platform/app-objects-and-service-principals?tabs=browser) for authentication. Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/entra/identity-platform/howto-create-service-principal-portal) to create a service principal. + +#### Azure Application Gateway permissions + +For quick start and non-production environments, a Role Assignment should be created on _each resource group_ that own Application Gateways desiring management that grants the created Application/Service Principal the [Contributor (Privileged administrator) Role](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#contributor). For production environments, a custom role should be created that grants the following permissions: + +- `Microsoft.Resources/subscriptions/resourcegroups/read` - Read : Get Resource Group +- `Microsoft.Network/applicationGateways/read` - Read : Get Application Gateway +- `Microsoft.Network/applicationGateways/write` - Write : Create or Update Application Gateway +- `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action` - Other : RBAC action for assigning an existing user assigned identity to a resource +- `Microsoft.Network/virtualNetworks/subnets/join/action` - Other : Joins a virtual network. Not Alertable. + +> Note that even if the Service Principal has permission to perform the 'Microsoft.Network/applicationGateways/write' action over the scope of the required resource group, there may be other permissions that are required by the CreateOrUpdate operation depending on the complexity of the Application Gateway's configuration. As such, the list of permissions above should not be considered as comprehensive. + +#### Azure Key Vault permissions + +If the managed Application Gateway is integrated with Azure Key Vault per the discussion in the [Certificates Imported to Application Gateways from Azure Key Vault](#certificates-imported-to-application-gateways-from-azure-key-vault) section, perform one of the following actions for each Key Vault with certificates imported to App Gateways: +* **Azure role-based access control** - Create a Role Assignment that grants the Application/Service Principal the [Key Vault Secrets User](https://learn.microsoft.com/en-us/azure/key-vault/general/rbac-guide?tabs=azure-cli) built-in role. +* **Vault access policy** - [Create an Access Policy](https://learn.microsoft.com/en-us/azure/key-vault/general/assign-access-policy?tabs=azure-portal) that grants the Application/Service Principal the Get secret permission for each Azure Key Vault. + +#### Client Certificate or Client Secret + +Beginning in version 3.0.0, the Azure Application Gateway Orchestrator extension supports both [client certificate authentication](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) and [client secret](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-2-add-a-client-secret) authentication. + +* **Client Secret** - Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-2-add-a-client-secret) to create a Client Secret. This secret will be used as the **Server Password** field in the [Certificate Store Configuration](#certificate-store-configuration) section. +* **Client Certificate** - Create a client certificate key pair with the Client Authentication extended key usage. The client certificate will be used in the ClientCertificate field in the [Certificate Store Configuration](#certificate-store-configuration) section. If you have access to Keyfactor Command, the instructions in this section walk you through enrolling a certificate and ensuring that it's in the correct format. Once enrolled, follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) to add the _public key_ certificate (no private key) to the service principal used for authentication. + + The certificate can be in either of the following formats: + * Base64-encoded PKCS#12 (PFX) with a matching private key. + * Base64-encoded PEM-encoded certificate _and_ PEM-encoded PKCS8 private key. Make sure that the certificate and private key are separated with a newline. The order doesn't matter - the extension will determine which is which. + + If the private key is encrypted, the encryption password will replace the **Server Password** field in the [Certificate Store Configuration](#certificate-store-configuration) section. + +> **Creating and Formatting a Client Certificate using Keyfactor Command** +> +> To get started quickly, you can follow the instructions below to create and properly format a client certificate to authenticate to the Microsoft Graph API. +> +> 1. In Keyfactor Command, hover over **Enrollment** and select **PFX Enrollment**. +> 2. Select a **Template** that supports Client Authentication as an extended key usage. +> 3. Populate the certificate subject as appropriate for the Template. It may be sufficient to only populate the Common Name, but consult your IT policy to ensure that this certificate is compliant. +> 4. At the bottom of the page, uncheck the box for **Include Chain**, and select either **PFX** or **PEM** as the certificate Format. +> 5. Make a note of the password on the next page - it won't be shown again. +> 6. Prepare the certificate and private key for Azure and the Orchestrator extension: +> * If you downloaded the certificate in PEM format, use the commands below: +> +> ```shell +> # Verify that the certificate downloaded from Command contains the certificate and private key. They should be in the same file +> cat +> +> # Separate the certificate from the private key +> openssl x509 -in -out pubkeycert.pem +> +> # Base64 encode the certificate and private key +> cat | base64 > clientcertkeypair.pem.base64 +> ``` +> +> * If you downloaded the certificate in PFX format, use the commands below: +> +> ```shell +> # Export the certificate from the PFX file +> openssl pkcs12 -in -clcerts -nokeys -out pubkeycert.pem +> +> # Base64 encode the PFX file +> cat | base64 > clientcert.pfx.base64 +> ``` +> 7. Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) to add the public key certificate to the service principal used for authentication. +> +> You will use `clientcert.[pem|pfx].base64` as the **ClientCertificate** field in the [Certificate Store Configuration](#certificate-store-configuration) section. + + + +## Extension Mechanics + +### Discovery Job + +The Discovery operation discovers all Azure Application Gateways in each resource group that the service principal has access to. The discovered Application Gateways are reported back to Command and can be easily added as certificate stores from the Locations tab. + +The Discovery operation uses the "Directories to search" field, and accepts input in one of the following formats: +- `*` - If the asterisk symbol `*` is used, the extension will search for Application Gateways in every resource group that the service principal has access to, but only in the tenant that the discovery job was configured for as specified by the "Client Machine" field in the certificate store configuration. +- `,,...` - If a comma-separated list of tenant IDs is used, the extension will search for Application Gateways in every resource group and tenant specified in the list. The tenant IDs should be the GUIDs associated with each tenant, and it's the user's responsibility to ensure that the service principal has access to the specified tenants. + +> The Discovery Job only supports Client Secret authentication. + +### Certificates Imported to Application Gateways from Azure Key Vault + +Natively, Azure Application Gateways support integration with Azure Key Vault for secret/certificate management. This integration works by creating a TLS Listener certificate with a reference to a secret in Azure Key Vault (specifically, a URI in the format `https://.vault.azure.net/secrets/`), authenticated using a Managed Identity. If the Application Gateway orchestrator extension is deployed to manage App Gateways with certificates imported from Azure Key Vault, the following truth table represents the possible operations and their result, specifically with respect to AKV. + +| Store Type | Operation | Result | +|--------------|-----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `AzureAppGw` | Inventory | Certificate is downloaded from Azure Key Vault and reported back to Keyfactor Command. In Keyfactor Command, the certificate will show as being located in the AzureAppGw certificate store [in addition to the AKV, if AKV orchestrator extension is also deployed]. | +| `AzureAppGw` | Add | The Add operation will not create secrets in AKV; it creates ApplicationGatewaySslCertificates.

If an `AzureAppGw` Add operation is scheduled with the Replace flag, the _**link to the AKV certificate will be broken**_, and a native ApplicationGatewaySslCertificate will be created in its place - The secret in AKV will still exist. | +| `AzureAppGw` | Remove | The ApplicationGatewaySslCertificate is deleted from the Application Gateway, but the secret that the certificate referenced in AKV still exists. | +| `AzureAppGwBin` | Inventory | Certificate is downloaded from Azure Key Vault and reported back to Keyfactor Command. In Keyfactor Command, the certificate will show as present in both an `AzureAppGw` certificate store _and_ an `AppGwBin` certificate store [in addition to the AKV, if AKV orchestrator extension is also deployed]. | +| `AzureAppGwBin` | Add | The Add operation will not create secrets in AKV; it creates ApplicationGatewaySslCertificates.

If a certificate with the same name as the TLS Listener already exists, it will be _replaced_ by a new ApplicationGatewaySslCertificate.

If the certificate being replaced was imported from AKV, this binding will be broken and the secret will still exist in AKV. | + +#### Mechanics of the Azure Key Vault Download Operation for Inventory Jobs that report certificates imported from AKV + +If an AzureApplicationSslCertificate references a secret in AKV (was imported to the App Gateway from AKV), the inventory job will create and use a `SecretClient` from the [`Azure.Security.KeyVault.Secrets.SecretClient` dotnet package](https://learn.microsoft.com/en-us/dotnet/api/azure.security.keyvault.secrets.secretclient?view=azure-dotnet). Authentication to AKV via this client is configured using the exact same `TokenCredential` provided by the [Azure Identity client library for .NET](https://learn.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme?view=azure-dotnet). This means that the Service Principal described in the [Azure Configuration](#azure-configuration) section must also have appropriate permissions to read secrets from the AKV that the App Gateway is integrated with. The secret referenced in the AzureApplicationSslCertificate will be accessed exactly as reported by Azure, regardless of whether it exists in AKV. + + + +## Certificate Store Type Configuration + +The recommended method for creating the `AppGwBin` Certificate Store Type is to use [kfutil](https://github.com/Keyfactor/kfutil). After installing, use the following command to create the `` Certificate Store Type: + +```shell +kfutil store-types create AppGwBin +``` + +
AppGwBin + +Create a store type called `AppGwBin` with the attributes in the tables below: + +### Basic Tab +| Attribute | Value | Description | +| --------- | ----- | ----- | +| Name | Azure Application Gateway Certificate Binding | Display name for the store type (may be customized) | +| Short Name | AppGwBin | Short display name for the store type | +| Capability | AzureAppGwBin | Store type name orchestrator will register with. Check the box to allow entry of value | +| Supported Job Types (check the box for each) | Add, Discovery, Remove | Job types the extension supports | +| Supports Add | ✅ | Check the box. Indicates that the Store Type supports Management Add | +| Supports Remove | | Indicates that the Store Type supports Management Remove | +| Supports Discovery | ✅ | Check the box. Indicates that the Store Type supports Discovery | +| Supports Reenrollment | | Indicates that the Store Type supports Reenrollment | +| Supports Create | | Indicates that the Store Type supports store creation | +| Needs Server | ✅ | Determines if a target server name is required when creating store | +| Blueprint Allowed | | Determines if store type may be included in an Orchestrator blueprint | +| Uses PowerShell | | Determines if underlying implementation is PowerShell | +| Requires Store Password | | Determines if a store password is required when configuring an individual store. | +| Supports Entry Password | | Determines if an individual entry within a store can have a password. | + +The Basic tab should look like this: + +![AppGwBin Basic Tab](../docsource/images/AppGwBin-basic-store-type-dialog.png) + +### Advanced Tab +| Attribute | Value | Description | +| --------- | ----- | ----- | +| Supports Custom Alias | Required | Determines if an individual entry within a store can have a custom Alias. | +| Private Key Handling | Required | This determines if Keyfactor can send the private key associated with a certificate to the store. Required because IIS certificates without private keys would be invalid. | +| PFX Password Style | Default | 'Default' - PFX password is randomly generated, 'Custom' - PFX password may be specified when the enrollment job is created (Requires the Allow Custom Password application setting to be enabled.) | + +The Advanced tab should look like this: + +![AppGwBin Advanced Tab](../docsource/images/AppGwBin-advanced-store-type-dialog.png) + +### Custom Fields Tab +Custom fields operate at the certificate store level and are used to control how the orchestrator connects to the remote target server containing the certificate store to be managed. The following custom fields should be added to the store type: + +| Name | Display Name | Type | Default Value/Options | Required | Description | +| ---- | ------------ | ---- | --------------------- | -------- | ----------- | +| ServerUsername | Server Username | Secret | | | Application ID of the service principal, representing the identity used for managing the Application Gateway. | +| ServerPassword | Server Password | Secret | | | A Client Secret that the extension will use to authenticate with the Azure Resource Management API for managing Application Gateway certificates, OR the password that encrypts the private key in ClientCertificate | +| ClientCertificate | Client Certificate | Secret | | | The client certificate used to authenticate with Azure Resource Management API for managing Application Gateway certificates. See the [requirements](#client-certificate-or-client-secret) for more information. | +| AzureCloud | Azure Global Cloud Authority Host | MultipleChoice | public,china,germany,government | | Specifies the Azure Cloud instance used by the organization. | +| ServerUseSsl | Use SSL | Bool | true | ✅ | Specifies whether SSL should be used for communication with the server. Set to 'true' to enable SSL, and 'false' to disable it. | + + +The Custom Fields tab should look like this: + +![AppGwBin Custom Fields Tab](../docsource/images/AppGwBin-custom-fields-store-type-dialog.png) + + + +
+ +## Certificate Store Configuration + +After creating the `AppGwBin` Certificate Store Type and installing the Azure Application Gateway Universal Orchestrator extension, you can create new [Certificate Stores](https://software.keyfactor.com/Core-OnPrem/Current/Content/ReferenceGuide/Certificate%20Stores.htm?Highlight=certificate%20store) to manage certificates in the remote platform. + +The following table describes the required and optional fields for the `AppGwBin` certificate store type. + +| Attribute | Description | +| --------- | ----------- | +| Category | Select "Azure Application Gateway Certificate Binding" or the customized certificate store name from the previous step. | +| Container | Optional container to associate certificate store with. | +| Client Machine | The Azure Tenant (directory) ID that owns the Service Principal. | +| Store Path | Azure resource ID of the application gateway, following the format: /subscriptions//resourceGroups//providers/Microsoft.Network/applicationGateways/. | +| Orchestrator | Select an approved orchestrator capable of managing `AppGwBin` certificates. Specifically, one with the `AzureAppGwBin` capability. | +| ServerUsername | Application ID of the service principal, representing the identity used for managing the Application Gateway. | +| ServerPassword | A Client Secret that the extension will use to authenticate with the Azure Resource Management API for managing Application Gateway certificates, OR the password that encrypts the private key in ClientCertificate | +| ClientCertificate | The client certificate used to authenticate with Azure Resource Management API for managing Application Gateway certificates. See the [requirements](#client-certificate-or-client-secret) for more information. | +| AzureCloud | Specifies the Azure Cloud instance used by the organization. | +| ServerUseSsl | Specifies whether SSL should be used for communication with the server. Set to 'true' to enable SSL, and 'false' to disable it. | + +* **Using kfutil** + + ```shell + # Generate a CSV template for the AzureApp certificate store + kfutil stores import generate-template --store-type-name AppGwBin --outpath AppGwBin.csv + + # Open the CSV file and fill in the required fields for each certificate store. + + # Import the CSV file to create the certificate stores + kfutil stores import csv --store-type-name AppGwBin --file AppGwBin.csv + ``` + +* **Manually with the Command UI**: In Keyfactor Command, navigate to Certificate Stores from the Locations Menu. Click the Add button to create a new Certificate Store using the attributes in the table above. \ No newline at end of file diff --git a/docs/azureappgw.md b/docs/azureappgw.md new file mode 100644 index 0000000..be302c1 --- /dev/null +++ b/docs/azureappgw.md @@ -0,0 +1,225 @@ +## Azure Application Gateway Certificate + +The Azure Application Gateway Certificate store type, `AzureAppGw`, manages `ApplicationGatewaySslCertificate` objects owned by Azure Application Gateways. This store type collects inventory and manages all ApplicationGatewaySslCertificate objects associated with an Application Gateway. The store type is implemented primarily for Inventory and Management Remove operations, since the intended usage of ApplicationGatewaySslCertificates in Application Gateways is for serving TLS client traffic via TLS Listeners. Management Add and associated logic for certificate renewal is also supported for this certificate store type for completeness, but the primary intended functionality of this extension is implemented with the App Gateway Certificate Binding store type. + +> If an ApplicationGatewaySslCertificate is bound to a TLS Listener at the time of a Management Remove operation, the operation will fail since at least one certificate must be bound at all times. + +> If a renewal job is scheduled for an `AzureAppGw` certificate store, the extension will report a success and perform no action if the certificate being renewed is bound to a TLS Listener. This is because a certificate located in an `AzureAppGw` certificate store that is bound to a TLS Listener is logically the same as the same certificate located in an `AzureAppGwBin` store type. For this reason, it's expected that the certificate will be renewed and re-bound to the listener by the `AppGwBin` certificate operations. +> +> If the renewed certificate is not bound to a TLS Listener, the operation will be performed the same as any certificate renewal process that honors the Overwrite flag. + + + +### Supported Job Types + +| Job Name | Supported | +| -------- | --------- | +| Inventory | ✅ | +| Management Add | ✅ | +| Management Remove | ✅ | +| Discovery | ✅ | +| Create | | +| Reenrollment | | + +## Requirements + +### Azure Service Principal (Azure Resource Manager Authentication) + +The Azure Application Gateway Orchestrator extension uses an [Azure Service Principal](https://learn.microsoft.com/en-us/entra/identity-platform/app-objects-and-service-principals?tabs=browser) for authentication. Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/entra/identity-platform/howto-create-service-principal-portal) to create a service principal. + +#### Azure Application Gateway permissions + +For quick start and non-production environments, a Role Assignment should be created on _each resource group_ that own Application Gateways desiring management that grants the created Application/Service Principal the [Contributor (Privileged administrator) Role](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#contributor). For production environments, a custom role should be created that grants the following permissions: + +- `Microsoft.Resources/subscriptions/resourcegroups/read` - Read : Get Resource Group +- `Microsoft.Network/applicationGateways/read` - Read : Get Application Gateway +- `Microsoft.Network/applicationGateways/write` - Write : Create or Update Application Gateway +- `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action` - Other : RBAC action for assigning an existing user assigned identity to a resource +- `Microsoft.Network/virtualNetworks/subnets/join/action` - Other : Joins a virtual network. Not Alertable. + +> Note that even if the Service Principal has permission to perform the 'Microsoft.Network/applicationGateways/write' action over the scope of the required resource group, there may be other permissions that are required by the CreateOrUpdate operation depending on the complexity of the Application Gateway's configuration. As such, the list of permissions above should not be considered as comprehensive. + +#### Azure Key Vault permissions + +If the managed Application Gateway is integrated with Azure Key Vault per the discussion in the [Certificates Imported to Application Gateways from Azure Key Vault](#certificates-imported-to-application-gateways-from-azure-key-vault) section, perform one of the following actions for each Key Vault with certificates imported to App Gateways: +* **Azure role-based access control** - Create a Role Assignment that grants the Application/Service Principal the [Key Vault Secrets User](https://learn.microsoft.com/en-us/azure/key-vault/general/rbac-guide?tabs=azure-cli) built-in role. +* **Vault access policy** - [Create an Access Policy](https://learn.microsoft.com/en-us/azure/key-vault/general/assign-access-policy?tabs=azure-portal) that grants the Application/Service Principal the Get secret permission for each Azure Key Vault. + +#### Client Certificate or Client Secret + +Beginning in version 3.0.0, the Azure Application Gateway Orchestrator extension supports both [client certificate authentication](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) and [client secret](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-2-add-a-client-secret) authentication. + +* **Client Secret** - Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-2-add-a-client-secret) to create a Client Secret. This secret will be used as the **Server Password** field in the [Certificate Store Configuration](#certificate-store-configuration) section. +* **Client Certificate** - Create a client certificate key pair with the Client Authentication extended key usage. The client certificate will be used in the ClientCertificate field in the [Certificate Store Configuration](#certificate-store-configuration) section. If you have access to Keyfactor Command, the instructions in this section walk you through enrolling a certificate and ensuring that it's in the correct format. Once enrolled, follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) to add the _public key_ certificate (no private key) to the service principal used for authentication. + + The certificate can be in either of the following formats: + * Base64-encoded PKCS#12 (PFX) with a matching private key. + * Base64-encoded PEM-encoded certificate _and_ PEM-encoded PKCS8 private key. Make sure that the certificate and private key are separated with a newline. The order doesn't matter - the extension will determine which is which. + + If the private key is encrypted, the encryption password will replace the **Server Password** field in the [Certificate Store Configuration](#certificate-store-configuration) section. + +> **Creating and Formatting a Client Certificate using Keyfactor Command** +> +> To get started quickly, you can follow the instructions below to create and properly format a client certificate to authenticate to the Microsoft Graph API. +> +> 1. In Keyfactor Command, hover over **Enrollment** and select **PFX Enrollment**. +> 2. Select a **Template** that supports Client Authentication as an extended key usage. +> 3. Populate the certificate subject as appropriate for the Template. It may be sufficient to only populate the Common Name, but consult your IT policy to ensure that this certificate is compliant. +> 4. At the bottom of the page, uncheck the box for **Include Chain**, and select either **PFX** or **PEM** as the certificate Format. +> 5. Make a note of the password on the next page - it won't be shown again. +> 6. Prepare the certificate and private key for Azure and the Orchestrator extension: +> * If you downloaded the certificate in PEM format, use the commands below: +> +> ```shell +> # Verify that the certificate downloaded from Command contains the certificate and private key. They should be in the same file +> cat +> +> # Separate the certificate from the private key +> openssl x509 -in -out pubkeycert.pem +> +> # Base64 encode the certificate and private key +> cat | base64 > clientcertkeypair.pem.base64 +> ``` +> +> * If you downloaded the certificate in PFX format, use the commands below: +> +> ```shell +> # Export the certificate from the PFX file +> openssl pkcs12 -in -clcerts -nokeys -out pubkeycert.pem +> +> # Base64 encode the PFX file +> cat | base64 > clientcert.pfx.base64 +> ``` +> 7. Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) to add the public key certificate to the service principal used for authentication. +> +> You will use `clientcert.[pem|pfx].base64` as the **ClientCertificate** field in the [Certificate Store Configuration](#certificate-store-configuration) section. + + + +## Extension Mechanics + +### Discovery Job + +The Discovery operation discovers all Azure Application Gateways in each resource group that the service principal has access to. The discovered Application Gateways are reported back to Command and can be easily added as certificate stores from the Locations tab. + +The Discovery operation uses the "Directories to search" field, and accepts input in one of the following formats: +- `*` - If the asterisk symbol `*` is used, the extension will search for Application Gateways in every resource group that the service principal has access to, but only in the tenant that the discovery job was configured for as specified by the "Client Machine" field in the certificate store configuration. +- `,,...` - If a comma-separated list of tenant IDs is used, the extension will search for Application Gateways in every resource group and tenant specified in the list. The tenant IDs should be the GUIDs associated with each tenant, and it's the user's responsibility to ensure that the service principal has access to the specified tenants. + +> The Discovery Job only supports Client Secret authentication. + +### Certificates Imported to Application Gateways from Azure Key Vault + +Natively, Azure Application Gateways support integration with Azure Key Vault for secret/certificate management. This integration works by creating a TLS Listener certificate with a reference to a secret in Azure Key Vault (specifically, a URI in the format `https://.vault.azure.net/secrets/`), authenticated using a Managed Identity. If the Application Gateway orchestrator extension is deployed to manage App Gateways with certificates imported from Azure Key Vault, the following truth table represents the possible operations and their result, specifically with respect to AKV. + +| Store Type | Operation | Result | +|--------------|-----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `AzureAppGw` | Inventory | Certificate is downloaded from Azure Key Vault and reported back to Keyfactor Command. In Keyfactor Command, the certificate will show as being located in the AzureAppGw certificate store [in addition to the AKV, if AKV orchestrator extension is also deployed]. | +| `AzureAppGw` | Add | The Add operation will not create secrets in AKV; it creates ApplicationGatewaySslCertificates.

If an `AzureAppGw` Add operation is scheduled with the Replace flag, the _**link to the AKV certificate will be broken**_, and a native ApplicationGatewaySslCertificate will be created in its place - The secret in AKV will still exist. | +| `AzureAppGw` | Remove | The ApplicationGatewaySslCertificate is deleted from the Application Gateway, but the secret that the certificate referenced in AKV still exists. | +| `AzureAppGwBin` | Inventory | Certificate is downloaded from Azure Key Vault and reported back to Keyfactor Command. In Keyfactor Command, the certificate will show as present in both an `AzureAppGw` certificate store _and_ an `AppGwBin` certificate store [in addition to the AKV, if AKV orchestrator extension is also deployed]. | +| `AzureAppGwBin` | Add | The Add operation will not create secrets in AKV; it creates ApplicationGatewaySslCertificates.

If a certificate with the same name as the TLS Listener already exists, it will be _replaced_ by a new ApplicationGatewaySslCertificate.

If the certificate being replaced was imported from AKV, this binding will be broken and the secret will still exist in AKV. | + +#### Mechanics of the Azure Key Vault Download Operation for Inventory Jobs that report certificates imported from AKV + +If an AzureApplicationSslCertificate references a secret in AKV (was imported to the App Gateway from AKV), the inventory job will create and use a `SecretClient` from the [`Azure.Security.KeyVault.Secrets.SecretClient` dotnet package](https://learn.microsoft.com/en-us/dotnet/api/azure.security.keyvault.secrets.secretclient?view=azure-dotnet). Authentication to AKV via this client is configured using the exact same `TokenCredential` provided by the [Azure Identity client library for .NET](https://learn.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme?view=azure-dotnet). This means that the Service Principal described in the [Azure Configuration](#azure-configuration) section must also have appropriate permissions to read secrets from the AKV that the App Gateway is integrated with. The secret referenced in the AzureApplicationSslCertificate will be accessed exactly as reported by Azure, regardless of whether it exists in AKV. + + + +## Certificate Store Type Configuration + +The recommended method for creating the `AzureAppGw` Certificate Store Type is to use [kfutil](https://github.com/Keyfactor/kfutil). After installing, use the following command to create the `` Certificate Store Type: + +```shell +kfutil store-types create AzureAppGw +``` + +
AzureAppGw + +Create a store type called `AzureAppGw` with the attributes in the tables below: + +### Basic Tab +| Attribute | Value | Description | +| --------- | ----- | ----- | +| Name | Azure Application Gateway Certificate | Display name for the store type (may be customized) | +| Short Name | AzureAppGw | Short display name for the store type | +| Capability | AzureAppGw | Store type name orchestrator will register with. Check the box to allow entry of value | +| Supported Job Types (check the box for each) | Add, Discovery, Remove | Job types the extension supports | +| Supports Add | ✅ | Check the box. Indicates that the Store Type supports Management Add | +| Supports Remove | ✅ | Check the box. Indicates that the Store Type supports Management Remove | +| Supports Discovery | ✅ | Check the box. Indicates that the Store Type supports Discovery | +| Supports Reenrollment | | Indicates that the Store Type supports Reenrollment | +| Supports Create | | Indicates that the Store Type supports store creation | +| Needs Server | ✅ | Determines if a target server name is required when creating store | +| Blueprint Allowed | | Determines if store type may be included in an Orchestrator blueprint | +| Uses PowerShell | | Determines if underlying implementation is PowerShell | +| Requires Store Password | | Determines if a store password is required when configuring an individual store. | +| Supports Entry Password | | Determines if an individual entry within a store can have a password. | + +The Basic tab should look like this: + +![AzureAppGw Basic Tab](../docsource/images/AzureAppGw-basic-store-type-dialog.png) + +### Advanced Tab +| Attribute | Value | Description | +| --------- | ----- | ----- | +| Supports Custom Alias | Required | Determines if an individual entry within a store can have a custom Alias. | +| Private Key Handling | Required | This determines if Keyfactor can send the private key associated with a certificate to the store. Required because IIS certificates without private keys would be invalid. | +| PFX Password Style | Default | 'Default' - PFX password is randomly generated, 'Custom' - PFX password may be specified when the enrollment job is created (Requires the Allow Custom Password application setting to be enabled.) | + +The Advanced tab should look like this: + +![AzureAppGw Advanced Tab](../docsource/images/AzureAppGw-advanced-store-type-dialog.png) + +### Custom Fields Tab +Custom fields operate at the certificate store level and are used to control how the orchestrator connects to the remote target server containing the certificate store to be managed. The following custom fields should be added to the store type: + +| Name | Display Name | Type | Default Value/Options | Required | Description | +| ---- | ------------ | ---- | --------------------- | -------- | ----------- | +| ServerUsername | Server Username | Secret | | | Application ID of the service principal, representing the identity used for managing the Application Gateway. | +| ServerPassword | Server Password | Secret | | | A Client Secret that the extension will use to authenticate with the Azure Resource Management API for managing Application Gateway certificates, OR the password that encrypts the private key in ClientCertificate | +| ClientCertificate | Client Certificate | Secret | | | The client certificate used to authenticate with Azure Resource Management API for managing Application Gateway certificates. See the [requirements](#client-certificate-or-client-secret) for more information. | +| AzureCloud | Azure Global Cloud Authority Host | MultipleChoice | public,china,germany,government | | Specifies the Azure Cloud instance used by the organization. | +| ServerUseSsl | Use SSL | Bool | true | ✅ | Specifies whether SSL should be used for communication with the server. Set to 'true' to enable SSL, and 'false' to disable it. | + + +The Custom Fields tab should look like this: + +![AzureAppGw Custom Fields Tab](../docsource/images/AzureAppGw-custom-fields-store-type-dialog.png) + + + +
+ +## Certificate Store Configuration + +After creating the `AzureAppGw` Certificate Store Type and installing the Azure Application Gateway Universal Orchestrator extension, you can create new [Certificate Stores](https://software.keyfactor.com/Core-OnPrem/Current/Content/ReferenceGuide/Certificate%20Stores.htm?Highlight=certificate%20store) to manage certificates in the remote platform. + +The following table describes the required and optional fields for the `AzureAppGw` certificate store type. + +| Attribute | Description | +| --------- | ----------- | +| Category | Select "Azure Application Gateway Certificate" or the customized certificate store name from the previous step. | +| Container | Optional container to associate certificate store with. | +| Client Machine | The Azure Tenant (directory) ID that owns the Service Principal. | +| Store Path | Azure resource ID of the application gateway, following the format: /subscriptions//resourceGroups//providers/Microsoft.Network/applicationGateways/. | +| Orchestrator | Select an approved orchestrator capable of managing `AzureAppGw` certificates. Specifically, one with the `AzureAppGw` capability. | +| ServerUsername | Application ID of the service principal, representing the identity used for managing the Application Gateway. | +| ServerPassword | A Client Secret that the extension will use to authenticate with the Azure Resource Management API for managing Application Gateway certificates, OR the password that encrypts the private key in ClientCertificate | +| ClientCertificate | The client certificate used to authenticate with Azure Resource Management API for managing Application Gateway certificates. See the [requirements](#client-certificate-or-client-secret) for more information. | +| AzureCloud | Specifies the Azure Cloud instance used by the organization. | +| ServerUseSsl | Specifies whether SSL should be used for communication with the server. Set to 'true' to enable SSL, and 'false' to disable it. | + +* **Using kfutil** + + ```shell + # Generate a CSV template for the AzureApp certificate store + kfutil stores import generate-template --store-type-name AzureAppGw --outpath AzureAppGw.csv + + # Open the CSV file and fill in the required fields for each certificate store. + + # Import the CSV file to create the certificate stores + kfutil stores import csv --store-type-name AzureAppGw --file AzureAppGw.csv + ``` + +* **Manually with the Command UI**: In Keyfactor Command, navigate to Certificate Stores from the Locations Menu. Click the Add button to create a new Certificate Store using the attributes in the table above. \ No newline at end of file diff --git a/docsource/appgwbin.md b/docsource/appgwbin.md new file mode 100644 index 0000000..9818b14 --- /dev/null +++ b/docsource/appgwbin.md @@ -0,0 +1,116 @@ +# Overview + +The Azure Application Gateway Certificate Binding store type, `AzureAppGwBin`, represents certificates bound to TLS Listeners on Azure App Gateways. The only supported operations on this store type are Management Add and Inventory. The Management Add operation for this store type creates and binds an ApplicationGatewaySslCertificate to a pre-existing TLS Listener on an Application Gateway. When the Add operation is configured in Keyfactor Command, the certificate Alias configures which TLS Listener the certificate will be bound to. If the HTTPS listener is already bound to a certificate with the same name, the Management Add operation will perform a replacement of the certificate, _**regardless of the existence of the Replace flag configured with renewal jobs**_. The replacement operation performs several API interactions with Azure since at least one certificate must be bound to a TLS listener at all times, and the name of ApplicationGatewaySslCertificates must be unique. For the sake of completeness, the following describes the mechanics of this replacement operation: + +1. Determine the name of the certificate currently bound to the HTTPS listener - Alias in 100% of cases if the certificate was originally added by the App Gateway Orchestrator Extension, or something else if the certificate was added by some other means (IE, the Azure Portal, or some other API client). +2. Create and bind a temporary certificate to the HTTPS listener with the same name as the Alias. +3. Delete the AppGatewayCertificate previously bound to the HTTPS listener called Alias. +4. Recreate and bind an AppGatewayCertificate with the same name as the HTTPS listener called Alias. If the Alias is called `listener1`, the new certificate will be called `listener1`, regardless of the name of the certificate that was previously bound to the listener. +5. Delete the temporary certificate. + +In the unlikely event that a failure occurs at any point in the replacement procedure, it's expected that the correct certificate will be served by the TLS Listener, since most of the mechanics are actually implemented to resolve the unique naming requirement. + +The Inventory job type for `AzureAppGwBin` reports only ApplicationGatewaySslCertificates that are bound to TLS Listeners. If the certificate was added with Keyfactor Command and this orchestrator extension, the name of the certificate in the Application Gateway will be the same as the TLS Listener. E.g., if the Alias configured in Command corresponds to a TLS Listener called `location-service-https-lstn1`, the certificate in the Application Gateway will also be called `location-service-https-lstn1`. However, if the certificate was added to the Application Gateway by other means (such as the Azure CLI, import from AKV, etc.), the Inventory job mechanics will still report the name of the TLS Listener in its report back to Command. + +# Requirements + +### Azure Service Principal (Azure Resource Manager Authentication) + +The Azure Application Gateway Orchestrator extension uses an [Azure Service Principal](https://learn.microsoft.com/en-us/entra/identity-platform/app-objects-and-service-principals?tabs=browser) for authentication. Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/entra/identity-platform/howto-create-service-principal-portal) to create a service principal. + +#### Azure Application Gateway permissions + +For quick start and non-production environments, a Role Assignment should be created on _each resource group_ that own Application Gateways desiring management that grants the created Application/Service Principal the [Contributor (Privileged administrator) Role](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#contributor). For production environments, a custom role should be created that grants the following permissions: + +- `Microsoft.Resources/subscriptions/resourcegroups/read` - Read : Get Resource Group +- `Microsoft.Network/applicationGateways/read` - Read : Get Application Gateway +- `Microsoft.Network/applicationGateways/write` - Write : Create or Update Application Gateway +- `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action` - Other : RBAC action for assigning an existing user assigned identity to a resource +- `Microsoft.Network/virtualNetworks/subnets/join/action` - Other : Joins a virtual network. Not Alertable. + +> Note that even if the Service Principal has permission to perform the 'Microsoft.Network/applicationGateways/write' action over the scope of the required resource group, there may be other permissions that are required by the CreateOrUpdate operation depending on the complexity of the Application Gateway's configuration. As such, the list of permissions above should not be considered as comprehensive. + +#### Azure Key Vault permissions + +If the managed Application Gateway is integrated with Azure Key Vault per the discussion in the [Certificates Imported to Application Gateways from Azure Key Vault](#certificates-imported-to-application-gateways-from-azure-key-vault) section, perform one of the following actions for each Key Vault with certificates imported to App Gateways: +* **Azure role-based access control** - Create a Role Assignment that grants the Application/Service Principal the [Key Vault Secrets User](https://learn.microsoft.com/en-us/azure/key-vault/general/rbac-guide?tabs=azure-cli) built-in role. +* **Vault access policy** - [Create an Access Policy](https://learn.microsoft.com/en-us/azure/key-vault/general/assign-access-policy?tabs=azure-portal) that grants the Application/Service Principal the Get secret permission for each Azure Key Vault. + +#### Client Certificate or Client Secret + +Beginning in version 3.0.0, the Azure Application Gateway Orchestrator extension supports both [client certificate authentication](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) and [client secret](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-2-add-a-client-secret) authentication. + +* **Client Secret** - Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-2-add-a-client-secret) to create a Client Secret. This secret will be used as the **Server Password** field in the [Certificate Store Configuration](#certificate-store-configuration) section. +* **Client Certificate** - Create a client certificate key pair with the Client Authentication extended key usage. The client certificate will be used in the ClientCertificate field in the [Certificate Store Configuration](#certificate-store-configuration) section. If you have access to Keyfactor Command, the instructions in this section walk you through enrolling a certificate and ensuring that it's in the correct format. Once enrolled, follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) to add the _public key_ certificate (no private key) to the service principal used for authentication. + + The certificate can be in either of the following formats: + * Base64-encoded PKCS#12 (PFX) with a matching private key. + * Base64-encoded PEM-encoded certificate _and_ PEM-encoded PKCS8 private key. Make sure that the certificate and private key are separated with a newline. The order doesn't matter - the extension will determine which is which. + + If the private key is encrypted, the encryption password will replace the **Server Password** field in the [Certificate Store Configuration](#certificate-store-configuration) section. + +> **Creating and Formatting a Client Certificate using Keyfactor Command** +> +> To get started quickly, you can follow the instructions below to create and properly format a client certificate to authenticate to the Microsoft Graph API. +> +> 1. In Keyfactor Command, hover over **Enrollment** and select **PFX Enrollment**. +> 2. Select a **Template** that supports Client Authentication as an extended key usage. +> 3. Populate the certificate subject as appropriate for the Template. It may be sufficient to only populate the Common Name, but consult your IT policy to ensure that this certificate is compliant. +> 4. At the bottom of the page, uncheck the box for **Include Chain**, and select either **PFX** or **PEM** as the certificate Format. +> 5. Make a note of the password on the next page - it won't be shown again. +> 6. Prepare the certificate and private key for Azure and the Orchestrator extension: +> * If you downloaded the certificate in PEM format, use the commands below: +> +> ```shell +> # Verify that the certificate downloaded from Command contains the certificate and private key. They should be in the same file +> cat +> +> # Separate the certificate from the private key +> openssl x509 -in -out pubkeycert.pem +> +> # Base64 encode the certificate and private key +> cat | base64 > clientcertkeypair.pem.base64 +> ``` +> +> * If you downloaded the certificate in PFX format, use the commands below: +> +> ```shell +> # Export the certificate from the PFX file +> openssl pkcs12 -in -clcerts -nokeys -out pubkeycert.pem +> +> # Base64 encode the PFX file +> cat | base64 > clientcert.pfx.base64 +> ``` +> 7. Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) to add the public key certificate to the service principal used for authentication. +> +> You will use `clientcert.[pem|pfx].base64` as the **ClientCertificate** field in the [Certificate Store Configuration](#certificate-store-configuration) section. + +# Extension Mechanics + +### Discovery Job + +The Discovery operation discovers all Azure Application Gateways in each resource group that the service principal has access to. The discovered Application Gateways are reported back to Command and can be easily added as certificate stores from the Locations tab. + +The Discovery operation uses the "Directories to search" field, and accepts input in one of the following formats: +- `*` - If the asterisk symbol `*` is used, the extension will search for Application Gateways in every resource group that the service principal has access to, but only in the tenant that the discovery job was configured for as specified by the "Client Machine" field in the certificate store configuration. +- `,,...` - If a comma-separated list of tenant IDs is used, the extension will search for Application Gateways in every resource group and tenant specified in the list. The tenant IDs should be the GUIDs associated with each tenant, and it's the user's responsibility to ensure that the service principal has access to the specified tenants. + +> The Discovery Job only supports Client Secret authentication. + +### Certificates Imported to Application Gateways from Azure Key Vault + +Natively, Azure Application Gateways support integration with Azure Key Vault for secret/certificate management. This integration works by creating a TLS Listener certificate with a reference to a secret in Azure Key Vault (specifically, a URI in the format `https://.vault.azure.net/secrets/`), authenticated using a Managed Identity. If the Application Gateway orchestrator extension is deployed to manage App Gateways with certificates imported from Azure Key Vault, the following truth table represents the possible operations and their result, specifically with respect to AKV. + +| Store Type | Operation | Result | +|--------------|-----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `AzureAppGw` | Inventory | Certificate is downloaded from Azure Key Vault and reported back to Keyfactor Command. In Keyfactor Command, the certificate will show as being located in the AzureAppGw certificate store [in addition to the AKV, if AKV orchestrator extension is also deployed]. | +| `AzureAppGw` | Add | The Add operation will not create secrets in AKV; it creates ApplicationGatewaySslCertificates.

If an `AzureAppGw` Add operation is scheduled with the Replace flag, the _**link to the AKV certificate will be broken**_, and a native ApplicationGatewaySslCertificate will be created in its place - The secret in AKV will still exist. | +| `AzureAppGw` | Remove | The ApplicationGatewaySslCertificate is deleted from the Application Gateway, but the secret that the certificate referenced in AKV still exists. | +| `AzureAppGwBin` | Inventory | Certificate is downloaded from Azure Key Vault and reported back to Keyfactor Command. In Keyfactor Command, the certificate will show as present in both an `AzureAppGw` certificate store _and_ an `AppGwBin` certificate store [in addition to the AKV, if AKV orchestrator extension is also deployed]. | +| `AzureAppGwBin` | Add | The Add operation will not create secrets in AKV; it creates ApplicationGatewaySslCertificates.

If a certificate with the same name as the TLS Listener already exists, it will be _replaced_ by a new ApplicationGatewaySslCertificate.

If the certificate being replaced was imported from AKV, this binding will be broken and the secret will still exist in AKV. | + +#### Mechanics of the Azure Key Vault Download Operation for Inventory Jobs that report certificates imported from AKV + +If an AzureApplicationSslCertificate references a secret in AKV (was imported to the App Gateway from AKV), the inventory job will create and use a `SecretClient` from the [`Azure.Security.KeyVault.Secrets.SecretClient` dotnet package](https://learn.microsoft.com/en-us/dotnet/api/azure.security.keyvault.secrets.secretclient?view=azure-dotnet). Authentication to AKV via this client is configured using the exact same `TokenCredential` provided by the [Azure Identity client library for .NET](https://learn.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme?view=azure-dotnet). This means that the Service Principal described in the [Azure Configuration](#azure-configuration) section must also have appropriate permissions to read secrets from the AKV that the App Gateway is integrated with. The secret referenced in the AzureApplicationSslCertificate will be accessed exactly as reported by Azure, regardless of whether it exists in AKV. + + diff --git a/docsource/azureappgw.md b/docsource/azureappgw.md new file mode 100644 index 0000000..1f674fa --- /dev/null +++ b/docsource/azureappgw.md @@ -0,0 +1,112 @@ +# Overview + +The Azure Application Gateway Certificate store type, `AzureAppGw`, manages `ApplicationGatewaySslCertificate` objects owned by Azure Application Gateways. This store type collects inventory and manages all ApplicationGatewaySslCertificate objects associated with an Application Gateway. The store type is implemented primarily for Inventory and Management Remove operations, since the intended usage of ApplicationGatewaySslCertificates in Application Gateways is for serving TLS client traffic via TLS Listeners. Management Add and associated logic for certificate renewal is also supported for this certificate store type for completeness, but the primary intended functionality of this extension is implemented with the App Gateway Certificate Binding store type. + +> If an ApplicationGatewaySslCertificate is bound to a TLS Listener at the time of a Management Remove operation, the operation will fail since at least one certificate must be bound at all times. + +> If a renewal job is scheduled for an `AzureAppGw` certificate store, the extension will report a success and perform no action if the certificate being renewed is bound to a TLS Listener. This is because a certificate located in an `AzureAppGw` certificate store that is bound to a TLS Listener is logically the same as the same certificate located in an `AzureAppGwBin` store type. For this reason, it's expected that the certificate will be renewed and re-bound to the listener by the `AppGwBin` certificate operations. +> +> If the renewed certificate is not bound to a TLS Listener, the operation will be performed the same as any certificate renewal process that honors the Overwrite flag. + +# Requirements + +### Azure Service Principal (Azure Resource Manager Authentication) + +The Azure Application Gateway Orchestrator extension uses an [Azure Service Principal](https://learn.microsoft.com/en-us/entra/identity-platform/app-objects-and-service-principals?tabs=browser) for authentication. Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/entra/identity-platform/howto-create-service-principal-portal) to create a service principal. + +#### Azure Application Gateway permissions + +For quick start and non-production environments, a Role Assignment should be created on _each resource group_ that own Application Gateways desiring management that grants the created Application/Service Principal the [Contributor (Privileged administrator) Role](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#contributor). For production environments, a custom role should be created that grants the following permissions: + +- `Microsoft.Resources/subscriptions/resourcegroups/read` - Read : Get Resource Group +- `Microsoft.Network/applicationGateways/read` - Read : Get Application Gateway +- `Microsoft.Network/applicationGateways/write` - Write : Create or Update Application Gateway +- `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action` - Other : RBAC action for assigning an existing user assigned identity to a resource +- `Microsoft.Network/virtualNetworks/subnets/join/action` - Other : Joins a virtual network. Not Alertable. + +> Note that even if the Service Principal has permission to perform the 'Microsoft.Network/applicationGateways/write' action over the scope of the required resource group, there may be other permissions that are required by the CreateOrUpdate operation depending on the complexity of the Application Gateway's configuration. As such, the list of permissions above should not be considered as comprehensive. + +#### Azure Key Vault permissions + +If the managed Application Gateway is integrated with Azure Key Vault per the discussion in the [Certificates Imported to Application Gateways from Azure Key Vault](#certificates-imported-to-application-gateways-from-azure-key-vault) section, perform one of the following actions for each Key Vault with certificates imported to App Gateways: +* **Azure role-based access control** - Create a Role Assignment that grants the Application/Service Principal the [Key Vault Secrets User](https://learn.microsoft.com/en-us/azure/key-vault/general/rbac-guide?tabs=azure-cli) built-in role. +* **Vault access policy** - [Create an Access Policy](https://learn.microsoft.com/en-us/azure/key-vault/general/assign-access-policy?tabs=azure-portal) that grants the Application/Service Principal the Get secret permission for each Azure Key Vault. + +#### Client Certificate or Client Secret + +Beginning in version 3.0.0, the Azure Application Gateway Orchestrator extension supports both [client certificate authentication](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) and [client secret](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-2-add-a-client-secret) authentication. + +* **Client Secret** - Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-2-add-a-client-secret) to create a Client Secret. This secret will be used as the **Server Password** field in the [Certificate Store Configuration](#certificate-store-configuration) section. +* **Client Certificate** - Create a client certificate key pair with the Client Authentication extended key usage. The client certificate will be used in the ClientCertificate field in the [Certificate Store Configuration](#certificate-store-configuration) section. If you have access to Keyfactor Command, the instructions in this section walk you through enrolling a certificate and ensuring that it's in the correct format. Once enrolled, follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) to add the _public key_ certificate (no private key) to the service principal used for authentication. + + The certificate can be in either of the following formats: + * Base64-encoded PKCS#12 (PFX) with a matching private key. + * Base64-encoded PEM-encoded certificate _and_ PEM-encoded PKCS8 private key. Make sure that the certificate and private key are separated with a newline. The order doesn't matter - the extension will determine which is which. + + If the private key is encrypted, the encryption password will replace the **Server Password** field in the [Certificate Store Configuration](#certificate-store-configuration) section. + +> **Creating and Formatting a Client Certificate using Keyfactor Command** +> +> To get started quickly, you can follow the instructions below to create and properly format a client certificate to authenticate to the Microsoft Graph API. +> +> 1. In Keyfactor Command, hover over **Enrollment** and select **PFX Enrollment**. +> 2. Select a **Template** that supports Client Authentication as an extended key usage. +> 3. Populate the certificate subject as appropriate for the Template. It may be sufficient to only populate the Common Name, but consult your IT policy to ensure that this certificate is compliant. +> 4. At the bottom of the page, uncheck the box for **Include Chain**, and select either **PFX** or **PEM** as the certificate Format. +> 5. Make a note of the password on the next page - it won't be shown again. +> 6. Prepare the certificate and private key for Azure and the Orchestrator extension: +> * If you downloaded the certificate in PEM format, use the commands below: +> +> ```shell +> # Verify that the certificate downloaded from Command contains the certificate and private key. They should be in the same file +> cat +> +> # Separate the certificate from the private key +> openssl x509 -in -out pubkeycert.pem +> +> # Base64 encode the certificate and private key +> cat | base64 > clientcertkeypair.pem.base64 +> ``` +> +> * If you downloaded the certificate in PFX format, use the commands below: +> +> ```shell +> # Export the certificate from the PFX file +> openssl pkcs12 -in -clcerts -nokeys -out pubkeycert.pem +> +> # Base64 encode the PFX file +> cat | base64 > clientcert.pfx.base64 +> ``` +> 7. Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) to add the public key certificate to the service principal used for authentication. +> +> You will use `clientcert.[pem|pfx].base64` as the **ClientCertificate** field in the [Certificate Store Configuration](#certificate-store-configuration) section. + +# Extension Mechanics + +### Discovery Job + +The Discovery operation discovers all Azure Application Gateways in each resource group that the service principal has access to. The discovered Application Gateways are reported back to Command and can be easily added as certificate stores from the Locations tab. + +The Discovery operation uses the "Directories to search" field, and accepts input in one of the following formats: +- `*` - If the asterisk symbol `*` is used, the extension will search for Application Gateways in every resource group that the service principal has access to, but only in the tenant that the discovery job was configured for as specified by the "Client Machine" field in the certificate store configuration. +- `,,...` - If a comma-separated list of tenant IDs is used, the extension will search for Application Gateways in every resource group and tenant specified in the list. The tenant IDs should be the GUIDs associated with each tenant, and it's the user's responsibility to ensure that the service principal has access to the specified tenants. + +> The Discovery Job only supports Client Secret authentication. + +### Certificates Imported to Application Gateways from Azure Key Vault + +Natively, Azure Application Gateways support integration with Azure Key Vault for secret/certificate management. This integration works by creating a TLS Listener certificate with a reference to a secret in Azure Key Vault (specifically, a URI in the format `https://.vault.azure.net/secrets/`), authenticated using a Managed Identity. If the Application Gateway orchestrator extension is deployed to manage App Gateways with certificates imported from Azure Key Vault, the following truth table represents the possible operations and their result, specifically with respect to AKV. + +| Store Type | Operation | Result | +|--------------|-----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `AzureAppGw` | Inventory | Certificate is downloaded from Azure Key Vault and reported back to Keyfactor Command. In Keyfactor Command, the certificate will show as being located in the AzureAppGw certificate store [in addition to the AKV, if AKV orchestrator extension is also deployed]. | +| `AzureAppGw` | Add | The Add operation will not create secrets in AKV; it creates ApplicationGatewaySslCertificates.

If an `AzureAppGw` Add operation is scheduled with the Replace flag, the _**link to the AKV certificate will be broken**_, and a native ApplicationGatewaySslCertificate will be created in its place - The secret in AKV will still exist. | +| `AzureAppGw` | Remove | The ApplicationGatewaySslCertificate is deleted from the Application Gateway, but the secret that the certificate referenced in AKV still exists. | +| `AzureAppGwBin` | Inventory | Certificate is downloaded from Azure Key Vault and reported back to Keyfactor Command. In Keyfactor Command, the certificate will show as present in both an `AzureAppGw` certificate store _and_ an `AppGwBin` certificate store [in addition to the AKV, if AKV orchestrator extension is also deployed]. | +| `AzureAppGwBin` | Add | The Add operation will not create secrets in AKV; it creates ApplicationGatewaySslCertificates.

If a certificate with the same name as the TLS Listener already exists, it will be _replaced_ by a new ApplicationGatewaySslCertificate.

If the certificate being replaced was imported from AKV, this binding will be broken and the secret will still exist in AKV. | + +#### Mechanics of the Azure Key Vault Download Operation for Inventory Jobs that report certificates imported from AKV + +If an AzureApplicationSslCertificate references a secret in AKV (was imported to the App Gateway from AKV), the inventory job will create and use a `SecretClient` from the [`Azure.Security.KeyVault.Secrets.SecretClient` dotnet package](https://learn.microsoft.com/en-us/dotnet/api/azure.security.keyvault.secrets.secretclient?view=azure-dotnet). Authentication to AKV via this client is configured using the exact same `TokenCredential` provided by the [Azure Identity client library for .NET](https://learn.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme?view=azure-dotnet). This means that the Service Principal described in the [Azure Configuration](#azure-configuration) section must also have appropriate permissions to read secrets from the AKV that the App Gateway is integrated with. The secret referenced in the AzureApplicationSslCertificate will be accessed exactly as reported by Azure, regardless of whether it exists in AKV. + + diff --git a/.github/images/AppGwBin-advanced-store-type-dialog.png b/docsource/images/AppGwBin-advanced-store-type-dialog.png similarity index 78% rename from .github/images/AppGwBin-advanced-store-type-dialog.png rename to docsource/images/AppGwBin-advanced-store-type-dialog.png index 5cc95d2..2b71e8c 100644 Binary files a/.github/images/AppGwBin-advanced-store-type-dialog.png and b/docsource/images/AppGwBin-advanced-store-type-dialog.png differ diff --git a/.github/images/AppGwBin-basic-store-type-dialog.png b/docsource/images/AppGwBin-basic-store-type-dialog.png similarity index 58% rename from .github/images/AppGwBin-basic-store-type-dialog.png rename to docsource/images/AppGwBin-basic-store-type-dialog.png index edc754a..d7ac55d 100644 Binary files a/.github/images/AppGwBin-basic-store-type-dialog.png and b/docsource/images/AppGwBin-basic-store-type-dialog.png differ diff --git a/docsource/images/AppGwBin-custom-fields-store-type-dialog.png b/docsource/images/AppGwBin-custom-fields-store-type-dialog.png new file mode 100644 index 0000000..296cd70 Binary files /dev/null and b/docsource/images/AppGwBin-custom-fields-store-type-dialog.png differ diff --git a/.github/images/AzureAppGw-advanced-store-type-dialog.png b/docsource/images/AzureAppGw-advanced-store-type-dialog.png similarity index 78% rename from .github/images/AzureAppGw-advanced-store-type-dialog.png rename to docsource/images/AzureAppGw-advanced-store-type-dialog.png index 5cc95d2..2b71e8c 100644 Binary files a/.github/images/AzureAppGw-advanced-store-type-dialog.png and b/docsource/images/AzureAppGw-advanced-store-type-dialog.png differ diff --git a/.github/images/AzureAppGw-basic-store-type-dialog.png b/docsource/images/AzureAppGw-basic-store-type-dialog.png similarity index 58% rename from .github/images/AzureAppGw-basic-store-type-dialog.png rename to docsource/images/AzureAppGw-basic-store-type-dialog.png index 5028c43..accfde4 100644 Binary files a/.github/images/AzureAppGw-basic-store-type-dialog.png and b/docsource/images/AzureAppGw-basic-store-type-dialog.png differ diff --git a/docsource/images/AzureAppGw-custom-fields-store-type-dialog.png b/docsource/images/AzureAppGw-custom-fields-store-type-dialog.png new file mode 100644 index 0000000..296cd70 Binary files /dev/null and b/docsource/images/AzureAppGw-custom-fields-store-type-dialog.png differ diff --git a/docsource/overview.md b/docsource/overview.md new file mode 100644 index 0000000..f8c615d --- /dev/null +++ b/docsource/overview.md @@ -0,0 +1,7 @@ +## Overview +The Azure Application Gateway Orchestrator extension remotely manages certificates used by Azure Application Gateways. The extension supports two different store types - one that generally manages certificates stored in the Application Gateway, and one that manages the bindings of Application Gateway certificates to HTTPS/TLS Listeners. + +> The extension manages only App Gateway Certificates, _not_ Azure Key Vault certificates. Certificates imported from Azure Key Vault to Azure Application Gateways will be downloaded for certificate inventory purposes _only_. The Azure Application Gateway orchestrator extension will _not_ perform certificate management operations on Azure Key Vault secrets. If you need to manage certificates in Azure Key Vault, use the [Azure Key Vault Orchestrator](https://github.com/Keyfactor/azurekeyvault-orchestrator). +> +> If the certificate management capabilities of Azure Key Vault are desired over direct management of certificates in Application Gateways, the Azure Key Vault orchestrator can be used in conjunction with this extension for accurate certificate location reporting via the inventory job type. This management strategy requires manual binding of certificates imported to an Application Gateway from AKV and can result in broken state in the Azure Application Gateway in the case that the secret is deleted in AKV. + diff --git a/integration-manifest.json b/integration-manifest.json index 62eeefb..9dc4c87 100644 --- a/integration-manifest.json +++ b/integration-manifest.json @@ -34,6 +34,8 @@ "ShortName": "AzureAppGw", "Capability": "AzureAppGw", "LocalStore": false, + "ClientMachineDescription": "The Azure Tenant (directory) ID that owns the Service Principal.", + "StorePathDescription": "Azure resource ID of the application gateway, following the format: /subscriptions//resourceGroups//providers/Microsoft.Network/applicationGateways/.", "SupportedOperations": { "Add": true, "Remove": true, @@ -46,19 +48,21 @@ "Name": "ServerUsername", "DisplayName": "Server Username", "Type": "Secret", - "Required": true + "Description": "Application ID of the service principal, representing the identity used for managing the Application Gateway.", + "Required": false }, { "Name": "ServerPassword", "DisplayName": "Server Password", "Type": "Secret", - "Required": true + "Description": "A Client Secret that the extension will use to authenticate with the Azure Resource Management API for managing Application Gateway certificates, OR the password that encrypts the private key in ClientCertificate", + "Required": false }, { - "Name": "ServerUseSsl", - "DisplayName": "Use SSL", - "Type": "Bool", - "DefaultValue": "true", + "Name": "ClientCertificate", + "DisplayName": "Client Certificate", + "Type": "Secret", + "Description": "The client certificate used to authenticate with Azure Resource Management API for managing Application Gateway certificates. See the [requirements](#client-certificate-or-client-secret) for more information.", "Required": false }, { @@ -66,7 +70,16 @@ "DisplayName": "Azure Global Cloud Authority Host", "Type": "MultipleChoice", "DefaultValue": "public,china,germany,government", + "Description": "Specifies the Azure Cloud instance used by the organization.", "Required": false + }, + { + "Name": "ServerUseSsl", + "DisplayName": "Use SSL", + "Type": "Bool", + "DefaultValue": "true", + "Description": "Specifies whether SSL should be used for communication with the server. Set to 'true' to enable SSL, and 'false' to disable it.", + "Required": true } ], "PasswordOptions": { @@ -85,6 +98,8 @@ "ShortName": "AppGwBin", "Capability": "AzureAppGwBin", "LocalStore": false, + "ClientMachineDescription": "The Azure Tenant (directory) ID that owns the Service Principal.", + "StorePathDescription": "Azure resource ID of the application gateway, following the format: /subscriptions//resourceGroups//providers/Microsoft.Network/applicationGateways/.", "SupportedOperations": { "Add": true, "Remove": false, @@ -97,27 +112,38 @@ "Name": "ServerUsername", "DisplayName": "Server Username", "Type": "Secret", + "Description": "Application ID of the service principal, representing the identity used for managing the Application Gateway.", "Required": false }, { "Name": "ServerPassword", "DisplayName": "Server Password", "Type": "Secret", + "Description": "A Client Secret that the extension will use to authenticate with the Azure Resource Management API for managing Application Gateway certificates, OR the password that encrypts the private key in ClientCertificate", "Required": false }, { - "Name": "ServerUseSsl", - "DisplayName": "Use SSL", - "Type": "Bool", - "DefaultValue": "true", - "Required": true + "Name": "ClientCertificate", + "DisplayName": "Client Certificate", + "Type": "Secret", + "Description": "The client certificate used to authenticate with Azure Resource Management API for managing Application Gateway certificates. See the [requirements](#client-certificate-or-client-secret) for more information.", + "Required": false }, { "Name": "AzureCloud", "DisplayName": "Azure Global Cloud Authority Host", "Type": "MultipleChoice", "DefaultValue": "public,china,germany,government", + "Description": "Specifies the Azure Cloud instance used by the organization.", "Required": false + }, + { + "Name": "ServerUseSsl", + "DisplayName": "Use SSL", + "Type": "Bool", + "DefaultValue": "true", + "Description": "Specifies whether SSL should be used for communication with the server. Set to 'true' to enable SSL, and 'false' to disable it.", + "Required": true } ], "PasswordOptions": { @@ -131,29 +157,7 @@ "BlueprintAllowed": false, "CustomAliasAllowed": "Required" } - ], - "store_types_metadata": { - "AzureAppGw": { - "ClientMachine": "The Azure Tenant ID of the service principal, representing the Tenant ID where the Application/Service Principal is managed.", - "StorePath": "Azure resource ID of the application gateway, following the format: `/subscriptions//resourceGroups//providers/Microsoft.Network/applicationGateways/`.", - "Properties": { - "ServerUsername": "Application ID of the service principal, representing the identity used for managing the Application Gateway.", - "ServerPassword": "Secret of the service principal that will be used to manage the Application Gateway.", - "ServerUseSsl": "Indicates whether SSL usage is enabled for the connection.", - "AzureCloud": "Specifies the Azure Cloud instance used by the organization." - } - }, - "AppGwBin": { - "ClientMachine": "The Azure Tenant ID of the service principal, representing the Tenant ID where the Application/Service Principal is managed.", - "StorePath": "Azure resource ID of the application gateway, following the format: `/subscriptions//resourceGroups//providers/Microsoft.Network/applicationGateways/`.", - "Properties": { - "ServerUsername": "Application ID of the service principal, representing the identity used for managing the Application Gateway.", - "ServerPassword": "Secret of the service principal that will be used to manage the Application Gateway.", - "ServerUseSsl": "Indicates whether SSL usage is enabled for the connection.", - "AzureCloud": "Specifies the Azure Cloud instance used by the organization." - } - } - } + ] } } } diff --git a/readme_source.md b/readme_source.md index 3c99033..6fc09c7 100644 --- a/readme_source.md +++ b/readme_source.md @@ -1,3 +1,35 @@ +

+ Azure Application Gateway Universal Orchestrator Extension +

+ +

+ +Integration Status: production +Release +Issues +GitHub Downloads (all assets, all releases) +

+ +

+ + + Support + + · + + Installation + + · + + License + + · + + Related Integrations + +

+ + ## Overview The Azure Application Gateway Orchestrator extension remotely manages certificates used by Azure Application Gateways. The extension supports two different store types - one that generally manages certificates stored in the Application Gateway, and one that manages the bindings of Application Gateway certificates to HTTPS/TLS Listeners. @@ -5,222 +37,243 @@ The Azure Application Gateway Orchestrator extension remotely manages certificat > > If the certificate management capabilities of Azure Key Vault are desired over direct management of certificates in Application Gateways, the Azure Key Vault orchestrator can be used in conjunction with this extension for accurate certificate location reporting via the inventory job type. This management strategy requires manual binding of certificates imported to an Application Gateway from AKV and can result in broken state in the Azure Application Gateway in the case that the secret is deleted in AKV. -### Azure Application Gateway Certificate store type - -The Azure Application Gateway Certificate store type, `AzureAppGw`, manages `ApplicationGatewaySslCertificate` objects owned by Azure Application Gateways. This store type collects inventory and manages all ApplicationGatewaySslCertificate objects associated with an Application Gateway. The store type is implemented primarily for Inventory and Management Remove operations, since the intended usage of ApplicationGatewaySslCertificates in Application Gateways is for serving TLS client traffic via TLS Listeners. Management Add and associated logic for certificate renewal is also supported for this certificate store type for completeness, but the primary intended functionality of this extension is implemented with the App Gateway Certificate Binding store type. - -> If an ApplicationGatewaySslCertificate is bound to a TLS Listener at the time of a Management Remove operation, the operation will fail since at least one certificate must be bound at all times. - -> If a renewal job is scheduled for an `AzureAppGw` certificate store, the extension will report a success and perform no action if the certificate being renewed is bound to a TLS Listener. This is because a certificate located in an `AzureAppGw` certificate store that is bound to a TLS Listener is logically the same as the same certificate located in an `AzureAppGwBin` store type. For this reason, it's expected that the certificate will be renewed and re-bound to the listener by the `AppGwBin` certificate operations. -> -> If the renewed certificate is not bound to a TLS Listener, the operation will be performed the same as any certificate renewal process that honors the Overwrite flag. -### Azure Application Gateway Certificate Binding store type +## Installation +Before installing the Azure Application Gateway Universal Orchestrator extension, it's recommended to install [kfutil](https://github.com/Keyfactor/kfutil). Kfutil is a command-line tool that simplifies the process of creating store types, installing extensions, and instantiating certificate stores in Keyfactor Command. -The Azure Application Gateway Certificate Binding store type, `AzureAppGwBin`, represents certificates bound to TLS Listeners on Azure App Gateways. The only supported operations on this store type are Management Add and Inventory. The Management Add operation for this store type creates and binds an ApplicationGatewaySslCertificate to a pre-existing TLS Listener on an Application Gateway. When the Add operation is configured in Keyfactor Command, the certificate Alias configures which TLS Listener the certificate will be bound to. If the HTTPS listener is already bound to a certificate with the same name, the Management Add operation will perform a replacement of the certificate, _**regardless of the existence of the Replace flag configured with renewal jobs**_. The replacement operation performs several API interactions with Azure since at least one certificate must be bound to a TLS listener at all times, and the name of ApplicationGatewaySslCertificates must be unique. For the sake of completeness, the following describes the mechanics of this replacement operation: - -1. Determine the name of the certificate currently bound to the HTTPS listener - Alias in 100% of cases if the certificate was originally added by the App Gateway Orchestrator Extension, or something else if the certificate was added by some other means (IE, the Azure Portal, or some other API client). -2. Create and bind a temporary certificate to the HTTPS listener with the same name as the Alias. -3. Delete the AppGatewayCertificate previously bound to the HTTPS listener called Alias. -4. Recreate and bind an AppGatewayCertificate with the same name as the HTTPS listener called Alias. If the Alias is called `listener1`, the new certificate will be called `listener1`, regardless of the name of the certificate that was previously bound to the listener. -5. Delete the temporary certificate. +The Azure Application Gateway Universal Orchestrator extension implements 2 Certificate Store Types. Depending on your use case, you may elect to install one, or all of these Certificate Store Types. An overview for each type is linked below: +* [Azure Application Gateway Certificate](docs/azureappgw.md) +* [Azure Application Gateway Certificate Binding](docs/appgwbin.md) -In the unlikely event that a failure occurs at any point in the replacement procedure, it's expected that the correct certificate will be served by the TLS Listener, since most of the mechanics are actually implemented to resolve the unique naming requirement. +
Azure Application Gateway Certificate -The Inventory job type for `AzureAppGwBin` reports only ApplicationGatewaySslCertificates that are bound to TLS Listeners. If the certificate was added with Keyfactor Command and this orchestrator extension, the name of the certificate in the Application Gateway will be the same as the TLS Listener. E.g., if the Alias configured in Command corresponds to a TLS Listener called `location-service-https-lstn1`, the certificate in the Application Gateway will also be called `location-service-https-lstn1`. However, if the certificate was added to the Application Gateway by other means (such as the Azure CLI, import from AKV, etc.), the Inventory job mechanics will still report the name of the TLS Listener in its report back to Command. -### Discovery Job +1. Follow the [requirements section](docs/azureappgw.md#requirements) to configure a Service Account and grant necessary API permissions. -Both `AzureAppGw` and `AzureAppGwBin` support the Discovery operation. The Discovery operation discovers all Azure Application Gateways in each resource group that the service principal has access to. The discovered Application Gateways are reported back to Command and can be easily added as certificate stores from the Locations tab. +
Requirements + + ### Azure Service Principal (Azure Resource Manager Authentication) -The Discovery operation uses the "Directories to search" field, and accepts input in one of the following formats: -- `*` - If the asterisk symbol `*` is used, the extension will search for Application Gateways in every resource group that the service principal has access to, but only in the tenant that the discovery job was configured for as specified by the "Client Machine" field in the certificate store configuration. -- `,,...` - If a comma-separated list of tenant IDs is used, the extension will search for Application Gateways in every resource group and tenant specified in the list. The tenant IDs should be the GUIDs associated with each tenant, and it's the user's responsibility to ensure that the service principal has access to the specified tenants. + The Azure Application Gateway Orchestrator extension uses an [Azure Service Principal](https://learn.microsoft.com/en-us/entra/identity-platform/app-objects-and-service-principals?tabs=browser) for authentication. Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/entra/identity-platform/howto-create-service-principal-portal) to create a service principal. -### Certificates Imported to Application Gateways from Azure Key Vault + #### Azure Application Gateway permissions -Natively, Azure Application Gateways support integration with Azure Key Vault for secret/certificate management. This integration works by creating a TLS Listener certificate with a reference to a secret in Azure Key Vault (specifically, a URI in the format `https://.vault.azure.net/secrets/`), authenticated using a Managed Identity. If the Application Gateway orchestrator extension is deployed to manage App Gateways with certificates imported from Azure Key Vault, the following truth table represents the possible operations and their result, specifically with respect to AKV. + For quick start and non-production environments, a Role Assignment should be created on _each resource group_ that own Application Gateways desiring management that grants the created Application/Service Principal the [Contributor (Privileged administrator) Role](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#contributor). For production environments, a custom role should be created that grants the following permissions: -| Store Type | Operation | Result | -|--------------|-----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `AzureAppGw` | Inventory | Certificate is downloaded from Azure Key Vault and reported back to Keyfactor Command. In Keyfactor Command, the certificate will show as being located in the AzureAppGw certificate store [in addition to the AKV, if AKV orchestrator extension is also deployed]. | -| `AzureAppGw` | Add | The Add operation will not create secrets in AKV; it creates ApplicationGatewaySslCertificates.

If an `AzureAppGw` Add operation is scheduled with the Replace flag, the _**link to the AKV certificate will be broken**_, and a native ApplicationGatewaySslCertificate will be created in its place - The secret in AKV will still exist. | -| `AzureAppGw` | Remove | The ApplicationGatewaySslCertificate is deleted from the Application Gateway, but the secret that the certificate referenced in AKV still exists. | -| `AzureAppGwBin` | Inventory | Certificate is downloaded from Azure Key Vault and reported back to Keyfactor Command. In Keyfactor Command, the certificate will show as present in both an `AzureAppGw` certificate store _and_ an `AppGwBin` certificate store [in addition to the AKV, if AKV orchestrator extension is also deployed]. | -| `AzureAppGwBin` | Add | The Add operation will not create secrets in AKV; it creates ApplicationGatewaySslCertificates.

If a certificate with the same name as the TLS Listener already exists, it will be _replaced_ by a new ApplicationGatewaySslCertificate.

If the certificate being replaced was imported from AKV, this binding will be broken and the secret will still exist in AKV. | + - `Microsoft.Resources/subscriptions/resourcegroups/read` - Read : Get Resource Group + - `Microsoft.Network/applicationGateways/read` - Read : Get Application Gateway + - `Microsoft.Network/applicationGateways/write` - Write : Create or Update Application Gateway + - `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action` - Other : RBAC action for assigning an existing user assigned identity to a resource + - `Microsoft.Network/virtualNetworks/subnets/join/action` - Other : Joins a virtual network. Not Alertable. -#### Mechanics of the Azure Key Vault Download Operation for Inventory Jobs that report certificates imported from AKV + > Note that even if the Service Principal has permission to perform the 'Microsoft.Network/applicationGateways/write' action over the scope of the required resource group, there may be other permissions that are required by the CreateOrUpdate operation depending on the complexity of the Application Gateway's configuration. As such, the list of permissions above should not be considered as comprehensive. -If an AzureApplicationSslCertificate references a secret in AKV (was imported to the App Gateway from AKV), the inventory job will create and use a `SecretClient` from the [`Azure.Security.KeyVault.Secrets.SecretClient` dotnet package](https://learn.microsoft.com/en-us/dotnet/api/azure.security.keyvault.secrets.secretclient?view=azure-dotnet). Authentication to AKV via this client is configured using the exact same `TokenCredential` provided by the [Azure Identity client library for .NET](https://learn.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme?view=azure-dotnet). This means that the Service Principal described in the [Azure Configuration](#azure-configuration) section must also have appropriate permissions to read secrets from the AKV that the App Gateway is integrated with. The secret referenced in the AzureApplicationSslCertificate will be accessed exactly as reported by Azure, regardless of whether it exists in AKV. + #### Azure Key Vault permissions -## Azure Configuration and Permissions + If the managed Application Gateway is integrated with Azure Key Vault per the discussion in the [Certificates Imported to Application Gateways from Azure Key Vault](#certificates-imported-to-application-gateways-from-azure-key-vault) section, perform one of the following actions for each Key Vault with certificates imported to App Gateways: + * **Azure role-based access control** - Create a Role Assignment that grants the Application/Service Principal the [Key Vault Secrets User](https://learn.microsoft.com/en-us/azure/key-vault/general/rbac-guide?tabs=azure-cli) built-in role. + * **Vault access policy** - [Create an Access Policy](https://learn.microsoft.com/en-us/azure/key-vault/general/assign-access-policy?tabs=azure-portal) that grants the Application/Service Principal the Get secret permission for each Azure Key Vault. -The Azure Application Gateway Orchestrator extension uses an [Azure Service Principal](https://learn.microsoft.com/en-us/entra/identity-platform/app-objects-and-service-principals?tabs=browser) for authentication. Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/azure/purview/create-service-principal-azure) to create a service principal. + #### Client Certificate or Client Secret -For quick start and non-production environments, a Role Assignment should be created on _each resource group_ that own Application Gateways desiring management that grants the created Application/Service Principal the [Contributor (Privileged administrator) Role](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#contributor). For production environments, a custom role should be created that grants the following permissions: + Beginning in version 3.0.0, the Azure Application Gateway Orchestrator extension supports both [client certificate authentication](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) and [client secret](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-2-add-a-client-secret) authentication. -- `Microsoft.Resources/subscriptions/resourcegroups/read` - Read : Get Resource Group -- `Microsoft.Network/applicationGateways/read` - Read : Get Application Gateway -- `Microsoft.Network/applicationGateways/write` - Write : Create or Update Application Gateway -- `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action` - Other : RBAC action for assigning an existing user assigned identity to a resource -- `Microsoft.Network/virtualNetworks/subnets/join/action` - Other : Joins a virtual network. Not Alertable. + * **Client Secret** - Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-2-add-a-client-secret) to create a Client Secret. This secret will be used as the **Server Password** field in the [Certificate Store Configuration](#certificate-store-configuration) section. + * **Client Certificate** - Create a client certificate key pair with the Client Authentication extended key usage. The client certificate will be used in the ClientCertificate field in the [Certificate Store Configuration](#certificate-store-configuration) section. If you have access to Keyfactor Command, the instructions in this section walk you through enrolling a certificate and ensuring that it's in the correct format. Once enrolled, follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) to add the _public key_ certificate (no private key) to the service principal used for authentication. -> Note that even if the Service Principal has permission to perform the 'Microsoft.Network/applicationGateways/write' action over the scope of the required resource group, there may be other permissions that are required by the CreateOrUpdate operation depending on the complexity of the Application Gateway's configuration. As such, the list of permissions above should not be considered as comprehensive. + The certificate can be in either of the following formats: + * Base64-encoded PKCS#12 (PFX) with a matching private key. + * Base64-encoded PEM-encoded certificate _and_ PEM-encoded PKCS8 private key. Make sure that the certificate and private key are separated with a newline. The order doesn't matter - the extension will determine which is which. -If the managed Application Gateway is integrated with Azure Key Vault per the discussion in the [Certificates Imported to Application Gateways from Azure Key Vault](#certificates-imported-to-application-gateways-from-azure-key-vault) section, an [Access policy must be created](https://learn.microsoft.com/en-us/azure/key-vault/general/assign-access-policy?tabs=azure-portal) that grants the Application/Service Principal the Get secret permission for the associated Azure Key Vault. + If the private key is encrypted, the encryption password will replace the **Server Password** field in the [Certificate Store Configuration](#certificate-store-configuration) section. -## Creating Store Types for the Azure Application Gateway Orchestrator -To get started with the Azure Application Gateway Orchestrator Extension, you'll need to create 2 store types in Keyfactor Command. The recommended and supported way to create store types is using the `kfutil` command line tool. Install [Kfutil](https://github.com/Keyfactor/kfutil) if it is not already installed. Once installed, use `kfutil login` to log into the target Command environment. + > **Creating and Formatting a Client Certificate using Keyfactor Command** + > + > To get started quickly, you can follow the instructions below to create and properly format a client certificate to authenticate to the Microsoft Graph API. + > + > 1. In Keyfactor Command, hover over **Enrollment** and select **PFX Enrollment**. + > 2. Select a **Template** that supports Client Authentication as an extended key usage. + > 3. Populate the certificate subject as appropriate for the Template. It may be sufficient to only populate the Common Name, but consult your IT policy to ensure that this certificate is compliant. + > 4. At the bottom of the page, uncheck the box for **Include Chain**, and select either **PFX** or **PEM** as the certificate Format. + > 5. Make a note of the password on the next page - it won't be shown again. + > 6. Prepare the certificate and private key for Azure and the Orchestrator extension: + > * If you downloaded the certificate in PEM format, use the commands below: + > + > ```shell + > # Verify that the certificate downloaded from Command contains the certificate and private key. They should be in the same file + > cat + > + > # Separate the certificate from the private key + > openssl x509 -in -out pubkeycert.pem + > + > # Base64 encode the certificate and private key + > cat | base64 > clientcertkeypair.pem.base64 + > ``` + > + > * If you downloaded the certificate in PFX format, use the commands below: + > + > ```shell + > # Export the certificate from the PFX file + > openssl pkcs12 -in -clcerts -nokeys -out pubkeycert.pem + > + > # Base64 encode the PFX file + > cat | base64 > clientcert.pfx.base64 + > ``` + > 7. Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) to add the public key certificate to the service principal used for authentication. + > + > You will use `clientcert.[pem|pfx].base64` as the **ClientCertificate** field in the [Certificate Store Configuration](#certificate-store-configuration) section. -Then, use the following commands to create the store types: -```shell -kfutil store-types create AzureAppGw -kfutil store-types create AppGwBin -``` +
-It is not required to create all store types. Only create the store types that are needed for the integration. +2. Create Certificate Store Types for the Azure Application Gateway Orchestrator extension. -If you prefer to create store types manually in the UI, navigate to your Command instance and follow the instructions below. -
AzureAppGw + * **Using kfutil**: -Create a store type called `AzureAppGw` with the attributes in the tables below: + ```shell + # Azure Application Gateway Certificate + kfutil store-types create AzureAppGw + ``` -### Basic Tab -| Attribute | Value | Description | -| --------- | ----- | ----- | -| Name | Azure Application Gateway Certificate | Display name for the store type (may be customized) | -| Short Name | AzureAppGw | Short display name for the store type | -| Capability | AzureAppGw | Store type name orchestrator will register with. Check the box to allow entry of value | -| Supported Job Types (check the box for each) | Add, Remove, Discovery, Inventory | Job types the extension supports | -| Needs Server | ✓ | Determines if a target server name is required when creating store | -| Blueprint Allowed | | Determines if store type may be included in an Orchestrator blueprint | -| Uses PowerShell | | Determines if underlying implementation is PowerShell | -| Requires Store Password | | Determines if a store password is required when configuring an individual store. | -| Supports Entry Password | | Determines if an individual entry within a store can have a password. | + * **Manually**: + * [Azure Application Gateway Certificate](docs/azureappgw.md#certificate-store-type-configuration) +3. Install the Azure Application Gateway Universal Orchestrator extension. + + * **Using kfutil**: On the server that that hosts the Universal Orchestrator, run the following command: -The Basic tab should look like this: + ```shell + # Windows Server + kfutil orchestrator extension -e azure-appgateway-orchestrator@latest --out "C:\Program Files\Keyfactor\Keyfactor Orchestrator\extensions" -![AzureAppGw Basic Tab](.github/images/AzureAppGw-basic-store-type-dialog.png) + # Linux + kfutil orchestrator extension -e azure-appgateway-orchestrator@latest --out "/opt/keyfactor/orchestrator/extensions" + ``` + + * **Manually**: Follow the [official Command documentation](https://software.keyfactor.com/Core-OnPrem/Current/Content/InstallingAgents/NetCoreOrchestrator/CustomExtensions.htm?Highlight=extensions) to install the latest [Azure Application Gateway Universal Orchestrator extension](https://github.com/Keyfactor/azure-appgateway-orchestrator/releases/latest). -### Advanced Tab -| Attribute | Value | Description | -| --------- | ----- | ----- | -| Supports Custom Alias | Required | Determines if an individual entry within a store can have a custom Alias. | -| Private Key Handling | Required | This determines if Keyfactor can send the private key associated with a certificate to the store. Required because IIS certificates without private keys would be invalid. | -| PFX Password Style | Default | 'Default' - PFX password is randomly generated, 'Custom' - PFX password may be specified when the enrollment job is created (Requires the Allow Custom Password application setting to be enabled.) | +4. Create new certificate stores in Keyfactor Command for the Sample Universal Orchestrator extension. + * [Azure Application Gateway Certificate](docs/azureappgw.md#certificate-store-configuration) +
+
Azure Application Gateway Certificate Binding -The Advanced tab should look like this: -![AzureAppGw Advanced Tab](.github/images/AzureAppGw-advanced-store-type-dialog.png) +1. Follow the [requirements section](docs/appgwbin.md#requirements) to configure a Service Account and grant necessary API permissions. -### Custom Fields Tab -Custom fields operate at the certificate store level and are used to control how the orchestrator connects to the remote target server containing the certificate store to be managed. The following custom fields should be added to the store type: +
Requirements -| Name | Display Name | Type | Default Value/Options | Required | Description | -| ---- | ------------ | ---- | --------------------- | -------- | ----------- | -| ServerUsername | Server Username | Secret | None | ✓ | Application ID of the service principal, representing the identity used for managing the Application Gateway. | -| ServerPassword | Server Password | Secret | None | ✓ | Secret of the service principal that will be used to manage the Application Gateway. | -| ServerUseSsl | Use SSL | Bool | true | | Indicates whether SSL usage is enabled for the connection. | -| AzureCloud | Azure Global Cloud Authority Host | MultipleChoice | public,china,germany,government | | Specifies the Azure Cloud instance used by the organization. | + ### Azure Service Principal (Azure Resource Manager Authentication) + The Azure Application Gateway Orchestrator extension uses an [Azure Service Principal](https://learn.microsoft.com/en-us/entra/identity-platform/app-objects-and-service-principals?tabs=browser) for authentication. Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/entra/identity-platform/howto-create-service-principal-portal) to create a service principal. -The Custom Fields tab should look like this: + #### Azure Application Gateway permissions -![AzureAppGw Custom Fields Tab](.github/images/AzureAppGw-custom-fields-store-type-dialog.png) + For quick start and non-production environments, a Role Assignment should be created on _each resource group_ that own Application Gateways desiring management that grants the created Application/Service Principal the [Contributor (Privileged administrator) Role](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#contributor). For production environments, a custom role should be created that grants the following permissions: -
+ - `Microsoft.Resources/subscriptions/resourcegroups/read` - Read : Get Resource Group + - `Microsoft.Network/applicationGateways/read` - Read : Get Application Gateway + - `Microsoft.Network/applicationGateways/write` - Write : Create or Update Application Gateway + - `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action` - Other : RBAC action for assigning an existing user assigned identity to a resource + - `Microsoft.Network/virtualNetworks/subnets/join/action` - Other : Joins a virtual network. Not Alertable. -
AppGwBin + > Note that even if the Service Principal has permission to perform the 'Microsoft.Network/applicationGateways/write' action over the scope of the required resource group, there may be other permissions that are required by the CreateOrUpdate operation depending on the complexity of the Application Gateway's configuration. As such, the list of permissions above should not be considered as comprehensive. -Create a store type called `AppGwBin` with the attributes in the tables below: + #### Azure Key Vault permissions -### Basic Tab -| Attribute | Value | Description | -| --------- | ----- | ----- | -| Name | Azure Application Gateway Certificate Binding | Display name for the store type (may be customized) | -| Short Name | AppGwBin | Short display name for the store type | -| Capability | AzureAppGwBin | Store type name orchestrator will register with. Check the box to allow entry of value | -| Supported Job Types (check the box for each) | Add, Discovery | Job types the extension supports | -| Needs Server | ✓ | Determines if a target server name is required when creating store | -| Blueprint Allowed | | Determines if store type may be included in an Orchestrator blueprint | -| Uses PowerShell | | Determines if underlying implementation is PowerShell | -| Requires Store Password | | Determines if a store password is required when configuring an individual store. | -| Supports Entry Password | | Determines if an individual entry within a store can have a password. | + If the managed Application Gateway is integrated with Azure Key Vault per the discussion in the [Certificates Imported to Application Gateways from Azure Key Vault](#certificates-imported-to-application-gateways-from-azure-key-vault) section, perform one of the following actions for each Key Vault with certificates imported to App Gateways: + * **Azure role-based access control** - Create a Role Assignment that grants the Application/Service Principal the [Key Vault Secrets User](https://learn.microsoft.com/en-us/azure/key-vault/general/rbac-guide?tabs=azure-cli) built-in role. + * **Vault access policy** - [Create an Access Policy](https://learn.microsoft.com/en-us/azure/key-vault/general/assign-access-policy?tabs=azure-portal) that grants the Application/Service Principal the Get secret permission for each Azure Key Vault. + #### Client Certificate or Client Secret -The Basic tab should look like this: + Beginning in version 3.0.0, the Azure Application Gateway Orchestrator extension supports both [client certificate authentication](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) and [client secret](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-2-add-a-client-secret) authentication. -![AppGwBin Basic Tab](.github/images/AppGwBin-basic-store-type-dialog.png) + * **Client Secret** - Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-2-add-a-client-secret) to create a Client Secret. This secret will be used as the **Server Password** field in the [Certificate Store Configuration](#certificate-store-configuration) section. + * **Client Certificate** - Create a client certificate key pair with the Client Authentication extended key usage. The client certificate will be used in the ClientCertificate field in the [Certificate Store Configuration](#certificate-store-configuration) section. If you have access to Keyfactor Command, the instructions in this section walk you through enrolling a certificate and ensuring that it's in the correct format. Once enrolled, follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) to add the _public key_ certificate (no private key) to the service principal used for authentication. -### Advanced Tab -| Attribute | Value | Description | -| --------- | ----- | ----- | -| Supports Custom Alias | Required | Determines if an individual entry within a store can have a custom Alias. | -| Private Key Handling | Required | This determines if Keyfactor can send the private key associated with a certificate to the store. Required because IIS certificates without private keys would be invalid. | -| PFX Password Style | Default | 'Default' - PFX password is randomly generated, 'Custom' - PFX password may be specified when the enrollment job is created (Requires the Allow Custom Password application setting to be enabled.) | + The certificate can be in either of the following formats: + * Base64-encoded PKCS#12 (PFX) with a matching private key. + * Base64-encoded PEM-encoded certificate _and_ PEM-encoded PKCS8 private key. Make sure that the certificate and private key are separated with a newline. The order doesn't matter - the extension will determine which is which. + If the private key is encrypted, the encryption password will replace the **Server Password** field in the [Certificate Store Configuration](#certificate-store-configuration) section. -The Advanced tab should look like this: + > **Creating and Formatting a Client Certificate using Keyfactor Command** + > + > To get started quickly, you can follow the instructions below to create and properly format a client certificate to authenticate to the Microsoft Graph API. + > + > 1. In Keyfactor Command, hover over **Enrollment** and select **PFX Enrollment**. + > 2. Select a **Template** that supports Client Authentication as an extended key usage. + > 3. Populate the certificate subject as appropriate for the Template. It may be sufficient to only populate the Common Name, but consult your IT policy to ensure that this certificate is compliant. + > 4. At the bottom of the page, uncheck the box for **Include Chain**, and select either **PFX** or **PEM** as the certificate Format. + > 5. Make a note of the password on the next page - it won't be shown again. + > 6. Prepare the certificate and private key for Azure and the Orchestrator extension: + > * If you downloaded the certificate in PEM format, use the commands below: + > + > ```shell + > # Verify that the certificate downloaded from Command contains the certificate and private key. They should be in the same file + > cat + > + > # Separate the certificate from the private key + > openssl x509 -in -out pubkeycert.pem + > + > # Base64 encode the certificate and private key + > cat | base64 > clientcertkeypair.pem.base64 + > ``` + > + > * If you downloaded the certificate in PFX format, use the commands below: + > + > ```shell + > # Export the certificate from the PFX file + > openssl pkcs12 -in -clcerts -nokeys -out pubkeycert.pem + > + > # Base64 encode the PFX file + > cat | base64 > clientcert.pfx.base64 + > ``` + > 7. Follow [Microsoft's documentation](https://learn.microsoft.com/en-us/graph/auth-register-app-v2#option-1-add-a-certificate) to add the public key certificate to the service principal used for authentication. + > + > You will use `clientcert.[pem|pfx].base64` as the **ClientCertificate** field in the [Certificate Store Configuration](#certificate-store-configuration) section. -![AppGwBin Advanced Tab](.github/images/AppGwBin-advanced-store-type-dialog.png) -### Custom Fields Tab -Custom fields operate at the certificate store level and are used to control how the orchestrator connects to the remote target server containing the certificate store to be managed. The following custom fields should be added to the store type: -| Name | Display Name | Type | Default Value/Options | Required | Description | -| ---- | ------------ | ---- | --------------------- | -------- | ----------- | -| ServerUsername | Server Username | Secret | None | | Application ID of the service principal, representing the identity used for managing the Application Gateway. | -| ServerPassword | Server Password | Secret | None | | Secret of the service principal that will be used to manage the Application Gateway. | -| ServerUseSsl | Use SSL | Bool | true | ✓ | Indicates whether SSL usage is enabled for the connection. | -| AzureCloud | Azure Global Cloud Authority Host | MultipleChoice | public,china,germany,government | | Specifies the Azure Cloud instance used by the organization. | +
+2. Create Certificate Store Types for the Azure Application Gateway Orchestrator extension. -The Custom Fields tab should look like this: + * **Using kfutil**: -![AppGwBin Custom Fields Tab](.github/images/AppGwBin-custom-fields-store-type-dialog.png) + ```shell + # Azure Application Gateway Certificate Binding + kfutil store-types create AppGwBin + ``` -
+ * **Manually**: + * [Azure Application Gateway Certificate Binding](docs/appgwbin.md#certificate-store-type-configuration) -## Instantiating New Azure Application Gateway Orchestrator Stores -Once the store types have been created, you can instantiate certificate stores for any of the 2 store types. This section describes how to instantiate a certificate store for each store type. Creating new certificate stores is how certificates in the remote platform are inventoried and managed by the orchestrator. -
AzureAppGw +3. Install the Azure Application Gateway Universal Orchestrator extension. + + * **Using kfutil**: On the server that that hosts the Universal Orchestrator, run the following command: -In Keyfactor Command, navigate to Certificate Stores from the Locations Menu. Click the Add button to create a new Certificate Store using the settings defined below. + ```shell + # Windows Server + kfutil orchestrator extension -e azure-appgateway-orchestrator@latest --out "C:\Program Files\Keyfactor\Keyfactor Orchestrator\extensions" -| Attribute | Description | -| --------- | ----------- | -| Category | Select Azure Application Gateway Certificate or the customized certificate store name from the previous step. | -| Container | Optional container to associate certificate store with. | -| Client Machine | The Azure Tenant ID of the service principal, representing the Tenant ID where the Application/Service Principal is managed. | -| Store Path | Azure resource ID of the application gateway, following the format: `/subscriptions//resourceGroups//providers/Microsoft.Network/applicationGateways/`. | -| Orchestrator | Select an approved orchestrator capable of managing AzureAppGw certificates. Specifically, one with the AzureAppGw capability. | -| Server Username | Application ID of the service principal, representing the identity used for managing the Application Gateway. | -| Server Password | Secret of the service principal that will be used to manage the Application Gateway. | -| Use SSL | Indicates whether SSL usage is enabled for the connection. | -| Azure Global Cloud Authority Host | Specifies the Azure Cloud instance used by the organization. | + # Linux + kfutil orchestrator extension -e azure-appgateway-orchestrator@latest --out "/opt/keyfactor/orchestrator/extensions" + ``` + * **Manually**: Follow the [official Command documentation](https://software.keyfactor.com/Core-OnPrem/Current/Content/InstallingAgents/NetCoreOrchestrator/CustomExtensions.htm?Highlight=extensions) to install the latest [Azure Application Gateway Universal Orchestrator extension](https://github.com/Keyfactor/azure-appgateway-orchestrator/releases/latest). +4. Create new certificate stores in Keyfactor Command for the Sample Universal Orchestrator extension. + * [Azure Application Gateway Certificate Binding](docs/appgwbin.md#certificate-store-configuration)
-
AppGwBin -In Keyfactor Command, navigate to Certificate Stores from the Locations Menu. Click the Add button to create a new Certificate Store using the settings defined below. +## License -| Attribute | Description | -| --------- | ----------- | -| Category | Select Azure Application Gateway Certificate Binding or the customized certificate store name from the previous step. | -| Container | Optional container to associate certificate store with. | -| Client Machine | The Azure Tenant ID of the service principal, representing the Tenant ID where the Application/Service Principal is managed. | -| Store Path | Azure resource ID of the application gateway, following the format: `/subscriptions//resourceGroups//providers/Microsoft.Network/applicationGateways/`. | -| Orchestrator | Select an approved orchestrator capable of managing AppGwBin certificates. Specifically, one with the AzureAppGwBin capability. | -| Server Username | Application ID of the service principal, representing the identity used for managing the Application Gateway. | -| Server Password | Secret of the service principal that will be used to manage the Application Gateway. | -| Use SSL | Indicates whether SSL usage is enabled for the connection. | -| Azure Global Cloud Authority Host | Specifies the Azure Cloud instance used by the organization. | +Apache License 2.0, see [LICENSE](LICENSE). +## Related Integrations -
+See all [Keyfactor Universal Orchestrator extensions](https://github.com/orgs/Keyfactor/repositories?q=orchestrator). \ No newline at end of file