Skip to content
This repository was archived by the owner on Oct 17, 2018. It is now read-only.

Add event ids to all publication sites #105

Closed
wants to merge 1 commit into from
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ private BCryptAlgorithmHandle GetHmacAlgorithmHandle(ILogger logger)

if (logger.IsVerboseLevelEnabled())
{
logger.LogVerboseF($"Opening CNG algorithm '{HashAlgorithm}' from provider '{HashAlgorithmProvider}' with HMAC.");
logger.LogVerbose(DataProtectionEventId.CngCbcAuthenticatedEncryptionOptions, $"Opening CNG algorithm '{HashAlgorithm}' from provider '{HashAlgorithmProvider}' with HMAC.");
}

BCryptAlgorithmHandle algorithmHandle = null;
Expand Down Expand Up @@ -154,7 +154,7 @@ private BCryptAlgorithmHandle GetSymmetricBlockCipherAlgorithmHandle(ILogger log

if (logger.IsVerboseLevelEnabled())
{
logger.LogVerboseF($"Opening CNG algorithm '{EncryptionAlgorithm}' from provider '{EncryptionAlgorithmProvider}' with chaining mode CBC.");
logger.LogVerbose(DataProtectionEventId.CngCbcAuthenticatedEncryptionOptions, $"Opening CNG algorithm '{EncryptionAlgorithm}' from provider '{EncryptionAlgorithmProvider}' with chaining mode CBC.");
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Event ids should typically be unique within a single logging "category". Suggest you create specific ids for Hmac and SymmetricBlockCipher code paths.

}

BCryptAlgorithmHandle algorithmHandle = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ private BCryptAlgorithmHandle GetSymmetricBlockCipherAlgorithmHandle(ILogger log

if (logger.IsVerboseLevelEnabled())
{
logger.LogVerboseF($"Opening CNG algorithm '{EncryptionAlgorithm}' from provider '{EncryptionAlgorithmProvider}' with chaining mode GCM.");
logger.LogVerbose(DataProtectionEventId.CngGcmAuthenticatedEncryptionOptions, $"Opening CNG algorithm '{EncryptionAlgorithm}' from provider '{EncryptionAlgorithmProvider}' with chaining mode GCM.");
}

// Special-case cached providers
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ private Func<KeyedHashAlgorithm> GetKeyedHashAlgorithmFactory(ILogger logger)

if (logger.IsVerboseLevelEnabled())
{
logger.LogVerboseF($"Using managed keyed hash algorithm '{ValidationAlgorithmType.FullName}'.");
logger.LogVerbose(DataProtectionEventId.ManagedAuthenticatedEncryptionOptions, $"Using managed keyed hash algorithm '{ValidationAlgorithmType.FullName}'.");
}

if (ValidationAlgorithmType == typeof(HMACSHA256))
Expand Down Expand Up @@ -120,7 +120,7 @@ private Func<SymmetricAlgorithm> GetSymmetricBlockCipherAlgorithmFactory(ILogger

if (logger.IsVerboseLevelEnabled())
{
logger.LogVerboseF($"Using managed symmetric algorithm '{EncryptionAlgorithmType.FullName}'.");
logger.LogVerbose(DataProtectionEventId.ManagedAuthenticatedEncryptionOptions, $"Using managed symmetric algorithm '{EncryptionAlgorithmType.FullName}'.");
}

if (EncryptionAlgorithmType == typeof(Aes))
Expand Down
27 changes: 27 additions & 0 deletions src/Microsoft.AspNet.DataProtection/DataProtectionEventId.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

namespace Microsoft.AspNet.DataProtection
{
public enum DataProtectionEventId
{
KeyServices = 1,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See the PRs that I mentioned for our logging style. It's more clear

XmlKeyManager,
KeyRingProvider,
CertificateXmlEncryptor,
DpapiNGXmlEncryptor,
DpapiNGXmlDecryptor,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another con for enums: if you remove an item, all those that follow will get a different value

DpapiXmlEncryptor,
DpapiXmlDecryptor,
NullXmlDecryptor,
DefaultKeyResolver,
RegistryXmlRepository,
EphemeralXmlRepository,
FileSystemXmlRepository,
KeyRingBasedDataProtector,
EphemeralDataProtectionProvider,
CngGcmAuthenticatedEncryptionOptions,
ManagedAuthenticatedEncryptionOptions,
CngCbcAuthenticatedEncryptionOptions
}
}
10 changes: 5 additions & 5 deletions src/Microsoft.AspNet.DataProtection/DataProtectionServices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public static IEnumerable<ServiceDescriptor> GetDefaultServices()
{
if (log.IsInformationLevelEnabled())
{
log.LogInformationF($"Azure Web Sites environment detected. Using '{azureWebSitesKeysFolder.FullName}' as key repository; keys will not be encrypted at rest.");
log.LogInformation(DataProtectionEventId.KeyServices, $"Azure Web Sites environment detected. Using '{azureWebSitesKeysFolder.FullName}' as key repository; keys will not be encrypted at rest.");
}

// Cloud DPAPI isn't yet available, so we don't encrypt keys at rest.
Expand All @@ -69,11 +69,11 @@ public static IEnumerable<ServiceDescriptor> GetDefaultServices()
{
if (keyEncryptorDescriptor != null)
{
log.LogInformationF($"User profile is available. Using '{localAppDataKeysFolder.FullName}' as key repository and Windows DPAPI to encrypt keys at rest.");
log.LogInformation(DataProtectionEventId.KeyServices, $"User profile is available. Using '{localAppDataKeysFolder.FullName}' as key repository and Windows DPAPI to encrypt keys at rest.");
}
else
{
log.LogInformationF($"User profile is available. Using '{localAppDataKeysFolder.FullName}' as key repository; keys will not be encrypted at rest.");
log.LogInformation(DataProtectionEventId.KeyServices, $"User profile is available. Using '{localAppDataKeysFolder.FullName}' as key repository; keys will not be encrypted at rest.");
}
}
}
Expand All @@ -93,7 +93,7 @@ public static IEnumerable<ServiceDescriptor> GetDefaultServices()

if (log.IsInformationLevelEnabled())
{
log.LogInformationF($"User profile not available. Using '{regKeyStorageKey.Name}' as key repository and Windows DPAPI to encrypt keys at rest.");
log.LogInformation(DataProtectionEventId.KeyServices, $"User profile not available. Using '{regKeyStorageKey.Name}' as key repository and Windows DPAPI to encrypt keys at rest.");
}
}
else
Expand All @@ -104,7 +104,7 @@ public static IEnumerable<ServiceDescriptor> GetDefaultServices()

if (log.IsWarningLevelEnabled())
{
log.LogWarning("Neither user profile nor HKLM registry available. Using an ephemeral key repository. Protected data will be unavailable when application exits.");
log.LogWarning(DataProtectionEventId.KeyServices, $"Neither user profile nor HKLM registry available. Using an ephemeral key repository. Protected data will be unavailable when application exits.");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public EphemeralDataProtectionProvider(IServiceProvider services)
var logger = services.GetLogger<EphemeralDataProtectionProvider>();
if (logger.IsWarningLevelEnabled())
{
logger.LogWarning("Using ephemeral data protection provider. Payloads will be undecipherable upon application shutdown.");
logger.LogWarning(DataProtectionEventId.EphemeralDataProtectionProvider, $"Using ephemeral data protection provider. Payloads will be undecipherable upon application shutdown.");
}

_dataProtectionProvider = new KeyRingBasedDataProtectionProvider(keyringProvider, services);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ private bool CanCreateAuthenticatedEncryptor(IKey key)
{
if (_logger.IsWarningLevelEnabled())
{
_logger.LogWarningF(ex, $"Key {key.KeyId:B} is ineligible to be the default key because its {nameof(IKey.CreateEncryptorInstance)} method failed.");
_logger.LogWarning(DataProtectionEventId.DefaultKeyResolver, ex, $"Key {key.KeyId:B} is ineligible to be the default key because its {nameof(IKey.CreateEncryptorInstance)} method failed.");
}
return false;
}
Expand All @@ -74,15 +74,15 @@ private IKey FindDefaultKey(DateTimeOffset now, IEnumerable<IKey> allKeys, out I
{
if (_logger.IsVerboseLevelEnabled())
{
_logger.LogVerboseF($"Considering key {preferredDefaultKey.KeyId:B} with expiration date {preferredDefaultKey.ExpirationDate:u} as default key.");
_logger.LogVerbose(DataProtectionEventId.DefaultKeyResolver, $"Considering key {preferredDefaultKey.KeyId:B} with expiration date {preferredDefaultKey.ExpirationDate:u} as default key.");
}

// if the key has been revoked or is expired, it is no longer a candidate
if (preferredDefaultKey.IsRevoked || preferredDefaultKey.IsExpired(now) || !CanCreateAuthenticatedEncryptor(preferredDefaultKey))
{
if (_logger.IsVerboseLevelEnabled())
{
_logger.LogVerboseF($"Key {preferredDefaultKey.KeyId:B} is no longer under consideration as default key because it is expired, revoked, or cannot be deciphered.");
_logger.LogVerbose(DataProtectionEventId.DefaultKeyResolver, $"Key {preferredDefaultKey.KeyId:B} is no longer under consideration as default key because it is expired, revoked, or cannot be deciphered.");
}
preferredDefaultKey = null;
}
Expand All @@ -106,7 +106,7 @@ private IKey FindDefaultKey(DateTimeOffset now, IEnumerable<IKey> allKeys, out I

if (callerShouldGenerateNewKey && _logger.IsVerboseLevelEnabled())
{
_logger.LogVerbose("Default key expiration imminent and repository contains no viable successor. Caller should generate a successor.");
_logger.LogVerbose(DataProtectionEventId.DefaultKeyResolver, "Default key expiration imminent and repository contains no viable successor. Caller should generate a successor.");
}

fallbackKey = null;
Expand All @@ -129,7 +129,7 @@ orderby key.CreationDate ascending

if (_logger.IsVerboseLevelEnabled())
{
_logger.LogVerbose("Repository contains no viable default key. Caller should generate a key with immediate activation.");
_logger.LogVerbose(DataProtectionEventId.DefaultKeyResolver, "Repository contains no viable default key. Caller should generate a key with immediate activation.");
}

callerShouldGenerateNewKey = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public byte[] Protect(byte[] plaintext)

if (_logger.IsDebugLevelEnabled())
{
_logger.LogDebugF($"Performing protect operation to key {defaultKeyId:B} with purposes {JoinPurposesForLog(Purposes)}.");
_logger.LogDebug(DataProtectionEventId.KeyRingBasedDataProtector, $"Performing protect operation to key {defaultKeyId:B} with purposes {JoinPurposesForLog(Purposes)}.");
}

// We'll need to apply the default key id to the template if it hasn't already been applied.
Expand Down Expand Up @@ -236,7 +236,7 @@ private byte[] UnprotectCore(byte[] protectedData, bool allowOperationsOnRevoked

if (_logger.IsDebugLevelEnabled())
{
_logger.LogDebugF($"Performing unprotect operation to key {keyIdFromPayload:B} with purposes {JoinPurposesForLog(Purposes)}.");
_logger.LogDebug(DataProtectionEventId.KeyRingBasedDataProtector, $"Performing unprotect operation to key {keyIdFromPayload:B} with purposes {JoinPurposesForLog(Purposes)}.");
}

// Find the correct encryptor in the keyring.
Expand All @@ -247,7 +247,7 @@ private byte[] UnprotectCore(byte[] protectedData, bool allowOperationsOnRevoked
{
if (_logger.IsDebugLevelEnabled())
{
_logger.LogDebugF($"Key {keyIdFromPayload:B} was not found in the key ring. Unprotect operation cannot proceed.");
_logger.LogDebug(DataProtectionEventId.KeyRingBasedDataProtector, $"Key {keyIdFromPayload:B} was not found in the key ring. Unprotect operation cannot proceed.");
}
throw Error.Common_KeyNotFound(keyIdFromPayload);
}
Expand All @@ -266,15 +266,15 @@ private byte[] UnprotectCore(byte[] protectedData, bool allowOperationsOnRevoked
{
if (_logger.IsVerboseLevelEnabled())
{
_logger.LogVerboseF($"Key {keyIdFromPayload:B} was revoked. Caller requested unprotect operation proceed regardless.");
_logger.LogVerbose(DataProtectionEventId.KeyRingBasedDataProtector, $"Key {keyIdFromPayload:B} was revoked. Caller requested unprotect operation proceed regardless.");
}
status = UnprotectStatus.DecryptionKeyWasRevoked;
}
else
{
if (_logger.IsVerboseLevelEnabled())
{
_logger.LogVerboseF($"Key {keyIdFromPayload:B} was revoked. Unprotect operation cannot proceed.");
_logger.LogVerbose(DataProtectionEventId.KeyRingBasedDataProtector, $"Key {keyIdFromPayload:B} was revoked. Unprotect operation cannot proceed.");
}
throw Error.Common_KeyRevoked(keyIdFromPayload);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ private CacheableKeyRing CreateCacheableKeyRingCore(DateTimeOffset now, IKey key

if (_logger.IsVerboseLevelEnabled())
{
_logger.LogVerbose("Policy resolution states that a new key should be added to the key ring.");
_logger.LogVerbose(DataProtectionEventId.KeyRingProvider, "Policy resolution states that a new key should be added to the key ring.");
}

// We shouldn't call CreateKey more than once, else we risk stack diving. This code path shouldn't
Expand All @@ -71,15 +71,15 @@ private CacheableKeyRing CreateCacheableKeyRingCore(DateTimeOffset now, IKey key
{
if (_logger.IsErrorLevelEnabled())
{
_logger.LogError("The key ring does not contain a valid default key, and the key manager is configured with auto-generation of keys disabled.");
_logger.LogError(DataProtectionEventId.KeyRingProvider, "The key ring does not contain a valid default key, and the key manager is configured with auto-generation of keys disabled.");
}
throw new InvalidOperationException(Resources.KeyRingProvider_NoDefaultKey_AutoGenerateDisabled);
}
else
{
if (_logger.IsWarningLevelEnabled())
{
_logger.LogWarningF($"Policy resolution states that a new key should be added to the key ring, but automatic generation of keys is disabled. Using fallback key {keyToUse.KeyId:B} with expiration {keyToUse.ExpirationDate:u} as default key.");
_logger.LogWarning(DataProtectionEventId.KeyRingProvider, $"Policy resolution states that a new key should be added to the key ring, but automatic generation of keys is disabled. Using fallback key {keyToUse.KeyId:B} with expiration {keyToUse.ExpirationDate:u} as default key.");
}
return CreateCacheableKeyRingCoreStep2(now, cacheExpirationToken, keyToUse, allKeys);
}
Expand Down Expand Up @@ -111,7 +111,7 @@ private CacheableKeyRing CreateCacheableKeyRingCoreStep2(DateTimeOffset now, Can

if (_logger.IsVerboseLevelEnabled())
{
_logger.LogVerboseF($"Using key {defaultKey.KeyId:B} as the default key.");
_logger.LogVerbose(DataProtectionEventId.KeyRingProvider, $"Using key {defaultKey.KeyId:B} as the default key.");
}

DateTimeOffset nextAutoRefreshTime = now + GetRefreshPeriodWithJitter(_keyManagementOptions.KeyRingRefreshPeriod);
Expand Down Expand Up @@ -167,7 +167,7 @@ internal IKeyRing GetCurrentKeyRingCore(DateTime utcNow)

if (existingCacheableKeyRing != null && _logger.IsVerboseLevelEnabled())
{
_logger.LogVerbose("Existing cached key ring is expired. Refreshing.");
_logger.LogVerbose(DataProtectionEventId.KeyRingProvider, "Existing cached key ring is expired. Refreshing.");
}

// It's up to us to refresh the cached keyring.
Expand All @@ -184,11 +184,11 @@ internal IKeyRing GetCurrentKeyRingCore(DateTime utcNow)
{
if (existingCacheableKeyRing != null)
{
_logger.LogError(ex, "An error occurred while refreshing the key ring. Will try again in 2 minutes.");
_logger.LogError(DataProtectionEventId.KeyRingProvider, ex, "An error occurred while refreshing the key ring. Will try again in 2 minutes.");
}
else
{
_logger.LogError(ex, "An error occurred while reading the key ring.");
_logger.LogError(DataProtectionEventId.KeyRingProvider, ex, "An error occurred while reading the key ring.");
}
}

Expand Down
Loading