Skip to content

appgw: validate cert only if certificateFile is specified in set ssl cert command #12794

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Sep 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions src/KeyVault/KeyVault/Models/KeyVaultDataServiceClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.KeyVault.Models;
using Microsoft.Azure.KeyVault.WebKey;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using KeyVaultProperties = Microsoft.Azure.Commands.KeyVault.Properties;

Expand All @@ -41,9 +43,8 @@ public KeyVaultDataServiceClient(IAuthenticationFactory authFactory, IAzureConte
if (context.Environment == null)
throw new ArgumentException(KeyVaultProperties.Resources.InvalidAzureEnvironment);

var credential = new DataServiceCredential(authFactory, context, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId);
this.keyVaultClient = new KeyVaultClient(credential.OnAuthentication);

ServiceClientCredentials clientCredentials = authFactory.GetServiceClientCredentials(context, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId);
this.keyVaultClient = AzureSession.Instance.ClientFactory.CreateCustomArmClient<KeyVaultClient>(clientCredentials);

this.vaultUriHelper = new VaultUriHelper(
context.Environment.GetEndpoint(AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix));
Expand Down
6 changes: 5 additions & 1 deletion src/Network/Network.Test/Network.Test.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<PsModuleName>Network</PsModuleName>
Expand All @@ -15,12 +15,16 @@
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Graph.RBAC" Version="3.4.0-preview" />
<PackageReference Include="Microsoft.Azure.Management.Network" Version="20.0.2-preview" />
<PackageReference Include="Microsoft.Azure.KeyVault" Version="3.0.5" />
<PackageReference Include="Microsoft.Azure.Management.KeyVault" Version="3.0.1" />
<PackageReference Include="Microsoft.Azure.Insights" Version="0.16.0-preview" />
<PackageReference Include="Microsoft.Azure.Management.Compute" Version="38.0.0" />
<PackageReference Include="Microsoft.Azure.Management.ContainerInstance" Version="2.0.0" />
<PackageReference Include="Microsoft.Azure.Management.PrivateDns" Version="1.0.0" />
<PackageReference Include="Microsoft.Azure.Management.Redis" Version="4.4.1" />
<PackageReference Include="Microsoft.Azure.Management.OperationalInsights" Version="0.21.0-preview" />
<PackageReference Include="Microsoft.Azure.Management.ManagedServiceIdentity" Version="0.10.0-preview" />
<PackageReference Include="Microsoft.Azure.Management.Storage" Version="17.2.0" />
</ItemGroup>

<ItemGroup>
Expand Down
26 changes: 26 additions & 0 deletions src/Network/Network.Test/ScenarioTests/ApplicationGatewayTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

using System;
using Microsoft.Azure.Commands.Network.Test.ScenarioTests;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Xunit;

Expand Down Expand Up @@ -66,6 +68,30 @@ public void TestApplicationGatewayCRUD3()
TestRunner.RunTestScript(string.Format("Test-ApplicationGatewayCRUD3 -baseDir '{0}'", AppDomain.CurrentDomain.BaseDirectory));
}

[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
[Trait(Category.Owner, NrpTeamAlias.nvadev)]
public void TestKeyVaultIntegrationTest()
{
string environmentConnectionString = Environment.GetEnvironmentVariable("TEST_CSM_ORGID_AUTHENTICATION");
string servicePrincipal = "fakefakefake";
if (!string.IsNullOrEmpty(environmentConnectionString))
{
var connectionInfo = new ConnectionString(Environment.GetEnvironmentVariable("TEST_CSM_ORGID_AUTHENTICATION"));
var mode = connectionInfo.GetValue<string>(ConnectionStringKeys.HttpRecorderModeKey);
if (mode == HttpRecorderMode.Playback.ToString())
{
servicePrincipal = HttpMockServer.GetVariable("spn", "fake");
}
else
{
servicePrincipal = connectionInfo.GetValue<string>(ConnectionStringKeys.ServicePrincipalKey);
HttpMockServer.Variables["spn"] = servicePrincipal;
}
}
TestRunner.RunTestScript(string.Format("Test-KeyVaultIntegrationTest -baseDir '{0}' -spn '{1}'", AppDomain.CurrentDomain.BaseDirectory, servicePrincipal));
}

[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
[Trait(Category.Owner, NrpTeamAlias.nvadev)]
Expand Down
134 changes: 134 additions & 0 deletions src/Network/Network.Test/ScenarioTests/ApplicationGatewayTests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -1390,6 +1390,140 @@ function Test-ApplicationGatewayCRUD3
}
}

