Skip to content

ConvertTo-SecureString truncates to multiples of 8 characters #16047

Closed

Description

@dwtaber

Prerequisites

Steps to reproduce

In 7.2.0-preview.9, ConvertTo-SecureString with either -Key or -SecureKey truncates the payload down to the nearest multiple of eight characters. ConvertFrom-SecureString seems to be fine; SecureStrings created in 7.1.4 and imported to 7.2.0-preview.9 aren't truncated when converted to plaintext.

Expected behavior

PS> $Key = [Byte[]]::New(32)
>> '[8Chars][8Chars][Not8]' |
>> ConvertTo-SecureString -AsPlainText -Force |
>> ConvertFrom-SecureString -Key $Key |
>> ConvertTo-SecureString -Key $Key |
>> ConvertFrom-SecureString -AsPlainText
[8Chars][8Chars][Not8]

PS> $Key = [Byte[]]::New(32)
>> '🟥🟧🟨🟩🟦🟪' |
>> ConvertTo-SecureString -AsPlainText -Force |
>> ConvertFrom-SecureString -Key $Key |
>> ConvertTo-SecureString -Key $Key |
>> ConvertFrom-SecureString -AsPlainText
🟥🟧🟨🟩🟦🟪

Actual behavior

PS> $Key = [Byte[]]::New(32)
>> '[8Chars][8Chars][Not8]' |
>> ConvertTo-SecureString -AsPlainText -Force |
>> ConvertFrom-SecureString -Key $Key |
>> ConvertTo-SecureString -Key $Key |
>> ConvertFrom-SecureString -AsPlainText
[8Chars][8Chars]

PS> $Key = [Byte[]]::New(32)
>> '🟥🟧🟨🟩🟦🟪' |
>> ConvertTo-SecureString -AsPlainText -Force |
>> ConvertFrom-SecureString -Key $Key |
>> ConvertTo-SecureString -Key $Key |
>> ConvertFrom-SecureString -AsPlainText
🟥🟧🟨🟩

Error details

No response

Environment data

Name                           Value
----                           -----
PSVersion                      7.2.0-preview.9
PSEdition                      Core
GitCommitId                    7.2.0-preview.9
OS                             Microsoft Windows 10.0.22449
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Visuals

No response

