Skip to content

Commit

Permalink
Store secrets to encrypted storage
Browse files Browse the repository at this point in the history
  • Loading branch information
msJinLei committed Nov 17, 2022
1 parent ba2086f commit 6b227ba
Show file tree
Hide file tree
Showing 19 changed files with 772 additions and 36 deletions.
15 changes: 15 additions & 0 deletions src/Accounts/Accounts.Test/AutosaveTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@
using Xunit.Abstractions;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using System;
using System.Security;
using Microsoft.Azure.Commands.Profile.Context;
using Microsoft.Azure.Commands.ScenarioTest;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.Azure.Commands.TestFx.Mocks;
using Moq;

namespace Microsoft.Azure.Commands.Profile.Test
{
Expand All @@ -41,6 +43,18 @@ public AutosaveTests(ITestOutputHelper output)
ResetState();
}

private void SetMockedAzKeyStore()
{
var storageMocker = new Mock<IStorage>();
storageMocker.Setup(f => f.Create()).Returns(storageMocker.Object);
storageMocker.Setup(f => f.ReadData()).Returns(new byte[0]);
var keyStore = new AzKeyStore(AzureSession.Instance.ARMProfileDirectory, "keystore.cache", false, false, storageMocker.Object);
AzKeyStore.RegisterJsonConverter(typeof(ServicePrincipalKey), typeof(ServicePrincipalKey).Name);
AzKeyStore.RegisterJsonConverter(typeof(SecureString), typeof(SecureString).Name, new SecureStringConverter());
AzureSession.Instance.RegisterComponent(AzKeyStore.Name, () => keyStore);
keyStore.LoadStorage();
}

void ResetState()
{

Expand All @@ -54,6 +68,7 @@ void ResetState()
Environment.SetEnvironmentVariable("Azure_PS_Data_Collection", "false");
PowerShellTokenCacheProvider tokenProvider = new InMemoryTokenCacheProvider();
AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => tokenProvider, true);
SetMockedAzKeyStore();
}

[Fact]
Expand Down
20 changes: 12 additions & 8 deletions src/Accounts/Accounts/Account/ConnectAzureRmAccount.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@
using Microsoft.Azure.PowerShell.Common.Config;
using Microsoft.Identity.Client;
using Microsoft.WindowsAzure.Commands.Common;
using Microsoft.WindowsAzure.Commands.Common.CustomAttributes;
using Microsoft.WindowsAzure.Commands.Common.Utilities;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using Microsoft.Azure.PowerShell.Common.Share.Survey;
Expand Down Expand Up @@ -426,7 +425,6 @@ public override void ExecuteCmdlet()
azureAccount.SetProperty(AzureAccount.Property.CertificatePath, resolvedPath);
if (CertificatePassword != null)
{
azureAccount.SetProperty(AzureAccount.Property.CertificatePassword, CertificatePassword.ConvertToString());
keyStore?.SaveKey(new ServicePrincipalKey(AzureAccount.Property.CertificatePassword, azureAccount.Id, Tenant), CertificatePassword);
}
}
Expand All @@ -449,7 +447,6 @@ public override void ExecuteCmdlet()

if (azureAccount.Type == AzureAccount.AccountType.ServicePrincipal && password != null)
{
azureAccount.SetProperty(AzureAccount.Property.ServicePrincipalSecret, password.ConvertToString());
keyStore?.SaveKey(new ServicePrincipalKey(AzureAccount.Property.ServicePrincipalSecret
,azureAccount.Id, Tenant), password);
if (GetContextModificationScope() == ContextModificationScope.CurrentUser)
Expand Down Expand Up @@ -713,16 +710,23 @@ public void OnImport()
WriteInitializationWarnings(Resources.FallbackContextSaveModeDueCacheCheckError.FormatInvariant(ex.Message));
}

if(!InitializeProfileProvider(autoSaveEnabled))
AzKeyStore keyStore = null;
//AzureSession.Instance.KeyStoreFile
keyStore = new AzKeyStore(AzureSession.Instance.ARMProfileDirectory, "keystore.cache", false, autoSaveEnabled);
AzKeyStore.RegisterJsonConverter(typeof(ServicePrincipalKey), typeof(ServicePrincipalKey).Name);
AzKeyStore.RegisterJsonConverter(typeof(SecureString), typeof(SecureString).Name, new SecureStringConverter());
AzureSession.Instance.RegisterComponent(AzKeyStore.Name, () => keyStore);

if (!InitializeProfileProvider(autoSaveEnabled))
{
AzureSession.Instance.ARMContextSaveMode = ContextSaveMode.Process;
autoSaveEnabled = false;
}