<#
.SYNOPSIS
Application gateway v2 tests for key vault
#>
function Test-KeyVaultIntegrationTest
{
param
(
[string]$basedir = "./",
[string]$spn
)

# Setup
$location = Get-ProviderLocation "Microsoft.Network/applicationGateways" "West US 2"

$rgname = Get-ResourceGroupName
$appgwName = Get-ResourceName
$identityName = Get-ResourceName
$vnetName = Get-ResourceName
$gwSubnetName = Get-ResourceName
$publicIpName = Get-ResourceName
$gipconfigname = Get-ResourceName

$frontendPort01Name = Get-ResourceName
$fipconfigName = Get-ResourceName
$listener01Name = Get-ResourceName

$poolName = Get-ResourceName
$poolSetting01Name = Get-ResourceName

$rule01Name = Get-ResourceName

$keyVaultName = Get-ResourceName
$sslCert01Name = Get-ResourceName
$sslCert02Name = Get-ResourceName

try
{
# resource group
New-AzResourceGroup -Name $rgname -Location $location -Tags @{ testtag = "APPGw tag"}

# managed identity
$identity = New-AzUserAssignedIdentity -Name $identityName -Location $location -ResourceGroup $rgname

# keyvault
if ((Get-NetworkTestMode) -ne 'Playback')
{
New-AzKeyVault -Name $keyVaultName -ResourceGroupName $rgname -Location $location -EnableSoftDelete
Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName -ServicePrincipalName $spn -PermissionsToSecrets get -PermissionsToCertificates get,list,delete,create,import,update,managecontacts,getissuers,listissuers,setissuers,deleteissuers,manageissuers,recover,purge,backup,restore
Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName -ObjectId $identity.PrincipalId -PermissionsToSecrets get -BypassObjectIdValidation

$policy = New-AzKeyVaultCertificatePolicy -ValidityInMonths 12 `
-SubjectName "CN=www.app.com" -IssuerName self `
-RenewAtNumberOfDaysBeforeExpiry 30

$certificate01 = Add-AzKeyVaultCertificate -VaultName $keyVaultName -Name $sslCert01Name -CertificatePolicy $policy
$certificate02 = Add-AzKeyVaultCertificate -VaultName $keyVaultName -Name $sslCert02Name -CertificatePolicy $policy

Start-Sleep 30

$certificate01 = Get-AzKeyVaultCertificate -VaultName $keyVaultName -Name $sslCert01Name
$secretId01 = $certificate01.SecretId.Replace($certificate01.Version, "")

$certificate02 = Get-AzKeyVaultCertificate -VaultName $keyVaultName -Name $sslCert02Name
$secretId02 = $certificate02.SecretId.Replace($certificate02.Version, "")
}
else
{
$secretId01 = "https://$keyVaultName.vault.azure.net:443/secrets/$sslCert01Name/"
$secretId02 = "https://$keyVaultName.vault.azure.net:443/secrets/$sslCert02Name/"
}

# virtual network
$gwSubnet = New-AzVirtualNetworkSubnetConfig -Name $gwSubnetName -AddressPrefix 10.0.0.0/24
$vnet = New-AzVirtualNetwork -Name $vnetName -ResourceGroupName $rgname -Location $location -AddressPrefix 10.0.0.0/16 -Subnet $gwSubnet
$vnet = Get-AzVirtualNetwork -Name $vnetName -ResourceGroupName $rgname
$gwSubnet = Get-AzVirtualNetworkSubnetConfig -Name $gwSubnetName -VirtualNetwork $vnet

# public ip
$publicip = New-AzPublicIpAddress -ResourceGroupName $rgname -name $publicIpName -location $location -AllocationMethod Static -sku Standard

# ip configuration
$gipconfig = New-AzApplicationGatewayIPConfiguration -Name $gipconfigname -Subnet $gwSubnet

$fipconfig = New-AzApplicationGatewayFrontendIPConfig -Name $fipconfigName -PublicIPAddress $publicip
$fp01 = New-AzApplicationGatewayFrontendPort -Name $frontendPort01Name  -Port 80
$listener01 = New-AzApplicationGatewayHttpListener -Name $listener01Name -Protocol Http -FrontendIPConfiguration $fipconfig -FrontendPort $fp01

# backend part
$pool = New-AzApplicationGatewayBackendAddressPool -Name $poolName -BackendIPAddresses 10.0.0.1
$poolSetting01 = New-AzApplicationGatewayBackendHttpSettings -Name $poolSetting01Name -Port 80 -Protocol Http -CookieBasedAffinity Enabled -PickHostNameFromBackendAddress

# rule
$rule01 = New-AzApplicationGatewayRequestRoutingRule -Name $rule01Name -RuleType basic -BackendHttpSettings $poolSetting01 -HttpListener $listener01 -BackendAddressPool $pool

# sku
$sku = New-AzApplicationGatewaySku -Name Standard_v2 -Tier Standard_v2 -Capacity 2

# appgw identity
$appgwIdentity = New-AzApplicationGatewayIdentity -UserAssignedIdentity $identity.Id

# ssl cert
$sslCert01 = New-AzApplicationGatewaySslCertificate -Name $sslCert01Name -KeyVaultSecretId $secretId01

# create
$appgw = New-AzApplicationGateway -Sku $sku -Identity $appgwIdentity -Name $appgwName -ResourceGroupName $rgname -Zone 1,2 -Location $location `
-BackendAddressPools $pool -BackendHttpSettingsCollection $poolSetting01 `
-FrontendIpConfigurations $fipconfig -GatewayIpConfigurations $gipconfig -FrontendPorts $fp01 -HttpListeners $listener01 `
-SslCertificates $sslCert01 `
-RequestRoutingRules $rule01

Assert-AreEqual $appgw.SslCertificates.Count 1
Assert-AreEqual $appgw.SslCertificates[0].KeyVaultSecretId $secretId01

# modify the certificate
$appgw = Set-AzApplicationGatewaySslCertificate -Name $sslCert01Name -KeyVaultSecretId $secretId02 -ApplicationGateway $appgw
$result = Set-AzApplicationGateway -ApplicationGateway $appgw

Assert-AreEqual $result.SslCertificates[0].KeyVaultSecretId $secretId02

$result = Remove-AzApplicationGatewaySslCertificate -Name $sslCert01Name -ApplicationGateway $result

Assert-AreEqual $result.SslCertificates.Count 0

# delete
Remove-AzApplicationGateway -Name $appgwName -ResourceGroupName $rgname -Force
}
finally
{
# Cleanup
Clean-ResourceGroup $rgname
}
}

<#
.SYNOPSIS
Compare connectionDraining of backendhttpsettings
Expand Down
95 changes: 94 additions & 1 deletion src/Network/Network.Test/ScenarioTests/NetworkTestRunner.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using Microsoft.Azure.Commands.TestFx;
using Microsoft.Azure.Internal.Common;
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Internal.Resources;
using Microsoft.Azure.Management.KeyVault;
using Microsoft.Azure.Management.ManagedServiceIdentity;
using Microsoft.Azure.Management.Network;
using Microsoft.Azure.Management.PrivateDns;
using Microsoft.Azure.Management.Storage;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Xunit.Abstractions;

namespace Microsoft.Azure.Commands.Network.Test.ScenarioTests
Expand Down Expand Up @@ -28,6 +42,7 @@ protected NetworkTestRunner(ITestOutputHelper output)
helper.GetRMModulePath("AzureRM.Sql.psd1"),
helper.GetRMModulePath("AzureRM.ContainerInstance.psd1"),
helper.GetRMModulePath("AzureRM.OperationalInsights.psd1"),
helper.GetRMModulePath("AzureRM.KeyVault.psd1"),
helper.GetRMModulePath("AzureRM.ManagedServiceIdentity.psd1"),
helper.GetRMModulePath("AzureRM.PrivateDns.psd1"),
})
Expand All @@ -44,11 +59,89 @@ protected NetworkTestRunner(ITestOutputHelper output)
{"Microsoft.Authorization", null},
{"Microsoft.Storage", null},
{"Microsoft.Sql", null},
{"Microsoft.KeyVault", null},
{"Microsoft.ManagedServiceIdentity", null},
{"Microsoft.PrivateDns", null},
}
).WithManagementClients(
GetResourceManagementClient,
GetManagedServiceIdentityClient,
GetKeyVaultManagementClient,
GetNetworkManagementClient,
GetComputeManagementClient,
GetStorageManagementClient,
GetKeyVaultClient,
GetAzureRestClient,
GetPrivateDnsManagementClient
)
.Build();
}

private static ResourceManagementClient GetResourceManagementClient(MockContext context)
{
return context.GetServiceClient<ResourceManagementClient>(TestEnvironmentFactory.GetTestEnvironment());
}

private static ManagedServiceIdentityClient GetManagedServiceIdentityClient(MockContext context)
{
return context.GetServiceClient<ManagedServiceIdentityClient>(TestEnvironmentFactory.GetTestEnvironment());
}

private static KeyVaultManagementClient GetKeyVaultManagementClient(MockContext context)
{
return context.GetServiceClient<KeyVaultManagementClient>(TestEnvironmentFactory.GetTestEnvironment());
}

private static NetworkManagementClient GetNetworkManagementClient(MockContext context)
{
return context.GetServiceClient<NetworkManagementClient>(TestEnvironmentFactory.GetTestEnvironment());
}

private static ComputeManagementClient GetComputeManagementClient(MockContext context)
{
return context.GetServiceClient<ComputeManagementClient>(TestEnvironmentFactory.GetTestEnvironment());
}

private static StorageManagementClient GetStorageManagementClient(MockContext context)
{
return context.GetServiceClient<StorageManagementClient>(TestEnvironmentFactory.GetTestEnvironment());
}

private static AzureRestClient GetAzureRestClient(MockContext context)
{
return context.GetServiceClient<AzureRestClient>(TestEnvironmentFactory.GetTestEnvironment());
}

private static PrivateDnsManagementClient GetPrivateDnsManagementClient(MockContext context)
{
return context.GetServiceClient<PrivateDnsManagementClient>(TestEnvironmentFactory.GetTestEnvironment());
}

private static KeyVaultClient GetKeyVaultClient(MockContext context)
{
string environmentConnectionString = Environment.GetEnvironmentVariable("TEST_CSM_ORGID_AUTHENTICATION");
string accessToken = "fakefakefake";

// When recording, we should have a connection string passed into the code from the environment
if (!string.IsNullOrEmpty(environmentConnectionString))
{
// Gather test client credential information from the environment
var connectionInfo = new ConnectionString(Environment.GetEnvironmentVariable("TEST_CSM_ORGID_AUTHENTICATION"));
var mode = connectionInfo.GetValue<string>(ConnectionStringKeys.HttpRecorderModeKey);
if (mode == HttpRecorderMode.Record.ToString())
{
string servicePrincipal = connectionInfo.GetValue<string>(ConnectionStringKeys.ServicePrincipalKey);
string servicePrincipalSecret = connectionInfo.GetValue<string>(ConnectionStringKeys.ServicePrincipalSecretKey);
string aadTenant = connectionInfo.GetValue<string>(ConnectionStringKeys.AADTenantKey);

// Create credentials
var clientCredentials = new ClientCredential(servicePrincipal, servicePrincipalSecret);
var authContext = new AuthenticationContext($"https://login.windows.net/{aadTenant}", TokenCache.DefaultShared);
accessToken = authContext.AcquireTokenAsync("https://vault.azure.net", clientCredentials).Result.AccessToken;
}
}

return new KeyVaultClient(new TokenCredentials(accessToken), HttpMockServer.CreateInstance());
}
}
}
Loading