Repository navigation
Description
I was giving some hints on this StackOverflow question where the idea of a PEM reader / writer for .NET was coming up. Jeremy then posted that if such a reader was available that it would be a nice idea to make it a one-shot, RFC 7468 compliant reader using the new Span<char> framework.
So I've created a sample implementation / API proposal which performs the parsing of the "lax" (i.e. permissive). I've used the following additional goals / non-goals:
Goals:
- no dynamic memory allocation that depends on the size of the input;
- possibility to skip a description (in front) of the PEM structure;
- possibility to detect the end of the PEM structure, if present;
- related: allow for parsing multiple PEM structures from a single
Span; - design in the spirit of other methods that use
Span;
Non-goals:
- returning the description in front of the PEM file;
- detailed error reporting;
- streaming implementation (requiring state machine or buffering);
- parsing the base64 inside the header / footer lines (pre/post encapsulation boundaries);
- support for stricter versions of PEM;
- return or comparison of the label in the footer.
Niceties:
- validation of the base64 inside the header / footer lines
- return the amount of bytes so that a correctly sized buffer can be created in advance for the base64 decryption (yes, implemented).
Parsing the base64 is easily done afterwards with the existing parser, and we may just want to skip the PEM.
Note that I didn't get my Unit testing working for Core 3, so the implementation has not yet received any significant testing. First let me know what you think.
Implementation notes: this implementation searches for the post-encapsulation boundary (footer) before validating the base64. It might be possible to use a state machine instead to create a single pass parser. This adds significant complexity to the parsing though, and searching for a static string should be relatively performant already.
Code in followup comment for now, as I don't know yet where to put it.
(Edited in):
API Proposal
namespace System.Security.Cryptography
{
public static class PemEncoding
{
public static bool TryFind(ReadOnlySpan<char> pemData, out PemFields fields) => throw null;
public static PemFields Find(ReadOnlySpan<char> pemData) => throw null;
public static int GetEncodedSize(int labelLength, int dataLength) => throw null;
public static bool TryWrite(ReadOnlySpan<char> label, ReadOnlySpan<byte> data, Span<char> destination, out int charsWritten) => throw null;
public static char[] Write(ReadOnlySpan<char> label, ReadOnlySpan<byte> data) => throw null;
}
public readonly struct PemFields
{
internal PemFields(Range label, Range base64data, Range location, int decodedDataLength) => throw null;
public Range Location { get; }
public Range Label { get; }
public Range Base64Data { get; }
public int DecodedDataLength { get; }
}
}
Activity
owlstead commentedon May 17, 2019
Here is the proposed API / implementation code:
PS removed one or two copy / paste bugs during edit, nothing big
bartonjs commentedon May 17, 2019
Thanks, @owlstead!
From a requirements perspective, things that I can see someone wanting to do:
"-----BEGIN ".Length)endOfPEMvaluecontents. Good there.label.bytesInContentSo I think, functionality-wise, it meets the needs.
Other things that might be reasonable for PEM (to help identify a type container for this)
ReadOnlySpan<byte>and a label to an outputSpan<char>, or a Stream, etc.Restricting to the cryptography uses of PEM (RFC 7468) makes all of this so much easier than my original thoughts, since the header/attributes section is out of scope.
Additionally, I know I'm the one who suggested
(ReadOnlySpan<char>, out ReadOnlySpan<char>, out ReadOnlySpan<char>), but I'm wondering if the extra data makes the signature too unwieldy and that it'd be better to return the parse state as a struct.I'll ignore my last sentence for now, to give the theoretical state of
I'm not entirely sold on the method names of any of the methods, just starting the creative juices flowing. In particular, it seems like AsnWriter variants should be proper overloads, so the "Write" name should unify.
Feels... wrongish.
owlstead commentedon May 17, 2019
OK, I can see that giving the start of the PEM might also be a good idea, as that will automatically show how to get the "description" or pre-amble, where needed (presuming that the right
Spanis given, excluding any previous PEM as you would need the start offset). We could create a PEM class with a static methods andContentclass.The
Contentclass would be a simple class with a single cto and getters (I don't see a use case for changing existing PEM content). We could still return aboolas to be compliant withe the general signature of theTry...methods and return the data class or struct in anoutparameter.Maybe we should return the
labelas astringrather than aSpan, with the disadvantage that we should then think of an upperbound. I don't see any other use of thelabelother than as a string. Say 64 characters should be plenty (it would already be more than the default PEM line size after all, so nobody with any sense would create such a label).Otherwise I would largely agree with your interface specification. I could, if you want, think of a
ReadDatamethod implementation as well (using an additional pass maybe, who cares, CPU's are plenty fast anyway). I'm visiting my family, will post an enhanced API spec. later.bartonjs commentedon May 17, 2019
The advantage of emitting the label as a
ReadOnlySpan<char>vs astringis that it is just a projection over the input. If the caller needs it as a System.String they can call ToString() on the span value.While it's also true that a string can go to a (read-only) span, the string required making a new object and a copy (since .NET strings are length-prepended for performance and null-terminated for interop).
So a string (or System.Range) would make sense for returning it as a field in a parse structure, but the span has advantage when it can be done via the
outparameter.owlstead commentedon May 18, 2019
As for that last comment, I don't see any advantage myself to keep
labelto aSpan. SureToStringornew Stringis easily performed, but you've got to ask yourself why theSpanis ever needed in the first place. From a user point of view it doesn't make sense and copying such small amounts doesn't have any performance benefits, in my opinion. It feels like over-optimization to me.So what seems natural to me is to supply:
I've used "Smurf naming conventions" to allow for
using staticto be used for the static methods.Other changes in order of appearance:
PEMEncodingto justPEMfor simplicity sake (debatable, but PEM is an encoding by itself, can change back);FieldsWithBase64should really beFieldsWithContentsInBase64but yeah...);TryFindPemas it may be trying to find the first PEM struture;TryWriteDatatoTryWritePemas I foundDatato be too generic, and for symmetry withTryFindPem.Most importantly I removed
WriteDatafrom the class in its entirety as it would require a full rewrite (unless you would count creating aSpan<char>over a newchar[]as acceptable solution). It also mixes high level streaming and low level spanning components, which seems a bad idea in itself (where would it end?). It could of course be added later.Very much interested in your opinions!
Oh, yeah, got Unit testing working and have a working implementation of above. Added constructors and methods to
ref structs, with a methodFieldsWithBase64.GetFieldswhich performs the base64 decoding as convenience method.owlstead commentedon May 19, 2019
Oh, I can test things now. I used command line to create a test project and then imported in VS. However, before I test I would like to know if the API is OK-ish this way.
Note that I'm personally not that happy with evaluating my own application. I am critical enough to think of some pretty nasty tests (boundary tests), but I cannot change my own thought process. So some review will of course be required.
bartonjs commentedon May 19, 2019
When reading a large multi-PEM (like /etc/ssl/certs.pem) the allocations of each string would cause the GC to kick in more often, which can have impact on servers. Of course, the API could internally avoid that by caching known (or encountered) strings and returning the string that is equivalent to the identified span... so then it comes down to a) always allocate a string (easy, usable, higher GC impact), b) returned shared strings (more work, usable, low GC impact), c) just return a span (easy, less friendly than string, no GC impact).
Since very few different names are expected I'm sure that (a) would end up being (b) if we switched to using this to read /etc/ssl/certs.pem on Linux.
Type name:
RSA, DSA, and ECDsa definitely already violate the rule, but the rule is that acronyms should either be expanded or be treated as a simple word, so "PEM" (Privacy Enhanced Mail) would be "Pem". I threw "Encoding" on it because "Pem" as a standalone typename felt weird, and it's using the data encoding model from PEM without actually being about Privacy Enhanced Mail. (The actual guideline is "DO capitalize only the first character of acronyms with three or more characters, except the first word of a camel-cased identifier.")
Methods/Structs:
public readonly ref struct.falsereturnchars, notbytes, so a TextWriter would be more appropriate). But it can be left off until such a review meeting.using static. But I don't see a rule for it.Span<byte>there's anout int bytesWritten, forSpan<char>it'sout int charsWritten, and for any other Span type else it's (IIRC)out int written). It's just the convention we have (and will eventually be codified), so I've gone ahead and restored the out.So, using "on the fence" means "don't change it", I'd suggest
And a formal API review would likely add
public static char[] Write(ReadOnlySpan<char> label, ReadOnlySpan<byte> contentBytes)andpublic static void Write(TextWriter destination, ReadOnlySpan<char> label, ReadOnlySpan<byte> contentBytes). API review might also do more cosmetic changes on the names.Testing:
I'd just expect tests to go in src/System.Security.Cryptography.Encoding/tests/, along with the rest of the xunit tests. After you build src/System.Security.Cryptography.Encoding/ref/ with the new API structure the tests should be able to reference it. (
msbuild /t:BuildAndTest /p:ForceRunTests=trueto run the tests (even if they succeeded previously), and they should automatically see updated binaries after src/System.Security.Cryptography.Encoding/src is rebuilt.One test that I think you're missing, from the current code: reading a payload with mismatched labels:
The usual flow, per https://github.com/dotnet/corefx/blob/master/Documentation/project-docs/api-review-process.md, is
api-ready-for-reviewapi-approvedas-isapi-approvedwith suggestions (e.g. rename some things)api-needs-workwith questions/comments (and the issue is now back in "Discussion")Of course, sometimes it takes actually doing the implementation and tests to understand how the API really needs to work.. Mainly I'm sharing that just because you and I think we've hit a good state, doesn't mean the (rest of the) API review will agree 😄.
bartonjs commentedon May 19, 2019
@vcsjones / @onovotny: Do either of you have any API feedback here? Missing scenarios, over-engineering, et cetera?
vcsjones commentedon May 19, 2019
I'm leaning toward
Labelbeing aROS<char>here if not because of performance for this specifically but because the whole API proposal seems geared toward being efficient. The use of aref structpresents some use constraints of a developer. It seems odd to use aref structandROS<char>for the content but then allocate for the label.If I were using this API (which is a great idea!) my typical usage pattern would probably be something like:
So I don't think using
ROS<char>feels like an optimization at any significant cost to the developer. That is if my supposed typical-usage is close.If we feel that a
ROS<char>forLabelis over-optimized then I might suggest that applies to much of the rest of the API proposal, and change the whole struct to not berefand instead operate entirely onReadOnlyMemory<char>. That will let developers use the result as they are used to being able to use things, like return it from a method, add them to aList<T>, or put the result in a field.I don't actually like my idea, I much prefer
{ReadOnly}Span<char>here, but if we are OK with allocations then we can use that to the advantage of making the API more developer-friendly.In the proposal the
FieldsWithBase64contains actual fields. Most of the API surface in the rest of the framework uses properties, even on readonly ref structs (e.g.Span<T>itself). Any particular reason to use fields here? I don't see any harm in it either, but it feels unconventional to me to add API surface exposing fields.ContentSizeBytesseems ambiguous to me.DecodedContentSizeorDecodedContentSizeBytesmight help folks understand what the size refers to (though I have a personal distaste for puttingBytesin member names to indicate the size refers to bytes)owlstead commentedon May 20, 2019
OK, so I've tried to take all your comments into consideration and came up with the following API, which is currently implemented and running some tests; I've simply refactored.
I've checked that the writers write all the PEM structures in the RFC, doing a full compare afterwards. I'm also skipping / parsing the following PEM's successfully even though they are obviously tosh:
Then I can write them again as strictly formatted PEM.
I've added a
SkipWhiteSpaceimplementation method. The previous implementation ofTryFinddid not skip blanks and / or the first line ending after the post-encapsulation boundary (aka footer), which it should do (also according to the RFC).I'm not completely happy with the
EncodedByteSizeandGetEncodedSizeidentifier names as they both contain the nameEncodedand rely too much on the context to understand. What aboutBase64EncodedDataSizeandGetEncodedPemSize? They are slightly larger, but more clear in my opinion.Note that I'm quite the polyglot w.r.t. PL, but sometimes it takes a bit of time to get up to speed with e.g. C# best practices - I'm pretty much rooted in Java, taking up Kotlin as well.
owlstead commentedon May 21, 2019
OK, let's discuss the two bears left: streaming support and error handling.
The problem with streaming is that it doesn't allow to back track a stream. However, it is required if e.g. large CMS structures need to be supported because those can be of arbitrary length and not fit into memory. It is useful but maybe not required if PEM structures are present in a stream e.g. received through HTTP.
As for the large data structures: it seems .NET only supports encoding of data in a
byte[]currently. So although streaming would definitely be useful for large messages, I don't see how we could do anything with the result that doesn't require at least one full copy in memory (correct me if I'm wrong about this). If the message size is not known in advance then you can simply create a buffer of a particular size and stop if it doesn't fit. So basically I think a streaming API doesn't seem to be useful in the short run.It is relatively easy to add streaming for the generating part, but it would not be a symmetric API. I think I saw some requests to do this, so we could basically copy the generation code as I don't see any generic way of merging the two.
Now for the error handling. Currently the
TryFindmessage simply returnsfalseif there is any error in the PEM, even if a full preeb (header line) is found and if there is a base64 encoding mistake. This doesn't feel right to me, I'd say that if there is a full preeb that an exception should be thrown if there are any mistakes. I don't think it makes too much sense to keep parsing after an error, so returning the location of the error doesn't make too much sense (for a one-shot decoder).Finally: should we create a
Readmethod that errors out if no PEM / preeb is found at the start of theSpan<char>? I don't think it would be all that useful as having text in front of the PEM is always allowed by the standard. If required, people can always question the returnedRangeand test if the PEM starts at offset zero after all. We could however think of aFindwithoutTrythat returns a byte array and throws an exception if no PEM could be found.vcsjones commentedon May 21, 2019
That seems reasonable. Using personal experience I would see myself using this for small PEM bundles that supply a certificate chain and reading a few kilobytes into memory shouldn't be problematic.
My suggestion now would be to get this API done now and consider streaming as a separate API proposal. It could either be added on later to these types or perhaps a new
PemEncodingStreamclass that uses this as its internals.Throwing exceptions would probably be useful, though I can't say with any certainly. Some .NET developers have taken
Try-prefixed methods to mean "does not throw" likeTryParse*methods.I agree with that, especially if this is intended to be a "lax" parser.
bartonjs commentedon May 31, 2019
For the API shape: I think that the nested struct needs to move out to be a peer type. We don't have crisp guidelines here, but it boils down to something like "If the average person working with the API needs to use the type by name, it shouldn't be nested". Since it's the output of the primary API (TryFind) it seems pretty "average user" to me. (So what does get to be a public nested type? Mostly struct-based iterators that most people never see, they just put the call in a foreach and let things happen).
"Base64Fields" is a little generic once it moves out. ParsedPemFields, maybe? (Or PemFields?)
I don't think that the output struct needs the DecodeBase64 method on it. Since the base64 data is already exposed the caller can just use the existing base64 decoding APIs.
I accept the logic here. Leaving it out until there's a demand seems reasonable.
We have guidance on this, which is (effectively) all
falseresponses need the same recovery action (different recovery action? throw.). So the question is really "as a caller, do you want to know the difference between 'no header found', 'no footer found', and 'contains attributes / has invalid base64'" (attributes being invalid base64), or are they all simply "there's no RFC 7468-PEM here"? Alternatively phrased, shouldfind "B", or throw? I'm, personally, having trouble deciding which I want it to do, so I'm wide open to suggestions.
(I think I might be leaning toward false means no preeb was found, and throw for "couldn't successfully get to the end" (bad base64, can't find a posteb))
I think that
Find, to be effectivelyTryFind+ throw instead of false is useful, it simplifies the "I'm not testing, I'm asserting" case (and matches the guideline "DO provide an exception-throwing member for each member using the Try-Parse Pattern.").I agree that there's not a lot of value in the "the first (or first non-whitespace) character wasn't
-" version, and it's easy enough for someone to write themselves given the output of Find.Yeah, it's more than 3 lines of code, but it's not tricky logic... and given that the RFC says leaders are allowed, it doesn't fit with the class.
owlstead commentedon May 31, 2019
I'm all open to use
PemFieldsas a separate instance. I'll check if I can get that to work withSpan.Ah, and here I just inserted the exceptions. Personally I'm in favor of throwing errors when if a full header line / pre encap boundary is found (i.e. five dashes, BEGIN, some kind of label (any chars) and then five dashes again. Because if anything is wrong, then it is hard to argue that this is not the PEM that you were looking for. Basically you ask to find it a PEM, it finds a full header, but then still returns false. What would you do next as a user? And if no exception is thrown then symmetry is also lost between TryFind and Find. So yeah, I'm not convinced that returning false instead of a
FormatExceptionis a good idea.I'll try and finish cleaning up the code and post early next week. I haven't got a compiled version of Core 3 here so I'll just post it as a file (or two) here if you don't mind. I've got a holiday coming so time is getting precious (and I need to post soon because the race may eat me, lookup "Pointe du Raz" and then imagine kajaking in it :P ).
owlstead commentedon Jun 3, 2019
Sorry, things taking too much time. I hope tomorrow or Wednesday.
12 remaining items
bartonjs commentedon Feb 3, 2020
@vcsjones Once we can close down on
DecodedByteSizevsDecodedDataLengthI think this is ready to go back through review. (If you actually prefer DecodedByteSize, I'd like to understand why; perhaps I'll come around 😄)vcsjones commentedon Feb 3, 2020
@bartonjs I amended my comment here which I think is the most "current" proposal with changes: #29588 (comment)
No preference, I don't think? Maybe I had a stronger opinion a month ago that I am unable to recall. Regardless,
DecodedDataLengthseems sensible.terrajobst commentedon Feb 4, 2020
Video
PemFieldsisn't public to avoid having to validate well-formednessPemFieldsimplement IEquatable`?danmoseley commentedon Feb 6, 2020
Is anyone interested in implementing this? I would like to get it in 5.0. @owlstead @vcsjones
vcsjones commentedon Feb 7, 2020
@danmosemsft It looks like @owlstead has already invested a good chunk of time in to it, but if @owlstead is unable to or no longer wishes to, I can probably do this next after I wrap up #2406.