Repository navigation
Description
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
jnm2 commentedon Jul 3, 2017
I'm interested to see what you come up with so I can compare it to my fast forward-only ASN.1 reader.
bachratyg commentedon Jul 3, 2017
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.
bartonjs commentedon Jul 3, 2017
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.
vcsjones commentedon Jul 11, 2017
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.
bartonjs commentedon Jul 11, 2017
@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 😄.
danmoseley commentedon Dec 1, 2017
@bartonjs estimates 1 week remaining
ebekker commentedon Dec 2, 2017
Awesome! Reader only or does that also include serialization?
bartonjs commentedon Dec 2, 2017
@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:
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.
ebekker commentedon Dec 4, 2017
Wow, thanks for the update.
jariq commentedon Dec 28, 2017
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?
bartonjs commentedon Jan 3, 2018
@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.
clairernovotny commentedon Jan 18, 2018
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 :)
clairernovotny commentedon Jan 18, 2018
Why does this have to be the case? Can they be added to a new standalone
.NET Standardlibrary 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.
bartonjs commentedon Jan 18, 2018
Sort of. They just copied the first draft of this.
No, because then the platform can't use it. (It's particularly a problem for the ability to go back to .NET Framework)
bachratyg commentedon Jan 29, 2018
Can this be done like the ValueTuple nuget? Separate package for older platforms, built-in for newer platforms.
31 remaining items
zivillian commentedon Sep 19, 2018
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:
as specified in RFC 4511 - 4.8
I wasn't able to find a way to set the tagClass in xml, since there is no attribute. Using
results in a
CryptographicExceptionbecause the generated code is checking forTagClass.ContextSpecific:bartonjs commentedon Sep 19, 2018
@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)
zivillian commentedon Sep 19, 2018
@bartonjs thanks for your hint, works like a charm zivillian/ldap.net#5 (comment)
clairernovotny commentedon Oct 16, 2018
@bartonjs What are the odds of getting these types made public for .NET Core 3?
bartonjs commentedon Nov 23, 2018
@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)
toady commentedon Mar 6, 2019
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:
Asn1ReaderandAsn1Writerclasses.Asn1Writerwork 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
TlvSerializerclass that holds a collection ofTlvConverter, one of which will be the Asn1Converter to contain all those methods that serealize/deserialize TLV types right now inAsn1ReaderandAsn1Writer.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.
bartonjs commentedon Mar 6, 2019
@lil-Toady I'm not sure what the context of your comment is...
The
AsnReaderandAsnWritertypes, both the corefx-internal versions and the corefxlab-public ones, handle Application, Private, Context-Specific, and Universal tags.The
asn.xsltcode generator in corefx doesn't handle Application or Private, but it isn't really a public aspect.I don't follow.
AsnReaderandAsnWriterunderstand 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.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.xsltis doing: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
Tlvinstead ofAsngains; if the tag is an ASN.1 class and number (and P/C bit) then it's still "Asn".bartonjs commentedon Feb 26, 2020
There's now a spec/feature proposal at dotnet/designs#93.
bartonjs commentedon Jun 23, 2020
Fixed by #36729.