Activity

  1. added
    Needs-Triage
    on Sep 4, 2021
  2. added
    WG-Security
    on Sep 4, 2021
  3. dwtaber commented on Sep 5, 2021

    @dwtaber
    ContributorAuthor

    I'm a little out of my depth, but could this breaking change to System.Security.Cryptography.CryptoStream be the culprit?

  4. fMichaleczek commented on Sep 7, 2021

    @fMichaleczek
    Contributor

    dwtaber out of my depth too, but i believe you're right.

    There is a breaking change in net 6.0 Preview 6 inside the API System.Security.Cryptography.CryptoStream.Read

    Breaking Change Documentation :
    https://docs.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams

    The API is used Line 372 :

    /// <summary>
    /// Decrypts the specified string using the specified key
    /// and return equivalent SecureString.
    ///
    /// The string must be obtained earlier by a call to Encrypt()
    /// </summary>
    /// <param name="input">Encrypted string.</param>
    /// <param name="key">Encryption key.</param>
    /// <param name="IV">Encryption initialization vector. If this is set to null, the method uses internally computed strong random number as IV.</param>
    /// <returns>SecureString .</returns>
    internal static SecureString Decrypt(string input, byte[] key, byte[] IV)
    {
    Utils.CheckArgForNullOrEmpty(input, "input");
    Utils.CheckKeyArg(key, "key");
    byte[] decryptedData = null;
    byte[] encryptedData = null;
    SecureString s = null;
    //
    // prepare the crypto stuff
    //
    Aes aes = Aes.Create();
    encryptedData = ByteArrayFromString(input);
    var decryptor = aes.CreateDecryptor(key, IV ?? aes.IV);
    MemoryStream ms = new MemoryStream(encryptedData);
    using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
    {
    byte[] tempDecryptedData = new byte[encryptedData.Length];
    int numBytesRead = 0;
    //
    // decrypt the data
    //
    numBytesRead = cs.Read(tempDecryptedData, 0,
    tempDecryptedData.Length);
    decryptedData = new byte[numBytesRead];
    for (int i = 0; i < numBytesRead; i++)
    {
    decryptedData[i] = tempDecryptedData[i];
    }
    s = New(decryptedData);
    Array.Clear(decryptedData, 0, decryptedData.Length);
    Array.Clear(tempDecryptedData, 0, tempDecryptedData.Length);
    return s;
    }
    }

    Learn about the .NET 6.0 breaking change in core .NET libraries where DeflateStream, GZipStream, and CryptoStream handle partial and zero-byte reads differently.
  5. added
    Breaking-Change
    on Sep 7, 2021
  6. vexx32 commented on Sep 7, 2021

    @vexx32
    Collaborator

    Yeah, looks like we'll need to add a loop in around that code to ensure we're reading all the data.

    That's a very strange way to write a stream api, to me at least.

  7. dwtaber commented on Sep 7, 2021

    @dwtaber
    ContributorAuthor

    The following change to the CryptoStream using statement starting at line 363 of SecureStringHelper.cs appears to work for me:

    using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
    {                
        int totalBytesRead = 0;
        var tempDecryptedData = ms.ToArray().AsSpan();
        //
        // decrypt the data
        //
        while (totalBytesRead < encryptedData.Length)
        {
            int bytesRead = cs.Read(tempDecryptedData.Slice(totalBytesRead));
            if (bytesRead == 0) { break; }
            totalBytesRead += bytesRead;
        }
        decryptedData = new byte[totalBytesRead];
    
        for (int i = 0; i < totalBytesRead; i++)
        {
            decryptedData[i] = tempDecryptedData[i];
        }
        
        s = New(decryptedData);
        Array.Clear(decryptedData, 0, decryptedData.Length);
        tempDecryptedData.Clear();
        
        return s;
    }

    Are there any security implications or other glaring issues with the code above? If not, is there a better way to achieve the result? I'm new to collaborating on a project like this and don't want to create a pull request prematurely.

  8. vexx32 commented on Sep 7, 2021

    @vexx32
    Collaborator

    I think rather than doing .ToArray().AsSpan() for the tempDecryptedData we're probably better off just creating a new Span or array of the appropriate length instead, which is more similar to the original code. Otherwise I'd expect that'll end up reading the memory stream multiple times, which might break some things.

    Other than that, I think that would work? Would need to be tested of course, but that looks pretty good. You could probably skip the for loop as well, because the decrypted data will already be in tempDecryptedData, so that can end up as the final span, and you can call .ToArray() on that if you really need to.

    Looking at the docs for CryptoStream.Read I think you also need to specify the offset and count anyway, it doesn't look like its Read method has optional parameters: https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.cryptostream.read?view=net-5.0

    ... Hm... The crypto stream API doesn't seem like it has a lot of span-friendly overloads 😕
    That might cause some issues for how you want to solve this. Best bet is to test it and see if it compiles / behaves like you expect.

    Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
  9. added this to the 7.2-Consider milestone on Sep 7, 2021
  10. dwtaber commented on Sep 7, 2021

    @dwtaber
    ContributorAuthor

    I think rather than doing .ToArray().AsSpan() for the tempDecryptedData we're probably better off just creating a new Span or array of the appropriate length instead, which is more similar to the original code. Otherwise I'd expect that'll end up reading the memory stream multiple times, which might break some things.

    Other than that, I think that would work? Would need to be tested of course, but that looks pretty good. You could probably skip the for loop as well, because the decrypted data will already be in tempDecryptedData, so that can end up as the final span, and you can call .ToArray() on that if you really need to.

    Looking at the docs for CryptoStream.Read I think you also need to specify the offset and count anyway, it doesn't look like its Read method has optional parameters: https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.cryptostream.read?view=net-5.0

    ... Hm... The crypto stream API doesn't seem like it has a lot of span-friendly overloads 😕
    That might cause some issues for how you want to solve this. Best bet is to test it and see if it compiles / behaves like you expect.

    Weird that it's not documented there, but it looks like CryptoStream inherits Stream.Read(Span<byte> buffer).
    (Edit: there's apparently also a new overload for Array.Clear that clears an entire array without requiring a start index and count to be specified, so I've made use of that as well.)

    You were right about the for loop; it doesn't appear to be necessary. I think the ToArray() at the end is necessary, as SecureStringHelper.New wants byte[], and I don't think there's any implicit conversion from Span<T> to T[]. Here's a revised version of my possible fix. It does compile and works in cases similar to the ones shown in the issue description, for at least as many as 512 characters.

    using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
    {                
        int totalBytesRead = 0;
        var tempDecryptedData = new Span<byte>(ms.ToArray());
        //
        // decrypt the data
        //
        while (totalBytesRead < encryptedData.Length)
        {
            int bytesRead = cs.Read(tempDecryptedData.Slice(totalBytesRead));
            if (bytesRead == 0) { break; }
            totalBytesRead += bytesRead;
        }
        decryptedData = tempDecryptedData[0..totalBytesRead].ToArray();
        
        s = New(decryptedData);
        Array.Clear(decryptedData);
        tempDecryptedData.Clear();
        
        return s;
    }

    There seem to be some extraneous bytes at the end of tempDecryptedData; if the range isn't specified when converting to byte[], the SecureString returned by the method winds up with a handful of extra bytes that, in the cases I tried, wound up getting interpreted as roughly three to five (seemingly) random non-Latin characters at the end of the intended string. The characters were different each time I ran the same set of commands; I'm not sure if that's because the random key was different each time, or maybe some other factor. Specifying the [0..totalBytesRead] range to be converted to byte[] appears to resolve the issue, but I mention it in case it points to some potential security issue or edge case that I wouldn't know to look for.

  11. PaulHigin commented on Sep 7, 2021

    @PaulHigin
    Contributor

    WG-Security

    Thanks for finding this. I am just beginning to look into it and will propose a PR if no one else does.

  12. added
    Issue-Bug
    and removed
    Needs-Triage
    on Sep 7, 2021
  13. dwtaber commented on Sep 7, 2021

    @dwtaber
    ContributorAuthor

    I'm going over the documentation re: contributing to make sure I get the PR right. I do have a potentially silly question that I haven't run into a specific answer for yet re: testing. Is it okay to modify an extant Pester test, or is it preferable to make a whole new one? \test\powershell\Modules\Microsoft.PowerShell.Security\SecureString.Tests.ps1 would have caught this bug with only a little modification, so making the necessary adjustments seems like the path of least resistance, but I'm happy to write a new test if that's the way things are done.

    Apologies if the answer's somewhere I should've seen it, or if I shouldn't be asking here.

  14. vexx32 commented on Sep 7, 2021

    @vexx32
    Collaborator

    As long as the test still serves its original purpose (assuming that purpose still makes sense, of course) then yeah that should usually be fine.

    An explicit test might be preferable in this case, just because of the esoteric nature of the bug -- probably would be good to link to the breaking change doc that was mentioned here in a comment near the test as well.

  15. PaulHigin commented on Sep 7, 2021

    @PaulHigin
    Contributor

    I was thinking of using a different pattern.

            internal static SecureString Decrypt(string input, byte[] key, byte[] IV)
            {
                Utils.CheckArgForNullOrEmpty(input, "input");
                Utils.CheckKeyArg(key, "key");
    
                //
                // prepare the crypto stuff
                //
                Aes aes = Aes.Create();
                byte[] encryptedData = ByteArrayFromString(input);
                var decryptor = aes.CreateDecryptor(key, IV ?? aes.IV);
                using (var ms = new MemoryStream(encryptedData))
                using (var sourceStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                using (var targetStream = new MemoryStream())
                {
                    //
                    // decrypt the data
                    //
                    sourceStream.CopyTo(targetStream);
                    byte[] decryptedData = targetStream.ToArray();
                    try
                    {
                        return New(decryptedData);
                    }
                    finally
                    {
                        Array.Clear(decryptedData, 0, decryptedData.Length);
                    }
                }
            }

    Also, I noticed that the Encrypt() method doesn't dispose disposable objects or always clear the clear text data. So I feel it should be cleaned up too. I'll submit a PR tomorrow and let you take a look.

  16. PaulHigin commented on Sep 8, 2021

    @PaulHigin
    Contributor

    I have created a PR for this (see above). Please take a look.

  17. dwtaber commented on Sep 8, 2021

    @dwtaber
    ContributorAuthor

    I have created a PR for this (see above). Please take a look.

    I'm no expert, but that definitely seems like a much cleaner and more straightforward approach. Parts of the original code seemed clunky enough that I figured they must be necessary for reasons I just wasn't seeing. I'm happy to learn I was wrong about that! Is there a performance reason to stick with Array.Clear(Array, Int32, Int32) rather than use the new Array.Clear(Array) overload in the finally block?

    An explicit test might be preferable in this case, just because of the esoteric nature of the bug

    Sorry, terminology misfire on my part; I wasn't thinking in terms of each It block constituting a test. Anyway, yeah, my plan was to replace $string = "ABCD" in the BeforeAll block with something long enough to reveal this issue, e.g. $String = "PrimeNumberOfCharacters", and to add this It block:

    It "can convert back from a secure string using AES" {
        $key = [byte[]]::new(24)
        $secureString1 = ConvertTo-SecureString -AsPlainText -Force -String $string
        $encryptedString = ConvertFrom-SecureString -SecureString $secureString1 -Key $key
        $secureString2 = ConvertTo-SecureString -String $encryptedString -Key $key
        $plaintextString = ConvertFrom-SecureString -AsPlainText -SecureString $secureString2
        $plaintextString | Should -Be $string
    }

    Edit: just noticed that the PR already includes updated tests. Huzzah!

  18. PaulHigin commented on Sep 9, 2021

    @PaulHigin
    Contributor

    Yes, I believe I have covered all issues in the PR. Feel free to post any additional comments directly in the PR. I am closing this issue since it has been addressed.

    Thanks for finding this and helping with the fix!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Breaking-ChangeIssue-BugResolution-FixedWG-Security

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions