|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +#if NETCOREAPP |
| 5 | +using System; |
| 6 | +using System.IO; |
| 7 | +using System.Security.Cryptography; |
| 8 | +using Microsoft.AspNetCore.Cryptography; |
| 9 | +using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption; |
| 10 | +using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel; |
| 11 | +using Microsoft.AspNetCore.DataProtection.SP800_108; |
| 12 | + |
| 13 | +namespace Microsoft.AspNetCore.DataProtection.Managed |
| 14 | +{ |
| 15 | + // An encryptor that uses AesGcm to do encryption |
| 16 | + internal unsafe sealed class AesGcmAuthenticatedEncryptor : IOptimizedAuthenticatedEncryptor, IDisposable |
| 17 | + { |
| 18 | + // Having a key modifier ensures with overwhelming probability that no two encryption operations |
| 19 | + // will ever derive the same (encryption subkey, MAC subkey) pair. This limits an attacker's |
| 20 | + // ability to mount a key-dependent chosen ciphertext attack. See also the class-level comment |
| 21 | + // on CngGcmAuthenticatedEncryptor for how this is used to overcome GCM's IV limitations. |
| 22 | + private const int KEY_MODIFIER_SIZE_IN_BYTES = 128 / 8; |
| 23 | + |
| 24 | + private const int NONCE_SIZE_IN_BYTES = 96 / 8; // GCM has a fixed 96-bit IV |
| 25 | + private const int TAG_SIZE_IN_BYTES = 128 / 8; // we're hardcoding a 128-bit authentication tag size |
| 26 | + |
| 27 | + // See CngGcmAuthenticatedEncryptor.CreateContextHeader for how these were precomputed |
| 28 | + |
| 29 | + // 128 "00-01-00-00-00-10-00-00-00-0C-00-00-00-10-00-00-00-10-95-7C-50-FF-69-2E-38-8B-9A-D5-C7-68-9E-4B-9E-2B" |
| 30 | + private static readonly byte[] AES_128_GCM_Header = new byte[] { 0x00, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x95, 0x7C, 0x50, 0xFF, 0x69, 0x2E, 0x38, 0x8B, 0x9A, 0xD5, 0xC7, 0x68, 0x9E, 0x4B, 0x9E, 0x2B }; |
| 31 | + |
| 32 | + // 192 "00-01-00-00-00-18-00-00-00-0C-00-00-00-10-00-00-00-10-0D-AA-01-3A-95-0A-DA-2B-79-8F-5F-F2-72-FA-D3-63" |
| 33 | + private static readonly byte[] AES_192_GCM_Header = new byte[] { 0x00, 0x01, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x0D, 0xAA, 0x01, 0x3A, 0x95, 0x0A, 0xDA, 0x2B, 0x79, 0x8F, 0x5F, 0xF2, 0x72, 0xFA, 0xD3, 0x63 }; |
| 34 | + |
| 35 | + // 256 00-01-00-00-00-20-00-00-00-0C-00-00-00-10-00-00-00-10-E7-DC-CE-66-DF-85-5A-32-3A-6B-B7-BD-7A-59-BE-45 |
| 36 | + private static readonly byte[] AES_256_GCM_Header = new byte[] { 0x00, 0x01, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0xE7, 0xDC, 0xCE, 0x66, 0xDF, 0x85, 0x5A, 0x32, 0x3A, 0x6B, 0xB7, 0xBD, 0x7A, 0x59, 0xBE, 0x45 }; |
| 37 | + |
| 38 | + private static readonly Func<byte[], HashAlgorithm> _kdkPrfFactory = key => new HMACSHA512(key); // currently hardcoded to SHA512 |
| 39 | + |
| 40 | + private readonly byte[] _contextHeader; |
| 41 | + |
| 42 | + private readonly Secret _keyDerivationKey; |
| 43 | + private readonly int _derivedkeySizeInBytes; |
| 44 | + private readonly IManagedGenRandom _genRandom; |
| 45 | + |
| 46 | + public AesGcmAuthenticatedEncryptor(ISecret keyDerivationKey, int derivedKeySizeInBytes, IManagedGenRandom? genRandom = null) |
| 47 | + { |
| 48 | + _keyDerivationKey = new Secret(keyDerivationKey); |
| 49 | + _derivedkeySizeInBytes = derivedKeySizeInBytes; |
| 50 | + |
| 51 | + switch (_derivedkeySizeInBytes) |
| 52 | + { |
| 53 | + case 16: |
| 54 | + _contextHeader = AES_128_GCM_Header; |
| 55 | + break; |
| 56 | + case 24: |
| 57 | + _contextHeader = AES_192_GCM_Header; |
| 58 | + break; |
| 59 | + case 32: |
| 60 | + _contextHeader = AES_256_GCM_Header; |
| 61 | + break; |
| 62 | + default: |
| 63 | + throw CryptoUtil.Fail("Unexpected AES key size in bytes only support 16, 24, 32."); // should never happen |
| 64 | + } |
| 65 | + |
| 66 | + _genRandom = genRandom ?? ManagedGenRandomImpl.Instance; |
| 67 | + } |
| 68 | + |
| 69 | + public byte[] Decrypt(ArraySegment<byte> ciphertext, ArraySegment<byte> additionalAuthenticatedData) |
| 70 | + { |
| 71 | + ciphertext.Validate(); |
| 72 | + additionalAuthenticatedData.Validate(); |
| 73 | + |
| 74 | + // Argument checking: input must at the absolute minimum contain a key modifier, nonce, and tag |
| 75 | + if (ciphertext.Count < KEY_MODIFIER_SIZE_IN_BYTES + NONCE_SIZE_IN_BYTES + TAG_SIZE_IN_BYTES) |
| 76 | + { |
| 77 | + throw Error.CryptCommon_PayloadInvalid(); |
| 78 | + } |
| 79 | + |
| 80 | + // Assumption: pbCipherText := { keyModifier || nonce || encryptedData || authenticationTag } |
| 81 | + var plaintextBytes = ciphertext.Count - (KEY_MODIFIER_SIZE_IN_BYTES + NONCE_SIZE_IN_BYTES + TAG_SIZE_IN_BYTES); |
| 82 | + var plaintext = new byte[plaintextBytes]; |
| 83 | + |
| 84 | + try |
| 85 | + { |
| 86 | + // Step 1: Extract the key modifier from the payload. |
| 87 | + |
| 88 | + int keyModifierOffset; // position in ciphertext.Array where key modifier begins |
| 89 | + int nonceOffset; // position in ciphertext.Array where key modifier ends / nonce begins |
| 90 | + int encryptedDataOffset; // position in ciphertext.Array where nonce ends / encryptedData begins |
| 91 | + int tagOffset; // position in ciphertext.Array where encrypted data ends |
| 92 | + |
| 93 | + checked |
| 94 | + { |
| 95 | + keyModifierOffset = ciphertext.Offset; |
| 96 | + nonceOffset = keyModifierOffset + KEY_MODIFIER_SIZE_IN_BYTES; |
| 97 | + encryptedDataOffset = nonceOffset + NONCE_SIZE_IN_BYTES; |
| 98 | + tagOffset = encryptedDataOffset + plaintextBytes; |
| 99 | + } |
| 100 | + |
| 101 | + var keyModifier = new ArraySegment<byte>(ciphertext.Array!, keyModifierOffset, KEY_MODIFIER_SIZE_IN_BYTES); |
| 102 | + |
| 103 | + // Step 2: Decrypt the KDK and use it to restore the original encryption and MAC keys. |
| 104 | + // We pin all unencrypted keys to limit their exposure via GC relocation. |
| 105 | + |
| 106 | + var decryptedKdk = new byte[_keyDerivationKey.Length]; |
| 107 | + var derivedKey = new byte[_derivedkeySizeInBytes]; |
| 108 | + |
| 109 | + fixed (byte* __unused__1 = decryptedKdk) |
| 110 | + fixed (byte* __unused__2 = derivedKey) |
| 111 | + { |
| 112 | + try |
| 113 | + { |
| 114 | + _keyDerivationKey.WriteSecretIntoBuffer(new ArraySegment<byte>(decryptedKdk)); |
| 115 | + ManagedSP800_108_CTR_HMACSHA512.DeriveKeysWithContextHeader( |
| 116 | + kdk: decryptedKdk, |
| 117 | + label: additionalAuthenticatedData, |
| 118 | + contextHeader: _contextHeader, |
| 119 | + context: keyModifier, |
| 120 | + prfFactory: _kdkPrfFactory, |
| 121 | + output: new ArraySegment<byte>(derivedKey)); |
| 122 | + |
| 123 | + // Perform the decryption operation |
| 124 | + var nonce = new Span<byte>(ciphertext.Array, nonceOffset, NONCE_SIZE_IN_BYTES); |
| 125 | + var tag = new Span<byte>(ciphertext.Array, tagOffset, TAG_SIZE_IN_BYTES); |
| 126 | + var encrypted = new Span<byte>(ciphertext.Array, encryptedDataOffset, plaintextBytes); |
| 127 | + using var aes = new AesGcm(derivedKey); |
| 128 | + aes.Decrypt(nonce, encrypted, tag, plaintext); |
| 129 | + return plaintext; |
| 130 | + } |
| 131 | + finally |
| 132 | + { |
| 133 | + // delete since these contain secret material |
| 134 | + Array.Clear(decryptedKdk, 0, decryptedKdk.Length); |
| 135 | + Array.Clear(derivedKey, 0, derivedKey.Length); |
| 136 | + } |
| 137 | + } |
| 138 | + } |
| 139 | + catch (Exception ex) when (ex.RequiresHomogenization()) |
| 140 | + { |
| 141 | + // Homogenize all exceptions to CryptographicException. |
| 142 | + throw Error.CryptCommon_GenericError(ex); |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + public byte[] Encrypt(ArraySegment<byte> plaintext, ArraySegment<byte> additionalAuthenticatedData, uint preBufferSize, uint postBufferSize) |
| 147 | + { |
| 148 | + plaintext.Validate(); |
| 149 | + additionalAuthenticatedData.Validate(); |
| 150 | + |
| 151 | + try |
| 152 | + { |
| 153 | + // Allocate a buffer to hold the key modifier, nonce, encrypted data, and tag. |
| 154 | + // In GCM, the encrypted output will be the same length as the plaintext input. |
| 155 | + var retVal = new byte[checked(preBufferSize + KEY_MODIFIER_SIZE_IN_BYTES + NONCE_SIZE_IN_BYTES + plaintext.Count + TAG_SIZE_IN_BYTES + postBufferSize)]; |
| 156 | + int keyModifierOffset; // position in ciphertext.Array where key modifier begins |
| 157 | + int nonceOffset; // position in ciphertext.Array where key modifier ends / nonce begins |
| 158 | + int encryptedDataOffset; // position in ciphertext.Array where nonce ends / encryptedData begins |
| 159 | + int tagOffset; // position in ciphertext.Array where encrypted data ends |
| 160 | + |
| 161 | + checked |
| 162 | + { |
| 163 | + keyModifierOffset = plaintext.Offset + (int)preBufferSize; |
| 164 | + nonceOffset = keyModifierOffset + KEY_MODIFIER_SIZE_IN_BYTES; |
| 165 | + encryptedDataOffset = nonceOffset + NONCE_SIZE_IN_BYTES; |
| 166 | + tagOffset = encryptedDataOffset + plaintext.Count; |
| 167 | + } |
| 168 | + |
| 169 | + // Randomly generate the key modifier and nonce |
| 170 | + var keyModifier = _genRandom.GenRandom(KEY_MODIFIER_SIZE_IN_BYTES); |
| 171 | + var nonceBytes = _genRandom.GenRandom(NONCE_SIZE_IN_BYTES); |
| 172 | + |
| 173 | + Buffer.BlockCopy(keyModifier, 0, retVal, (int)preBufferSize, keyModifier.Length); |
| 174 | + Buffer.BlockCopy(nonceBytes, 0, retVal, (int)preBufferSize + keyModifier.Length, nonceBytes.Length); |
| 175 | + |
| 176 | + // At this point, retVal := { preBuffer | keyModifier | nonce | _____ | _____ | postBuffer } |
| 177 | + |
| 178 | + // Use the KDF to generate a new symmetric block cipher key |
| 179 | + // We'll need a temporary buffer to hold the symmetric encryption subkey |
| 180 | + var decryptedKdk = new byte[_keyDerivationKey.Length]; |
| 181 | + var derivedKey = new byte[_derivedkeySizeInBytes]; |
| 182 | + fixed (byte* __unused__1 = decryptedKdk) |
| 183 | + fixed (byte* __unused__2 = derivedKey) |
| 184 | + { |
| 185 | + try |
| 186 | + { |
| 187 | + _keyDerivationKey.WriteSecretIntoBuffer(new ArraySegment<byte>(decryptedKdk)); |
| 188 | + ManagedSP800_108_CTR_HMACSHA512.DeriveKeysWithContextHeader( |
| 189 | + kdk: decryptedKdk, |
| 190 | + label: additionalAuthenticatedData, |
| 191 | + contextHeader: _contextHeader, |
| 192 | + context: keyModifier, |
| 193 | + prfFactory: _kdkPrfFactory, |
| 194 | + output: new ArraySegment<byte>(derivedKey)); |
| 195 | + |
| 196 | + // do gcm |
| 197 | + var nonce = new Span<byte>(retVal, nonceOffset, NONCE_SIZE_IN_BYTES); |
| 198 | + var tag = new Span<byte>(retVal, tagOffset, TAG_SIZE_IN_BYTES); |
| 199 | + var encrypted = new Span<byte>(retVal, encryptedDataOffset, plaintext.Count); |
| 200 | + using var aes = new AesGcm(derivedKey); |
| 201 | + aes.Encrypt(nonce, plaintext, encrypted, tag); |
| 202 | + |
| 203 | + // At this point, retVal := { preBuffer | keyModifier | nonce | encryptedData | authenticationTag | postBuffer } |
| 204 | + // And we're done! |
| 205 | + return retVal; |
| 206 | + } |
| 207 | + finally |
| 208 | + { |
| 209 | + // delete since these contain secret material |
| 210 | + Array.Clear(decryptedKdk, 0, decryptedKdk.Length); |
| 211 | + Array.Clear(derivedKey, 0, derivedKey.Length); |
| 212 | + } |
| 213 | + } |
| 214 | + } |
| 215 | + catch (Exception ex) when (ex.RequiresHomogenization()) |
| 216 | + { |
| 217 | + // Homogenize all exceptions to CryptographicException. |
| 218 | + throw Error.CryptCommon_GenericError(ex); |
| 219 | + } |
| 220 | + } |
| 221 | + |
| 222 | + public byte[] Encrypt(ArraySegment<byte> plaintext, ArraySegment<byte> additionalAuthenticatedData) |
| 223 | + => Encrypt(plaintext, additionalAuthenticatedData, 0, 0); |
| 224 | + |
| 225 | + public void Dispose() |
| 226 | + { |
| 227 | + _keyDerivationKey.Dispose(); |
| 228 | + } |
| 229 | + } |
| 230 | +} |
| 231 | +#endif |
0 commit comments