Skip to content

Commit

Permalink
Support reading existing DataProtection KeyVault keys (#14778)
Browse files Browse the repository at this point in the history
  • Loading branch information
pakrym authored Sep 2, 2020
1 parent 6171954 commit 53f6dbb
Show file tree
Hide file tree
Showing 8 changed files with 354 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
# Release History

## 1.1.0-preview.1 (Unreleased)
## 1.0.2 (2020-09-01)

### Fixed

- Support reading keys created by a previous version of Azure KeyVault Keys DataProtection library.

## 1.0.1 (2020-08-06)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<PropertyGroup>
<Description>Microsoft Azure Key Vault key encryption support.</Description>
<PackageTags>aspnetcore;dataprotection;azure;keyvault</PackageTags>
<Version>1.1.0-preview.1</Version>
<Version>1.0.2</Version>
<ApiCompatVersion>1.0.1</ApiCompatVersion>
<IsExtensionClientLibrary>true</IsExtensionClientLibrary>
<NoWarn>$(NoWarn);AZC0102</NoWarn>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Azure.Core;
using Azure.Core.Cryptography;
using Azure.Security.KeyVault.Keys.Cryptography;
using Microsoft.AspNetCore.DataProtection.Internal;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.Extensions.DependencyInjection;

Expand Down Expand Up @@ -45,6 +46,7 @@ public static IDataProtectionBuilder ProtectKeysWithAzureKeyVault(this IDataProt
Argument.AssertNotNullOrEmpty(keyIdentifier, nameof(keyIdentifier));

builder.Services.AddSingleton<IKeyEncryptionKeyResolver>(keyResolver);
builder.Services.AddSingleton<IActivator, DecryptorTypeForwardingActivator>();
builder.Services.Configure<KeyManagementOptions>(options =>
{
options.XmlEncryptor = new AzureKeyVaultXmlEncryptor(keyResolver, keyIdentifier);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ private async Task<EncryptedXmlInfo> EncryptAsync(XElement plaintextElement)
var wrappedKey = await key.WrapKeyAsync(DefaultKeyEncryption, symmetricKey).ConfigureAwait(false);

var element = new XElement("encryptedKey",
new XComment(" This key is encrypted with Azure KeyVault. "),
new XComment(" This key is encrypted with Azure Key Vault. "),
new XElement("kid", key.KeyId),
new XElement("key", Convert.ToBase64String(wrappedKey)),
new XElement("iv", Convert.ToBase64String(symmetricIV)),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.DataProtection.Internal;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;

#pragma warning disable AZC0001
namespace Microsoft.AspNetCore.DataProtection
#pragma warning restore AZC0001
{
/// <summary>
/// This type is a copy of https://github.com/dotnet/aspnetcore/blob/e1bf38ccaf2a98f95e48bf22b8b76d996a0c33ea/src/DataProtection/DataProtection/test/TypeForwardingActivatorTests.cs
/// with addition of AzureKeyVaultXmlDecryptor forwarding logic.
/// </summary>
internal class DecryptorTypeForwardingActivator : IActivator
{
private readonly IServiceProvider _services;
private const string OldNamespace = "Microsoft.AspNet.DataProtection";
private const string CurrentNamespace = "Microsoft.AspNetCore.DataProtection";
private const string CurrentAzureNamespace = "Azure.Extensions.AspNetCore.DataProtection.Keys";

private const string OldDecryptor = "Microsoft.AspNetCore.DataProtection.AzureKeyVault.AzureKeyVaultXmlDecryptor";
private const string OldDecryptorAssembly = "Microsoft.AspNetCore.DataProtection.AzureKeyVault";
private const string NewDecryptor = "Azure.Extensions.AspNetCore.DataProtection.Keys.AzureKeyVaultXmlDecryptor";
private const string NewDecryptorAssembly = "Azure.Extensions.AspNetCore.DataProtection.Keys";

private readonly ILogger _logger;
private static readonly Regex _versionPattern = new Regex(@",\s?Version=[0-9]+(\.[0-9]+){0,3}", RegexOptions.Compiled, TimeSpan.FromSeconds(2));
private static readonly Regex _tokenPattern = new Regex(@",\s?PublicKeyToken=[\w\d]+", RegexOptions.Compiled, TimeSpan.FromSeconds(2));

public DecryptorTypeForwardingActivator(IServiceProvider services)
: this(services, NullLoggerFactory.Instance)
{
}

public DecryptorTypeForwardingActivator(IServiceProvider services, ILoggerFactory loggerFactory)
{
_services = services;
_logger = loggerFactory.CreateLogger(typeof(DecryptorTypeForwardingActivator));
}

public object CreateInstance(Type expectedBaseType, string originalTypeName)
=> CreateInstance(expectedBaseType, originalTypeName, out var _);

// for testing
internal object CreateInstance(Type expectedBaseType, string originalTypeName, out bool forwarded)
{
var forwardedTypeName = originalTypeName;
var candidate = false;
if (originalTypeName.Contains(OldNamespace))
{
candidate = true;
forwardedTypeName = originalTypeName.Replace(OldNamespace, CurrentNamespace);
}

if (originalTypeName.Contains(OldDecryptor))
{
candidate = true;
forwardedTypeName = originalTypeName
.Replace(OldDecryptor, NewDecryptor)
.Replace(OldDecryptorAssembly, NewDecryptorAssembly);
}

if ((candidate || forwardedTypeName.StartsWith(CurrentNamespace + ".", StringComparison.Ordinal)) ||
forwardedTypeName.StartsWith(CurrentAzureNamespace + ".", StringComparison.Ordinal))
{
candidate = true;
forwardedTypeName = RemoveVersionFromAssemblyName(forwardedTypeName);
forwardedTypeName = RemovePublicKeyTokenFromAssemblyName(forwardedTypeName);
}

if (candidate)
{
var type = Type.GetType(forwardedTypeName, false);
if (type != null)
{
_logger.LogDebug("Forwarded activator type request from {FromType} to {ToType}",
originalTypeName,
forwardedTypeName);
forwarded = true;
return CreateInstanceImpl(expectedBaseType, forwardedTypeName);
}
}

forwarded = false;
return CreateInstanceImpl(expectedBaseType, originalTypeName);
}

private static string RemovePublicKeyTokenFromAssemblyName(string forwardedTypeName)
=> _tokenPattern.Replace(forwardedTypeName, "");

internal static string RemoveVersionFromAssemblyName(string forwardedTypeName)
=> _versionPattern.Replace(forwardedTypeName, "");

private object CreateInstanceImpl(Type expectedBaseType, string implementationTypeName)
{
// Would the assignment even work?
var implementationType = Type.GetType(implementationTypeName, throwOnError: true);

if (!expectedBaseType.IsAssignableFrom(implementationType))
{
// It might seem a bit strange to throw an InvalidCastException explicitly rather than
// to let the CLR generate one, but searching through NetFX there is indeed precedent
// for this pattern when the caller knows ahead of time the operation will fail.
throw new InvalidCastException($"The type '{implementationType.AssemblyQualifiedName}' is not assignable to '{expectedBaseType.AssemblyQualifiedName}'.");
}

// If no IServiceProvider was specified, prefer .ctor() [if it exists]
if (_services == null)
{
var ctorParameterless = implementationType.GetConstructor(Type.EmptyTypes);
if (ctorParameterless != null)
{
return Activator.CreateInstance(implementationType);
}
}

// If an IServiceProvider was specified or if .ctor() doesn't exist, prefer .ctor(IServiceProvider) [if it exists]
var ctorWhichTakesServiceProvider = implementationType.GetConstructor(new Type[] { typeof(IServiceProvider) });
if (ctorWhichTakesServiceProvider != null)
{
return ctorWhichTakesServiceProvider.Invoke(new[] { _services });
}

// Finally, prefer .ctor() as an ultimate fallback.
// This will throw if the ctor cannot be called.
return Activator.CreateInstance(implementationType);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Moq" />

<PackageReference Include="Microsoft.AspNetCore.DataProtection.AzureKeyVault" VersionOverride="3.1.7" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;

namespace Azure.Extensions.AspNetCore.DataProtection.Blobs.Tests
namespace Azure.Extensions.AspNetCore.DataProtection.Keys.Tests
{
public class DataProtectionKeysFunctionalTests
{
Expand Down Expand Up @@ -55,7 +55,59 @@ public async Task ProtectsKeysWithKeyVaultKey()

foreach (var element in testKeyRepository.GetAllElements())
{
StringAssert.Contains("This key is encrypted with Azure KeyVault", element.ToString());
StringAssert.Contains("This key is encrypted with Azure Key Vault", element.ToString());
}
}

[Test]
[Category("Live")]
public async Task CanUprotectExistingKeys()
{
var credential = new ClientSecretCredential(
DataProtectionTestEnvironment.Instance.TenantId,
DataProtectionTestEnvironment.Instance.ClientId,
DataProtectionTestEnvironment.Instance.ClientSecret);
var client = new KeyClient(new Uri(DataProtectionTestEnvironment.Instance.KeyVaultUrl), credential);
var key = await client.CreateKeyAsync("TestEncryptionKey2", KeyType.Rsa);

var serviceCollection = new ServiceCollection();

var testKeyRepository = new TestKeyRepository();

AzureDataProtectionBuilderExtensions.ProtectKeysWithAzureKeyVault(
serviceCollection.AddDataProtection(),
key.Value.Id.AbsoluteUri,
DataProtectionTestEnvironment.Instance.ClientId,
DataProtectionTestEnvironment.Instance.ClientSecret);

serviceCollection.Configure<KeyManagementOptions>(options =>
{
options.XmlRepository = testKeyRepository;
});

var servicesOld = serviceCollection.BuildServiceProvider();

var serviceCollectionNew = new ServiceCollection();
serviceCollectionNew.AddDataProtection().ProtectKeysWithAzureKeyVault(key.Value.Id, credential);
serviceCollectionNew.Configure<KeyManagementOptions>(options =>
{
options.XmlRepository = testKeyRepository;
});

var dataProtector = servicesOld.GetService<IDataProtectionProvider>().CreateProtector("Fancy purpose");
var protectedText = dataProtector.Protect("Hello world!");

var newServices = serviceCollectionNew.BuildServiceProvider();
var newDataProtectionProvider = newServices.GetService<IDataProtectionProvider>().CreateProtector("Fancy purpose");
var unprotectedText = newDataProtectionProvider.Unprotect(protectedText);

Assert.AreEqual("Hello world!", unprotectedText);

// double check that keys were protected with KeyVault

foreach (var element in testKeyRepository.GetAllElements())
{
StringAssert.Contains("This key is encrypted with Azure", element.ToString());
}
}

Expand Down
Loading

0 comments on commit 53f6dbb

Please sign in to comment.