#pragma warning disable CS0618 // Type or member is obsolete
var keyStore = new AzKeyStore(AzureRmProfileProvider.Instance.Profile);
#pragma warning restore CS0618 // Type or member is obsolete
AzureSession.Instance.RegisterComponent(AzKeyStore.Name, () => keyStore);
if (!keyStore.LoadStorage())
{
WriteInitializationWarnings(Resources.KeyStoreLoadingError);
}

IAuthenticatorBuilder builder = null;
if (!AzureSession.Instance.TryGetComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, out builder))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,11 @@ void DisableAutosave(IAzureSession session, bool writeAutoSaveFile, out ContextA
builder.Reset();
}

if (AzureSession.Instance.TryGetComponent(AzKeyStore.Name, out AzKeyStore keystore))
{
keystore.DisableAutoSaving();
}

if (writeAutoSaveFile)
{
FileUtilities.EnsureDirectoryExists(session.ProfileDirectory);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,12 @@ void EnableAutosave(IAzureSession session, bool writeAutoSaveFile, out ContextAu
AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => newCacheProvider, true);
}

if (AzureSession.Instance.TryGetComponent(AzKeyStore.Name, out AzKeyStore keystore))
{
keystore.Flush();
keystore.DisableAutoSaving();
}


if (writeAutoSaveFile)
{
Expand Down
11 changes: 10 additions & 1 deletion src/Accounts/Accounts/Properties/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/Accounts/Accounts/Properties/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -571,4 +571,7 @@
<value>The command {0} is part of Azure PowerShell module "{1}" and it is not installed. Run "Install-Module {1}" to install it.</value>
<comment>0: command being not found; 1: its module</comment>
</data>
<data name="KeyStoreLoadingError" xml:space="preserve">
<value>KeyStore cannot be loaded from storage. Please check the keystore file integrity or system compablity. The functions relate to context autosaving may be affected.</value>
</data>
</root>
31 changes: 30 additions & 1 deletion src/Accounts/Authentication.ResourceManager/AzureRmProfile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
using Microsoft.Azure.Commands.Common.Authentication.ResourceManager.Properties;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.Azure.Commands.ResourceManager.Common.Serialization;
using Microsoft.WindowsAzure.Commands.Common;

using Newtonsoft.Json;

Expand Down Expand Up @@ -205,15 +206,39 @@ private void Initialize(AzureRmProfile profile)
EnvironmentTable[environment.Key] = environment.Value;
}

AzKeyStore keystore = null;
AzureSession.Instance.TryGetComponent(AzKeyStore.Name, out keystore);

foreach (var context in profile.Contexts)
{
this.Contexts.Add(context.Key, context.Value);
this.Contexts.Add(context.Key, MigrateSecretToKeyStore(context.Value, keystore));
}

DefaultContextKey = profile.DefaultContextKey ?? (profile.Contexts.Any() ? null : "Default");
}
}

private IAzureContext MigrateSecretToKeyStore(IAzureContext context, AzKeyStore keystore)
{
if (keystore != null)
{
var account = context.Account;
if (account.IsPropertySet(AzureAccount.Property.ServicePrincipalSecret))
{
keystore?.SaveKey(new ServicePrincipalKey(AzureAccount.Property.ServicePrincipalSecret, account.Id, account.GetTenants().First())
, account.ExtendedProperties.GetProperty(AzureAccount.Property.ServicePrincipalSecret).ConvertToSecureString());
account.ExtendedProperties.Remove(AzureAccount.Property.ServicePrincipalSecret);
}
if (account.IsPropertySet(AzureAccount.Property.CertificatePassword))
{
keystore?.SaveKey(new ServicePrincipalKey(AzureAccount.Property.CertificatePassword, account.Id, account.GetTenants().First())
, account.ExtendedProperties.GetProperty(AzureAccount.Property.CertificatePassword).ConvertToSecureString());
account.ExtendedProperties.Remove(AzureAccount.Property.CertificatePassword);
}
}
return context;
}

private void LoadImpl(string contents)
{
}
Expand Down Expand Up @@ -311,6 +336,10 @@ public void Save(IFileProvider provider, bool serializeCache = true)
// so that previous data is overwritten
provider.Stream.SetLength(provider.Stream.Position);
}

AzKeyStore keystore = null;
AzureSession.Instance.TryGetComponent(AzKeyStore.Name, out keystore);
keystore?.Flush();
}
finally
{
Expand Down
Loading

0 comments on commit 6b227ba

Please sign in to comment.