Skip to content

General low level primitive for ciphers (AES-GCM being the first) #23365

Closed
dotnet/corefx
#31389

Description

@Drawaes

Rationale

There is a general need for a number of ciphers for encryption. Todays mix of interfaces and classes has become a little disjointed. Also there is no support for AEAD style ciphers as they need the ability to provide extra authentication information. The current designs are also prone to allocation and these are hard to avoid due to the returning arrays.

Proposed API

A general purpose abstract base class that will be implemented by concrete classes. This will allow for expansion and also by having a class rather than static methods we have the ability to make extension methods as well as hold state between calls. The API should allow for recycling of the class to allow for lower allocations (not needing a new instance each time, and to catch say unmanaged keys). Due to the often unmanaged nature of resources that are tracked the class should implement IDisposable

public abstract class Cipher : IDisposable
{
    public virtual int TagSize { get; }
    public virtual int IVSize { get; }
    public virtual int BlockSize { get; }
    public virtual bool SupportsAssociatedData { get; }

    public abstract void Init(ReadOnlySpan<byte> key, ReadOnlySpan<byte> iv);
    public abstract void Init(ReadOnlySpan<byte> iv);
    public abstract int Update(ReadOnlySpan<byte> input, Span<byte> output);
    public abstract int Finish(ReadOnlySpan<byte> input, Span<byte> output);
    public abstract void AddAssociatedData(ReadOnlySpan<byte> associatedData);
    public abstract int GetTag(Span<byte> span);
    public abstract void SetTag(ReadOnlySpan<byte> tagSpan);
}

Example Usage

(the input/output source is a mythical span based stream like IO source)

using (var cipher = new AesGcmCipher(bitsize: 256))
{
    cipher.Init(myKey, nonce);
    while (!inputSource.EOF)
    {
        var inputSpan = inputSource.ReadSpan(cipher.BlockSize);
        cipher.Update(inputSpan);
        outputSource.Write(inputSpan);
    }
    cipher.AddAssociatedData(extraInformation);
    cipher.Finish(finalBlockData);
    cipher.GetTag(tagData);
}

API Behaviour

  1. If get tag is called before finish a [exception type?] should be thrown and the internal state should be set to invalid
  2. If the tag is invalid on finish for decrypt it should be an exception thrown
  3. Once finished is called, a call to anything other than one of the Init methods will throw
  4. Once Init is called, a second call without "finishing" will throw
  5. If the type expects an key supplied (a straight "new'd" up instance) if the Initial "Init" call only has an IV it will throw
  6. If the type was generated say from a store based key and you attempt to change the key via Init and not just the IV it will throw
  7. If get tag is not called before dispose or Init should an exception be thrown? To stop the user not collecting the tag by accident?

Reference dotnet/corefx#7023

Updates

  1. Changed nonce to IV.
  2. Added behaviour section
  3. Removed the single input/output span cases from finish and update, they can just be extension methods
  4. Changed a number of spans to readonlyspan as suggested by @bartonjs
  5. Removed Reset, Init with IV should be used instead

Activity

  1. sdrapkin commented on Aug 29, 2017

    @sdrapkin

    Quick-to-judge feedback on the proposed API (trying to be helpful):

    • Span<T> is not in NetStandard2.
    • "Nonce" is very implementation-specific - ie. smells of GCM. However, even GCM docs (ex. NIST SP800-38D) refer to it as "IV", which - in case of GCM - happens to be a nonce. However, in case of other AEAD implementations the IV does not have to be a nonce (ex. repeating IV under CBC+HMAC is not catastrophic).
    • Streaming AEAD should either work seamlessly with CryptoStream, or provide its own "AEADCryptoStream" which is just as easy to stream in/out as CryptoStream.
    • AEAD API imlementations should be allowed to do internal key derivation based on AAD (Associated Data). Using AAD purely for tag calculation/verification is too restrictive and prevents a stronger AEAD model.
    • "Get*" methods should return something (GetTag). If they are void, they must be setting something/changing state.
    • Trying to obtain a tag before "finishing" is probably a bad idea, so "IsFinished" might be helpful.
    • Folks that designed ICryptoTransform thought about reuse, multi-block support, and differently-sized input/output block sizes. These concerns are not captured.

    As a proof of AEAD API sanity, the first implementation of such proposed API should not be AES-GCM, but the classic/default AES-CBC with an HMAC tag. The simple reason for it is that anyone can build AES-CBC+HMAC AEAD implementation today, with simple, existing, well-known .NET classes. Let's get a boring old [AES-CBC+HMAC] working over the new AEAD APIs first, since that's easy for everyone to MVP and test-drive.

  2. Drawaes commented on Aug 29, 2017

    @Drawaes
    ContributorAuthor

    The nonce/IV naming issue was something I was undecided about, happy with a change to IV so will change.

    As for Get methods returning something, this avoids any allocations. There could be an overload Get() that returns something. Maybe it requires a naming change, but I am pretty married to the idea that the whole API needs to be basically allocation free.

    As for streams etc, I am not overly bothered with that as they are higher level API's that can easily be constructed from the lower level primitives.

    Obtaining a Tag before you have finished should not be allowed, however you should know when you have called finish, so I am not sure it should be in the API, however it should be a defined behaviour so I have updated the API design to include a behaviour section so we can capture any others that are thought of.

    As for which cipher, I don't think any specific cipher should be the sole target, in order to prove out a new general purpose API it needs to fit a number. AES GCM, and CBC should both be covered.

    (all on topic feedback good or bad is always helpful! )

  3. bartonjs commented on Aug 29, 2017

    @bartonjs
    Member
    • Class, or interface?
    • How, if at all, do the current SymmetricAlgorithm classes interact with this?
    • How would this be used for persisted keys, like TripleDESCng and AesCng can do?
    • Many of these Spans seem like they could be ReadOnlySpan.
  4. morganbr commented on Aug 29, 2017

    @morganbr
    Contributor

    @Drawaes thanks for getting the ball rolling on this API. A few thoughts:

    1. Tag generation and verification is a very important part of this API since misuse of tags can defeat the whole purpose. If possible, I'd like to see tags built into the initialize and finish operations to ensure they can't be accidentally ignored. That likely implies that encrypt and decrypt shouldn't use the same initialize and finalize methods.
    2. I have mixed feelings about outputting blocks during decryption before getting to the end since the data isn't trustworthy until the tag has been checked (which can't be done until all data has been processed). We'll need to evaluate that tradeoff very carefully.
    3. Is Reset necessary? Should finish just reset? We do that on incremental hashes (but they don't need new IVs)
  5. Drawaes commented on Aug 29, 2017

    @Drawaes
    ContributorAuthor

    @bartonjs

    1. Class, as has often been seen in the BCL with an interface you can't expand it later without breaking everything. An interface is like a puppy for life... unless default interface methods can be considered as a solution to that problem.
      Also a sealed class from a abstract type is actually faster (as of now) because the jitt can devirtualise the methods now ... So it's basically free. interface dispatch isn't as good (still good just not as good)
    2. I dunno how would you like that to work? I have little interest in the current stuff as it's so confusing I would just patch all reasonable modern algos straight in (leave 3DES in The other classes :) But I don't have all the answers so do you have any further thoughts on this?
    3. Persisted keys should be easy. Make an extension method on the key method or persistence store.
    MyKeyStore.GetCipher();
    

    It's not initialized. It's disposable so any refs can be dropped by normal disposable pattern. If they try to set the key throw an invalid operation exception.

    Yes to the read-only spans I will adjust when I am not on the tube on my phone.

  6. Drawaes commented on Aug 29, 2017

    @Drawaes
    ContributorAuthor

    @morganbr no problem... I just want to see it happen more than anything ;)

    1. Can you give a code snippet on how you see that working? Not sure it does but code always brings clarity
    2. It's unfortunate but you really have to spit out the blocks early. With hmac and hashing you don't but you don't have interim data just the state. So in this case you would have to buffer an unknown amount of data. Let's take a look at the pipelines example and TLS. We can write 16k of plaintext but the pipeline buffers are today the size of a 4k page. So we would at best want to encrypt/decrypt 4*4k. Of you don't give me the answer until the end you need to allocate internal memory to store all of that and then I presume throw it away when I get the result? Or will you wipe it. What if I decrypt 10mb and you hold that memory after I now have to worry about latent memory use.
    3. Not 100% on the init/reset thing (not your ideas, my current API shape) it doesn't sit well with me so I am open to a new suggestion!
  7. bartonjs commented on Aug 29, 2017

    @bartonjs
    Member

    I have little interest in the current stuff as it's so confusing I would just patch all reasonable modern algos straight in (leave 3DES in The other classes :)

    The problem would be that container formats like EnvelopedCms (or EncryptedXml) may need to work with 3DES-CBC, AES-CBC, etc. Someone wanting to decrypt something encrypted with ECIES/AES-256-CBC-PKCS7/HMAC-SHA-2-256 probably wouldn't feel that they're doing old and crufty things.

    If it's only supposed to be for AE, then that should be reflected somewhere in the name. Right now it's generic "cipher" (which I was/am, at some point, going to sit down with a dictionary/glossary and find out if there's a word for "an encryption algorithm in a mode of operation", since I think that "cipher" == "algorithm", therefore "Aes").

  8. Drawaes commented on Aug 29, 2017

    @Drawaes
    ContributorAuthor

    :) I was merely pointing out that it's not my subject area or of much interest to me so I am willing to defer to you and the community on this topic I haven't thought through the implications for this.


    After quickly scanning through these, one option is allow them to take an instance of the "Cipher" or whatever it's called class. This might not be done in the first wave, but could quickly follow it up. If the API is super efficient then I see no reason they should do their own thing internally and is exactly the use case for this API.

  9. Drawaes commented on Aug 29, 2017

    @Drawaes
    ContributorAuthor

    As a side bar on the naming... I must admit its a tough one however
    Openssl = cipher
    Ruby = cipher
    Go = cipher package with ducktyped interfaces for AEAD etc
    Java = cipher

    Now I am all for being different but... there is a trend. If something better is possible that is cool.

    Possibly "BlockModeCipher" ... ?

  10. Drawaes commented on Aug 29, 2017

    @Drawaes
    ContributorAuthor

    I have made a few changes, I will change naming if a better name is decided upon.

  11. morganbr commented on Aug 30, 2017

    @morganbr
    Contributor

    When I started trying to answer questions, I realized the API is already missing encryption/decryption differentiation, so in your example, it doesn't know whether to encrypt or decrypt data. Getting that put in might add some clarity.

    I could imagine a couple ways that the API could enforce proper tag usage (based on the assumption that this is an AEAD API, not just symmetric encryption since we already have SymmetricAlgorithm/ICryptoTransform/CryptoStream). Don't take these as prescriptive, just as an example of enforcing the tagging.
    By method:

    class Cipher
    {
       void InitializeEncryption(ReadOnlySpan<byte> key, ReadOnlySpan<byte> iv);
       // Ensures decryptors get a tag
       void InitializeDecryption(ReadOnlySpan<byte> key, ReadOnlySpan<byte> iv, ReadOnlySpan<byte> tag);
       // Ensure encryptors produce a tag
        void FinishEncryption(ReadOnlySpan<byte> input, Span<byte> output, Span<byte> tag);
       // Throws if tag didn't verify
       void FinishDecryption(ReadOnlySpan<byte> input, Span<byte> output);
       // Update and properties are unchanged, but GetTag and SetTag are gone
    }
    

    By class:

    class Cipher
    {
        // Has properties and update, but Initialize and Finish aren't present
    }
    class Encryptor : Cipher
    {
        void Initialize(ReadOnlySpan<byte> key, ReadOnlySpan<byte> iv);
        void Finish(ReadOnlySpan<byte> input, Span<byte> output, Span<byte> tag);
    }
    class Decryptor : Cipher
    {
       void Initialize(ReadOnlySpan<byte> key, ReadOnlySpan<byte> iv, ReadOnlySpan<byte> tag);
       // Throws if tag didn't verify
       void Finish(ReadOnlySpan<byte> input, Span<byte> output);
    }
    class AesGCMEncryptor : Encryptor {}
    class AesGCMDecryptor : Decryptor {}
    }
    

    That said, if it doesn't buffer on decryption, is it practical to ensure decryption actually gets finished and the tag gets checked? Can Update somehow figure out that it's time to check? Is that something Dispose should do? (Dispose is a bit dangerous since you may have already trusted the data by the time you dispose the object)

    As far as naming, our precedent is SymmetricAlgorithm and AsymmetricAlgorithm. If this is intended for AEAD, some ideas could be AuthenticatedSymmetricAlgorithm or AuthenticatedEncryptionAlgorithm.

  12. sdrapkin commented on Aug 30, 2017

    @sdrapkin

    Some thoughts & API ideas:

    public interface IAEADConfig
    {
    	// size of the input block (plaintext)
    	int BlockSize { get; }
    
    	// size of the output per input-block;
    	// typically a multiple of BlockSize or equal to BlockSize.
    	int FeedbackSize { get; }
    
    	// IV size; CAESAR completition uses a fixed-length IV
    	int IVSize { get; }
    
    	// CAESAR competition uses a fixed-length key
    	int KeySize { get; }
    
    	// CAESAR competition states that typical AEAD ciphers have a constant gap between plaintext length
    	// and ciphertext length, but the requirement is to have a constant *limit* on the gap.
    	int MaxTagSize { get; }
    
    	// allows for AE-only algorithms
    	bool IsAdditionalDataSupported { get; }
    }
    
    public interface ICryptoAEADTransform : ICryptoTransform
    {
    	// new AEAD-specific ICryptoTransform interface will allow CryptoStream implementation
    	// to distinguish AEAD transforms.
    	// AEAD decryptor transforms should throw on auth failure, but current CryptoStream
    	// logic swallows exceptions.
    	// Alternatively, we can create a new AEAD_Auth_Failed exception class, and
    	// CryptoTransform is modified to catch that specific exception.
    }
    
    public interface IAEADAlgorithm : IDisposable, IAEADConfig
    {
    	// separates object creation from initialization/keying; allows for unkeyed factories
    	void Initialize(ArraySegment<byte> key);
    
    	void Encrypt(
    		ArraySegment<byte> iv, // readonly; covered by authentication
    		ArraySegment<byte> plaintext, // readonly; covered by authentication
    		ref ArraySegment<byte> ciphertext, // must be of at least [plaintext_length + MaxTagSize] length. iv is not part of ciphertext.
    		ArraySegment<byte> additionalData = default(ArraySegment<byte>) // readonly; optional; covered by authentication
    		); // no failures expected under normal operation - abnormal failures will throw
    
    	bool Decrypt(
    		ArraySegment<byte> iv, // readonly
    		ArraySegment<byte> ciphertext, // readonly
    		ref ArraySegment<byte> plaintext, // must be of at least [ciphertext_length - MaxTagSize] length.
    		ArraySegment<byte> additionalData = default(ArraySegment<byte>), // readonly; optional
    		bool isAuthenticateOnly = false // supports Authentication-only mode
    		);// auth failures expected under normal operation - return false on auth failure; throw on abnormal failure; true on success
    
    	/*	Notes:
    		* Array.LongLength should be used instead of Array.Length to accomodate byte arrays longer than 2^32.
    		* Ciphertext/Plaintext produced by Encrypt()/Decrypt() must be determined *only* by method inputs (combined with a key).
    		  - (ie. if randomness or other hidden inputs are needed, they must be a part of iv)
    		* Encrypt()/Decrypt() are allowed to write to ciphertext/plaintext segments under all conditions (failure/success/abnormal)
    		  - some implementations might be more stringent than others, and ex. not leak decrypted plaintext on auth failures
    	*/
    	
    	ICryptoAEADTransform CreateEncryptor(
    		ArraySegment<byte> key,
    		ArraySegment<byte> iv,
    		ArraySegment<byte> additionalData = default(ArraySegment<byte>)
    		);
    
    	ICryptoAEADTransform CreateDecryptor(
    		ArraySegment<byte> key,
    		ArraySegment<byte> iv,
    		ArraySegment<byte> additionalData = default(ArraySegment<byte>)
    		);
    
    	// Streaming AEAD can be done with good-old CryptoStream
    	// (possibly modified to be AEAD-aware).
    }
  13. morganbr commented on Aug 30, 2017

    @morganbr
    Contributor

    @sdrapkin , thanks for contributing thoughts. Where should tags go in your API? Are they implicitly part of the ciphertext? If so, that implies a protocol that some algorithms don't actually have. I'd like to understand what protocols people might care about to see whether implicit tag placement is acceptable or if it needs to be carried separately.

  14. Drawaes commented on Aug 30, 2017

    @Drawaes
    ContributorAuthor

    @morganbr I noticed the encrypt/decrypt issue as well but hadn't had time tonight to fix so glad for your design. I prefer the methods over the class as it allows better aggressive recycling (buffers for keys and IV's can add up).

    As for a check before the dispose. It's not possible to tell the end of an operation unfortunately.

    @sdrapkin interfaces I would say are a no go due to the version problem mentioned previously. Unless we rely on default implantation in the future. Also interface dispatch is slower.. the array segments also are our as span is the more versatile lower primitive. However extension methods could be added for arraysegment to span if there was demand later.

    Some of your properties are of interest so will update when I am at a computer rather than on my phone.

    Good feedback all round!

  15. sdrapkin commented on Aug 30, 2017

    @sdrapkin

    @morganbr Tags are part of ciphertext. This is modelled after CAESAR API (which includes AES-GCM).

    @Drawaes I've used interfaces to illustrate thoughts only - I'm perfectly ok with static methods/classes. Span does not exist. I don't care about what may or may not be coming - it is not in NetStandard2, and it is not in the normal .NET that serious projects actually use (yeah, yeah, I know it's in Core, but Core is a toy for now). I'd be happy to personally consider Span when I see it - until then ArraySegment is the closest NetStandard API that actually ships.

  16. 119 remaining items

  17. pgolebiowski commented on Apr 13, 2018

    @pgolebiowski
    Contributor

    am I defending streaming AES-GCM anywhere? can't recall. but can recall saying:

    • Streams are important. If you cannot support them directly because that would mean security vulnerability, then if possible provide a higher-level wrapper built on top of your low-level API that would expose streams (in an inefficient but safe way).
    • If AES-GCM absolutely cannot use streams in any scenario, then provide a legit implementation of AES-CBC-HMAC that is based on streams. Or some other AE algorithm.

    or stating an open problem for corefx:

    How to deal with encryption of data that does not fit into memory?


    bonus:

    You can also look at Inferno forks. There are at least 2 forks where a few trivial changes achieved NetStandard20. [...] Inferno was audited by 2 professionals from "Cure53" organisation [...] easy auditability is among the key features of Inferno, precisely for those who don't want to trust.

    I did not advertise anything

  18. Drawaes commented on Apr 13, 2018

    @Drawaes
    ContributorAuthor

    Just as an aside I never really wanted "streaming" in the sense that most are thinking. I just wanted "block" processing for perf and memory use reasons. I don't actually want to "stream" out the results. This is what openssl and cng support seems a shame to lose that and basically makes the "primatives" useless in any scenario I can think of.

  19. Timovzl commented on Apr 16, 2018

    @Timovzl

    @Drawaes Come to think of it, block operation might be much safer than using streams. A layman may touch streams, but he will much rather use the one-shot API than block operation. Moreover, block operation cannot straightforwardly be combined with, say, XmlReader. So actually, many of the dangers discussed apply to stream objects, but not to block operation.

    To work with block operation when a one-shot API is also available, suggests that we know what we are doing, and that we specifically require low-level tweaking. We could protect the layman and have flexibility.

    As for avoiding RUP, I'm still pondering how much of an advantage block operation truly is for GCM. Encryption reaps the full benefits, whereas decryption benefits only somewhat. We can avoid storing the full ciphertext, but we must still buffer the full plaintext. A decryptor could choose to store the intermediate plaintext on disk. But in return, we have introduced more room for error. Do we have a convincing argument to not solve this problem at a higher level (e.g. chunk there, or use a truly streaming algorithm)?

  20. Drawaes commented on Apr 16, 2018

    @Drawaes
    ContributorAuthor

    TLS and pipelines. Currently (and for the foreseeable future) pipelines uses 4k blocks but a tls message can be 16k of cipher text.with a one shot you will need to copy the 16k to a single contingous buffer before you can decrypt. With blocks you might have say 4 or 5 and you might need to buffer upto 16 bytes to ensure compete blocks.

  21. Timovzl commented on Apr 16, 2018

    @Timovzl

    @Drawaes 16k is still constant and not huge. Does it make much of a difference in this context?

  22. Drawaes commented on Apr 16, 2018

    @Drawaes
    ContributorAuthor

    Yes, it means another copy in the pipeline. This has a major and measurable effect on perf.

  23. pgolebiowski commented on Aug 17, 2018

    @pgolebiowski
    Contributor

    What is needed to make this happen? What are the next steps? @Drawaes

  24. pgolebiowski commented on Aug 17, 2018

    @pgolebiowski
    Contributor

    As for AES-GCM, I think that its delivery is impaired due to the corresponding issue being locked: https://github.com/dotnet/corefx/issues/7023. @blowdart, could you unlock? It is really hard to have progress when people can't discuss. Or, if that's not an option, maybe propose an alternative solution that allows bringing this feature to the public.

  25. blowdart commented on Aug 18, 2018

    @blowdart
    Contributor

    Nope, I'm not unlocking that. A decision has been made, the topic is done.

  26. pgolebiowski commented on Aug 18, 2018

    @pgolebiowski
    Contributor

    @blowdart Thanks for the reply. I understand that maybe this was not clear enough:

    Or, if that's not an option, maybe propose an alternative solution that allows bringing this feature to the public.

    I appreciate that there is a decision for supporting AES-GCM. This is great, I definitely want that algorithm. Thus, now it would be cool to actually have it supported. Would you like the discussion on AES-GCM design and implementation be held here or in a new issue?

    Also, if that topic is done, why not close it? And make it more explicit by changing the title of that issue, as right now it suggests that the discussion on the implementation would be held here: https://github.com/dotnet/corefx/issues/7023. Maybe something like Decide which AEAD algorithm to support first.

    In other words: I provide feedback that in the current situation it is unclear what is needed to push AES-GCM forward.

    @karelz

  27. bartonjs commented on Aug 18, 2018

    @bartonjs
    Member

    @pgolebiowski There's already a PR out. It'll probably be available in master Wednesday next week.

  28. transferred this issue fromdotnet/corefxon Jan 31, 2020
  29. added this to the 3.0 milestone on Jan 31, 2020
  30. ghost locked as resolved and limited conversation to collaborators on Dec 20, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-System.Security

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions