Skip to content

.NET should expose a generalized ASN.1 reader/writer API #22610

Closed

Description

@bartonjs

A lot of features in cryptography and X.509 certificates rely on the ability to read or write ASN.1-structured data. Not only would a good API for ASN.1 reading/writing simplify some of our existing code, it's very handy when someone wants to try adding support for something we don't have inbox, like reading a new certificate extension.

There are a couple of different aspects to the problem:

1) What do inputs/outputs look like?

One of the harder parts to remember to get right is rejecting unexpected data. For example, from https://tools.ietf.org/html/rfc3280#section-4.1.1.2:

   AlgorithmIdentifier  ::=  SEQUENCE  {
        algorithm               OBJECT IDENTIFIER,
        parameters              ANY DEFINED BY algorithm OPTIONAL  }

The AlgorithmIdentifier structure defines two, and only two fields. If a third field is present the data is invalid. (In our current internal implementation this means you need if (reader.HasData) throw new CryptographicException(); at the end of reading it).

This means that we really don't want to have to resort to a ReadNext() type API, since it's easy to do it poorly.

One strawman is to build on the model of existing serializers, so one would so something like

[StructLayout(StructLayoutKind.Sequential)]
internal struct AlgorithmIdentifier
{
    internal ObjectIdentifier Algorithm;
    [Optional]
    internal ??? Parameters;
}

The fact that the first example drew a need for a base class might be telling that it needs to be a Sequential-layout class instead of a struct. Or maybe ASN-ANY has to be a byte[] that gets reinterpreted by the caller (but the serializer validates that it was legally encoded).

But sequential ordering on the type seems like a requirement.

C-based libraries generally seem to solve this problem with macro-based template languages. So maybe a template is the way to go. But, maybe not.

Needs to consider:

  • OPTIONAL (DER says never to write down ASN-NULL for an OPTIONAL value)
  • DEFAULT (DER says to never write down a default value)
    • Sometimes a default is on a complex type (like saying that a default AlgorithmIdentifier is SHA-2-256).
  • ANY
  • Context-specific tagging
    • And Application-specific, and Private. I suppose
  • That tags technically are not constrained to one-byte values.
  • Collections (arrays/etc) can be SEQUENCE OF (write them down in the order I gave you) or SET OF (write them down in a proscribed order)
    • This could be skipped in the encoder and declared to be a problem for the data provider; but since the sort order for SET OF frequently comes down to the data length (before data values) it is sort of hard for them to do it right.
  • ASN INTEGER is C# BigInteger. But also supporting Int32/Int64/etc has virtue.
  • There are lots of string encodings in ASN
  • I'm sure floating point is unpleasant.
  • DateTime values can be pretty weird. X.509 adds more restrictions than DER does. Is that an encoding? An attribute? A post-deserialization validation?
  • Any other quirks that exist when combining ITU-T X.680 (ASN), ITU-T X.690 (BER/CER/DER) and C#.

2) What encodings are supported?

ITU-T X.690 defines 3 different encoding rulesets:

  • BER (Basic Encoding Rules)
  • CER (Canonical Encoding Rules)
  • DER (Distinguished Encoding Rules)

Generally speaking; BER defines all the possibilities for representing data, CER describes a set of restrictions on BER, and DER describes even more restrictions. Occasionally CER and DER give conflicting recommendations, though.

  • Read-as-BER can read anything.
  • Read-as-CER (maybe) should reject an octet-string with a primitive encoding in excess of 1000 octets (ITU-T REC X.690 2015-08 section 9.2)
    • (Maybe there needs to be CER-strict and CER-flexible?)
  • Read-as-DER should (definitely) reject any indefinite length encoding (ITU-T REC X.690 2015-08 section 10.1).

Almost all things in cryptography use DER, making DER a minimum bar. But, since CMS / S/MIME / PKCS#7 says that it's designed to allow BER indefinite length encodings, there are clearly cases where readers need to be more flexible. (Windows and OpenSSL both write all CMS objects with DER; macOS uses indefinite length encodings)

3) What does an API look like?

Largely this comes out of the inputs/outputs section, but encodings need to be taken into account.

public static AsnEncoding
{
    public static ???? Encode<T>(T value, AsnEncodingType type, Span<byte> output);
    public static ???? Decode<T>(ReadOnlySpan<byte> input, 
}

If there's a base class then there could be an OnDeserialize()-style validation callback per hydrated member. If it's a convention that ends up being reflection, which isn't super fun. So maybe it's just up to the user... but that's somewhat annoying for embedded structures. Particularly through OPTIONAL.


It probably makes sense to try to design the API, and use it internally, and then eventually expose it (essentially letting internal consumption be the proving ground).

Activity

  1. jnm2 commented on Jul 3, 2017

    @jnm2
    Contributor

    I'm interested to see what you come up with so I can compare it to my fast forward-only ASN.1 reader.

  2. bachratyg commented on Jul 3, 2017

    @bachratyg

    Pretty excited to hear this being considered. I was working on a TSP client a while back and wrote my own generic parser for it. There's naturally BouncyCastle but the API looks quite overcomplicated and alloc-heavy.

    Let's just say the task is very very far from trivial and since it's usually security related there's a very low margin for error. Sometimes you may want BER+DER in the same input stream or mixed implicit+explicit tagging.

    Not sure about the attribute/serializer approach. I ditched this pretty early on as it was too complex to implement and not flexible enough. Using an XmlReader-like approach (with peek instead of ReadNext and some sequence scoping) worked quite well though. I could then avoid reflection entirely and add app-specific logic to the deserialization like inline-decoding the context-specific content of an EncapsulatedContentInfo.
    This could also serve as a basis for a higher level abstraction if you still want to go attribute-based.

  3. bartonjs commented on Jul 3, 2017

    @bartonjs
    MemberAuthor

    This could also serve as a basis for a higher level abstraction if you still want to go attribute-based.

    Yeah, the idea is that someone should be able to, for example, look at https://tools.ietf.org/html/rfc5652#section-9.1 and quickly (and correctly) be able to write a structured reader to read the AuthenticatedData object structure. (And, one supposes, write it as well).

    While it's possible to do that with a reader-style API it's really easy to forget to check for unknown values, which could be there as part of a length-extension (or other) payload attack.

  4. vcsjones commented on Jul 11, 2017

    @vcsjones
    Member

    If it is helps with the consideration and planning at all, I consider this feature important enough to me that I am willing to spend a significant amount of time helping, if you're open to it.

  5. bartonjs commented on Jul 11, 2017

    @bartonjs
    MemberAuthor

    @vcsjones The core feature work is on the feature-set that I've given up my management chain. There's a chance that we won't want to mark the API as public during the 2.1 timeframe; it depends on how polished we think it is.

    My official suggestions were that we'd need to start on this first, since it's useful in a number of things I'd like us to be doing, and when we're happy with the API flip it to public. I also decided that the Reader-style API is important in addition to the template/serialization API, for different reasons... so maybe what happens for 2.1 is a good primitive reader, but the serialization part isn't ready.

    And, of course, there's a chance that all "my" funding gets cut and nothing at all happens here. But I was told I can mark my proposals as being in the 2.1 milestone 😄.

  6. danmoseley commented on Dec 1, 2017

    @danmoseley
    Contributor

    @bartonjs estimates 1 week remaining

  7. ebekker commented on Dec 2, 2017

    @ebekker

    Awesome! Reader only or does that also include serialization?

  8. bartonjs commented on Dec 2, 2017

    @bartonjs
    MemberAuthor

    @ebekker The "one week remaining" is for the reader+writer and the serializer+deserializer; all as internal API only. For becoming public it looks like:

    • Be able to read BER tags. That's easy, right? Just one byte and a bitmask.
      • Nah, ~80 lines of code and ~160 lines of test.
    • BER lengths
      • Another 150 loc.
    • Foreach tag in the universal class
      • Write tests for it
        • Would you believe that there are currently 32,640 ways to write BOOLEAN TRUE in BER, and 128 ways to write BOOLEAN FALSE? (Only one each in CER and DER, and not counting non-Universal tags)
          • ReadBoolean: 220 lines of tests
          • WriteBoolean: 81 lines of tests (much simpler, the writer only supports one true and one false 😄 (but also custom tags exist))
        • Ambiguous wording in the spec says there are either 128 or 1 ways to write BER NULL. Windows supports 5 different ways. (Not counting non-Universal tags)
        • Try and rationalize why the time values are stored as ASCII strings instead of something more compact, give up.
        • Try and rationalize why in the world anyone would store time as yyyyMMddHH and fractional hours, give up.
        • Try and understand why the spec says you can have an empty BIT STRING when it says every primitive BIT STRING has "an initial octet".
      • Write a reader for it
      • Write a writer for it
    • Write a deserializer
      • Deal with CHOICE, DEFAULT, OPTIONAL, and all the problems they bring.
      • Sigh, and change the reader API where it couldn't do what the deserializer needed.
    • Write a serializer
      • Same problems, but now the writer.
    • Try using it
    • PR the reader+writer (it's only a 17,000 line PR, sheesh)
      • We are here.
    • PR the serializer (the code part looks like it eked in at about 1000 lines, given the reader+writer)
    • PR a feature making use of it
    • Backfill code using the previous internal version and see if any functionality/assumptions got missed
    • Write a second new feature using it
    • API review
    • Rewrite everything based on API review
    • Make it public

    The "one week remaining" means that I think there are between 20 and 40 bartonjs-hours remaining to move the "We are here" down one-and-a-half points, so a reader+writer and a serializer+deserializer will be checked in, non-public.

    There's still a fair bit of things to do before "Make it public", and that means that it's probably not going to be public in the 2.1 release. But it will be in it, getting tested by being the internals powering a couple of things.

  9. ebekker commented on Dec 4, 2017

    @ebekker

    Wow, thanks for the update.

  10. jariq commented on Dec 28, 2017

    @jariq

    I was hoping to use this ASN.1 reader/writer in .NET 4.x projects. @bartonjs do I understand it correctly that it will available only for .NET Core?

  11. bartonjs commented on Jan 3, 2018

    @bartonjs
    MemberAuthor

    @jariq When the ASN.1 types become public API they will become public only for netcoreapp; and then would appear in .NET Framework at some later point; but it won't be applicable retroactively to existing .NET Framework versions.

    The code for the reader/writer/serializer/deserializer should work on .NET Framework (since it was built using only netstandard references) if you want to copy it into a project locally.

  12. clairernovotny commented on Jan 18, 2018

    @clairernovotny

    FWIW, NuGet seems to have had to implement quite a bit of ASN.1 parsing/writing as part of getting signatures working: https://github.com/NuGet/NuGet.Client/tree/dev/src/NuGet.Core/NuGet.Packaging/Signing/Signatures

    They even have their own DerEncoder.

    It should would be nice to get something public here so we can all stop re-implementing this :)

  13. clairernovotny commented on Jan 18, 2018

    @clairernovotny

    When the ASN.1 types become public API they will become public only for netcoreapp; and then would appear in .NET Framework at some later point; but it won't be applicable retroactively to existing .NET Framework versions.

    Why does this have to be the case? Can they be added to a new standalone .NET Standard library that can be used everywhere rather than baked into the platform components itself?

    For ASN.1 parsing, that seems to be the kind of thing that can be standalone.

  14. bartonjs commented on Jan 18, 2018

    @bartonjs
    MemberAuthor

    FWIW, NuGet seems to have had to implement quite a bit of ASN.1 parsing/writing as part of getting signatures working

    Sort of. They just copied the first draft of this.

    Can they be added to a new standalone .NET Standard library that can be used everywhere rather than baked into the platform components itself?

    No, because then the platform can't use it. (It's particularly a problem for the ability to go back to .NET Framework)

  15. bachratyg commented on Jan 29, 2018

    @bachratyg

    Can this be done like the ValueTuple nuget? Separate package for older platforms, built-in for newer platforms.

  16. 31 remaining items

  17. zivillian commented on Sep 19, 2018

    @zivillian
    Contributor

    After trying to migrate to the XML generator I found a blocking issue (zivillian/ldap.net#5) regarding the tag class.

    With attributes it is possible to specify the tagClass and tagValue:

    [ExpectedTag(TagClass.Application, 10)]
    [OctetString]
    public ReadOnlyMemory<byte>? DelRequest;

    as specified in RFC 4511 - 4.8

    DelRequest ::= [APPLICATION 10] LDAPDN
    
    LDAPDN ::= LDAPString  -- Constrained to <distinguishedName> [RFC4514]
    
    LDAPString ::= OCTET STRING -- UTF-8 encoded, -- [ISO10646] characters
    

    I wasn't able to find a way to set the tagClass in xml, since there is no attribute. Using

    <asn:OctetString name="DelRequest" implicitTag="10"/>

    results in a CryptographicException because the generated code is checking for TagClass.ContextSpecific:

    if (tag.HasSameClassAndValue(new Asn1Tag(TagClass.ContextSpecific, 10)))
    {
    	if (reader.TryGetPrimitiveOctetStringBytes(new Asn1Tag(TagClass.ContextSpecific, 10), out ReadOnlyMemory<byte> tmpDelRequest))
    	{
    		decoded.DelRequest = tmpDelRequest;
    	}
    	else
    	{
    		decoded.DelRequest = reader.ReadOctetString(new Asn1Tag(TagClass.ContextSpecific, 10));
    	}
    }
    else
    {
    	throw new CryptographicException();
    }
  18. bartonjs commented on Sep 19, 2018

    @bartonjs
    MemberAuthor

    @zivillian You could add an attribute in your copy of asn.xsd and process it in asn.xslt to change the class https://github.com/dotnet/corefx/blob/master/src/Common/src/System/Security/Cryptography/Asn1/asn.xslt#L882. We simply haven't had a need for it yet (nothing that we've built used the APPLICATION or PRIVATE classes)

  19. zivillian commented on Sep 19, 2018

    @zivillian
    Contributor

    @bartonjs thanks for your hint, works like a charm zivillian/ldap.net#5 (comment)

  20. clairernovotny commented on Oct 16, 2018

    @clairernovotny

    @bartonjs What are the odds of getting these types made public for .NET Core 3?

  21. bartonjs commented on Nov 23, 2018

    @bartonjs
    MemberAuthor

    @onovotny Public: not great ("temporal mechanics"). But I've closed the gap a bit by copying the reader and writer (and support types) to corefxlab.

    https://dotnet.myget.org/feed/dotnet-corefxlab/package/nuget/System.Security.Cryptography.Asn1.Experimental

    The API there is different than the one here, because it got an extra pass of me looking at the shape, and starting to write down how I'd present it for API review, and then me making all the fixes that I'd bring up during that meeting if it wasn't my feature :). (The good old "let it sit for a couple months and see if you still like it" strategy)

  22. toady commented on Mar 6, 2019

    @toady

    I understand that Application/Private/ContextSpecific tag classes might be out of scope here, but it would be great to not leave them out absolutely, as they are widely used in smart cards industry, for example, including banking (see EMV specifications). And it's all mostly related to cryptography in those areas too.

    The major complexities I see here are:

    1. X-690-201508 BER/DER/CER encodings not only control how the "framing layer" is done - TLV, but also limit the application level in Universal tags. Hence I understand why those two have been combined in current implementation and encapsulated in Asn1Reader and Asn1Writer classes.
    2. Cause of the 'L' part in TLV it's hard to make Asn1Writer work with streams, especially with constructed tags.

    What if we actually try to break the two layers mentioned before apart in the code and introduce one more to control how the actual Asn.1 elements are serialized, say TlvSerializer class that holds a collection of TlvConverter, one of which will be the Asn1Converter to contain all those methods that serealize/deserialize TLV types right now in Asn1Reader and Asn1Writer.

    This way we give users the ability to extend this implementation with their own converters for their Application/Private tag classes. Or even provide extension libraries to deserialize TLV/ASN.1 data into POCO.

  23. bartonjs commented on Mar 6, 2019

    @bartonjs
    MemberAuthor

    @lil-Toady I'm not sure what the context of your comment is...

    I understand that Application/Private/ContextSpecific tag classes might be out of scope here

    The AsnReader and AsnWriter types, both the corefx-internal versions and the corefxlab-public ones, handle Application, Private, Context-Specific, and Universal tags.

    The asn.xslt code generator in corefx doesn't handle Application or Private, but it isn't really a public aspect.

    X-690-201508 BER/DER/CER encodings not only control how the "framing layer" is done - TLV, but also limit the application level in Universal tags.

    I don't follow. AsnReader and AsnWriter understand that UNIVERSAL 2 means Integer, so they won't let you read or write an Integer as UNIVERSAL 3. But you can write an Integer as PRIVATE 900, or APPLICATION 3 or CONTEXT-SPECIFIC 0... it can't say it's not true, so it lets it happen.

    ... introduce one more to control how the actual Asn.1 elements are serialized, say TlvSerializer ...

    I'm not sure how this would help write to Stream... for a DER encoded object you can't write the second byte until you know what the last one is.

    I'm also not sure where you're suggesting it would be / how it would be utilized. The interpretation I'm coming up with is codifying the Encode/Decode contract from what asn.xslt is doing:

    public abstract class AsnSerializer<T>
    {
        public T Decode(AsnReader reader) { throw null; }
        public void Decode(AsnReader reader, out T value) { throw null; }
        protected abstract void DecodeCore(AsnReader reader, out T value) { throw null; }
    
        public void Encode(in T value, AsnWriter writer) { throw null; }
        protected abstract void EncodeCore(in T value, AsnWriter writer) { throw null; }
    }

    but that still seems to require explicit calls to reader.ThrowIfNotEmpty() (making that implicit was my main goal of a serializer). I'm not sure what it buys other than pattern-building and composition (granted, those are useful things). -- But at the same time it sounds like you were intending it within the reader and writer, instead of utilizing the reader and writer, so I might not be following.

    I'm definitely not understanding what going down to something called Tlv instead of Asn gains; if the tag is an ASN.1 class and number (and P/C bit) then it's still "Asn".

  24. transferred this issue fromdotnet/corefxon Jan 31, 2020
  25. added this to the 5.0 milestone on Jan 31, 2020
  26. added
    untriaged
    on Feb 23, 2020
  27. bartonjs commented on Feb 26, 2020

    @bartonjs
    MemberAuthor

    There's now a spec/feature proposal at dotnet/designs#93.

  28. removed
    untriaged
    on May 21, 2020
  29. bartonjs commented on Jun 23, 2020

    @bartonjs
    MemberAuthor

    Fixed by #36729.

  30. ghost locked as resolved and limited conversation to collaborators on Dec 21, 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-needs-workarea-System.Security

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions