runtime icon indicating copy to clipboard operation
runtime copied to clipboard

SymmetricAlgorithm.BlockSize setter resets IV even if BlockSize isn't changing

Open MA-Maddin opened this issue 1 year ago • 6 comments

Description

The setter of SymmetricAlgorithm.BlockSize is setting IVValue to null even if the new BlockSize value is the same (at least in the case of Aes class). So maybe because of validatedByZeroSkipSizeKeySizes. https://github.com/dotnet/runtime/blob/67837792faa88beb3f44105dfa7a3a430961ff12/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SymmetricAlgorithm.cs#L54-L58

I have found that bug when migrated code from using RijndaelManaged to Aes, which was recommended by the IDE (SYSLIB0022).

Relevant part of code was like:

using RijndaelManaged rm = new();
rm.IV = ivValue;                  // is byte[] in length of new RijndaelManaged().IV.Length // byte[16]
rm.BlockSize = rm.IV.Length * 8;  // 128 (same as the only allowed AES BlockSize) 

Changing from RijndaelManaged to Aes broke the decryption to work.

Sure, it probably doesn't make sense to set the BlockSize after the IV since the IV length depends on the BlockSize, but nevertheless setting a property to its current value shouldn't have any side-effects imho.

Reproduction Steps

xUnit test:

private const string InputText = "Lorem ipsum dolor sit amet";
private readonly byte[] MyKey = [
    0x79, 0x3B, 0x56, 0x79, 0x7F, 0x2D, 0x6B, 0xFD,
    0x43, 0xAD, 0xFA, 0xC6, 0xF2, 0xD4, 0x7F, 0x44,
    0x1A, 0x5A, 0x58, 0x49, 0xAF, 0x28, 0xCC, 0xF6,
    0xC6, 0xCE, 0xA6, 0x79, 0x19, 0x31, 0xC6, 0x3F];
private readonly byte[] MyIV = [
    0x53, 0x46, 0xBD, 0x29, 0xC3, 0xAF, 0x44, 0x9F,
    0x7E, 0x0A, 0x0A, 0xBF, 0x16, 0xA3, 0x87, 0xF9];

[Fact]
public void Rijndael_EncryptAndDecrypt_ReturnsInitialValue()
{
    using RijndaelManaged rm1 = new();
    byte[] encrypted = Encrypt(rm1, InputText, MyKey, MyIV);

    using RijndaelManaged rm2 = new();
    string decrypted = Decrypt(rm2, encrypted, MyKey, MyIV);
    
    Assert.Equal(InputText, decrypted);
}

[Fact]
public void AES_EncryptAndDecrypt_ReturnsInitialValue()
{
    using Aes aes1 = Aes.Create();
    byte[] encrypted = Encrypt(aes1, InputText, MyKey, MyIV);

    using Aes aes2 = Aes.Create();
    string decrypted = Decrypt(aes2, encrypted, MyKey, MyIV);

    Assert.Equal(InputText, decrypted);
}

private byte[] Encrypt(SymmetricAlgorithm algorithm, string input, byte[] key, byte[] iv)
{
    algorithm.Key = key;
    algorithm.IV = iv;
    algorithm.BlockSize = algorithm.BlockSize; // The reason for AES to fail

    using ICryptoTransform encryptor = algorithm.CreateEncryptor();
    using MemoryStream msEncrypt = new();
    using (CryptoStream csEncrypt = new(msEncrypt, encryptor, CryptoStreamMode.Write))
    {
        using StreamWriter swEncrypt = new(csEncrypt);
        swEncrypt.Write(input);
    }
    return msEncrypt.ToArray();
}

private string Decrypt(SymmetricAlgorithm algorithm, byte[] encInput, byte[] key, byte[] iv)
{
    algorithm.Key = key;
    algorithm.IV = iv;
    algorithm.BlockSize = algorithm.BlockSize; // The reason for AES to fail

    using ICryptoTransform decryptor = algorithm.CreateDecryptor();
    using MemoryStream msDecrypt = new(encInput);
    using CryptoStream csDecrypt = new(msDecrypt, decryptor, CryptoStreamMode.Read);
    using StreamReader srDecrypt = new(csDecrypt);

    return srDecrypt.ReadToEnd();
}

Expected behavior

One of these:

  • Setting SymmetricAlgorithm.BlockSize doesn't reset the IV if BlockSize isn't changing.
  • Setting AES.BlockSize (and other algos that allow only one specific block size) is prevented (Assert, readonly, or Exception).

Actual behavior

IV is reset to a new value, causing decryptions to return wrong (but possibly not corrupted) data. If input is shorter than the IV, furthermore a CryptographicException is thrown: "Padding is invalid and cannot be removed."

Regression?

No response

Known Workarounds

Not being a noob; being aware of how this works and not migrating code blindly. So, (re)moving any .BlockSize setter statements that exist.

Configuration

.NET 8.0 & .NET 10.0 Preview Windows 11 23H2 x64, x86

"Do you know whether it is specific to that configuration?": No

Other information

No response

MA-Maddin avatar Jul 25 '25 17:07 MA-Maddin

Tagging subscribers to this area: @dotnet/area-system-security, @bartonjs, @vcsjones See info in area-owners.md if you want to be subscribed.

dotnet-policy-service avatar Jul 25 '25 17:07 dotnet-policy-service

On one hand I agree it is a bit of a weird behavior. Especially for an algorithm like Aes that only has one block size.

On the other hand... maybe... someone is depending on this behavior.

using System.Security.Cryptography;


Aes aes = Aes.Create();
Console.WriteLine(Convert.ToHexString(aes.IV));

aes.BlockSize = aes.BlockSize;
Console.WriteLine(Convert.ToHexString(aes.IV));

IVs need to be unique per cipher text, so if someone is depending on this to generate fresh IVs, we've introduced a nonce-reuse vulnerability in their system.

I'll admit it's a fairly contrived concern, but on the other hand, introducing a vulnerability for someone may not be worth addressing the issue.

@bartonjs what do you think?

vcsjones avatar Jul 25 '25 17:07 vcsjones

The fixed IV in the example is, of course, only for testing purposes. In my real-world case, the IV was indeed unique for each stream. However, the migration to AES broke the data without telling my why.

Depending on a side-effect of another property-setter to create a new IV while there exists stuff like SymmetricAlgorithm.GenerateIV()... feels odd 😅

MA-Maddin avatar Jul 25 '25 17:07 MA-Maddin

Offhand, I think this is going to be one of those "if we broke this when we built .NET Core, we should fix it; but if it's what .NET Framework does, it should stay that way".

I agree that it's wrong, but it's definitely a thing that would be surprising to have as a behavioral difference across runtimes or versions; so the sad case where the cure may be worse than the disease.

I haven't yet looked to see if it's a netfx vs corefx difference, or a "yep, this got screwed up 20 years ago, and it is what it is now"... just answering both halves pending that investigation.

bartonjs avatar Jul 25 '25 17:07 bartonjs

Depending on a side-effect of another property-setter to create a new IV while there exists stuff like SymmetricAlgorithm.GenerateIV()... feels odd 😅

It would be more likely accidental than intention. Someone could be doing something like:

List<byte[]> stuffToEncrypt = GetStuffToEncrypt();
Aes aes = Aes.Create();

foreach (byte[] thing in stuffToEncrypt)
{
    aes.BlockSize = 128;
    byte[] encrypted = aes.TransformFinalBlock(thing, 0, thing.Length);
    HandleEncryptedContents(encrypted, aes.IV);
}

Someone could perhaps, reasonably, it's TransformFinalBlock that generates a fresh IV, not the BlockSize setter.

I haven't yet looked to see if it's a netfx vs corefx difference,

.NET Framework 4.8.1 has the same behavior (which means its probably had it for a very long time)


using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography;

Console.WriteLine(RuntimeInformation.FrameworkDescription);

Aes aes = Aes.Create();
Console.WriteLine(Convert.ToBase64String(aes.IV));

aes.BlockSize = aes.BlockSize;
Console.WriteLine(Convert.ToBase64String(aes.IV));

Output:

.NET Framework 4.8.9215.0
y0Fgb9lzwV1CFwY9ibxhIQ==
Y8RsSDKTCODHuWUIqLzEtg==

vcsjones avatar Jul 25 '25 18:07 vcsjones

Given the above I think the most likely scenario here is that we shouldn't change anything. For better or for worse this is how it has worked for a very long time, and there has been some effort in SymmetricAlgorithm's BlockSize setter to preserve compatibility.

This is also the only issue that I am aware of that has ever been raised for this. So the answer I think is going to more or less amount to "Yes, the BlockSize setter can reset the IV, even when the value is technically not changing"

We can always revisit this if there is more evidence from the community that this is causing some heartburn.

Thanks for taking the time to make an issue though!

vcsjones avatar Jun 17 '26 21:06 vcsjones