-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
X500NameEncoder.cs
575 lines (494 loc) · 21.5 KB
/
X500NameEncoder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Formats.Asn1;
using System.Text;
namespace System.Security.Cryptography.X509Certificates
{
internal static partial class X500NameEncoder
{
private const string OidTagPrefix = "OID.";
private const string UseSemicolonSeparators = ";";
private const string UseCommaSeparators = ",";
private const string UseNewlineSeparators = "\r\n";
private const string DefaultSeparators = ",;";
internal static string X500DistinguishedNameDecode(
byte[] encodedName,
bool printOid,
X500DistinguishedNameFlags flags,
bool addTrailingDelimiter = false)
{
bool reverse = (flags & X500DistinguishedNameFlags.Reversed) == X500DistinguishedNameFlags.Reversed;
bool quoteIfNeeded = (flags & X500DistinguishedNameFlags.DoNotUseQuotes) != X500DistinguishedNameFlags.DoNotUseQuotes;
bool useMultiSeparator = (flags & X500DistinguishedNameFlags.DoNotUsePlusSign) != X500DistinguishedNameFlags.DoNotUsePlusSign;
string dnSeparator;
if ((flags & X500DistinguishedNameFlags.UseSemicolons) == X500DistinguishedNameFlags.UseSemicolons)
{
dnSeparator = "; ";
}
// Explicit UseCommas has preference over explicit UseNewLines.
else if ((flags & (X500DistinguishedNameFlags.UseNewLines | X500DistinguishedNameFlags.UseCommas)) == X500DistinguishedNameFlags.UseNewLines)
{
dnSeparator = Environment.NewLine;
}
else
{
// This is matching Windows (native) behavior, UseCommas does not need to be asserted,
// it is just what happens if neither UseSemicolons nor UseNewLines is specified.
dnSeparator = ", ";
}
string multiValueSparator = useMultiSeparator ? " + " : " ";
try
{
return X500DistinguishedNameDecode(
encodedName,
printOid,
reverse,
quoteIfNeeded,
dnSeparator,
multiValueSparator,
addTrailingDelimiter);
}
catch (CryptographicException)
{
// Windows compat:
return "";
}
}
internal static byte[] X500DistinguishedNameEncode(
string stringForm,
X500DistinguishedNameFlags flags)
{
bool reverse = (flags & X500DistinguishedNameFlags.Reversed) == X500DistinguishedNameFlags.Reversed;
bool noQuotes = (flags & X500DistinguishedNameFlags.DoNotUseQuotes) == X500DistinguishedNameFlags.DoNotUseQuotes;
bool forceUtf8Encoding = (flags & X500DistinguishedNameFlags.ForceUTF8Encoding) == X500DistinguishedNameFlags.ForceUTF8Encoding;
string dnSeparators;
// This rank ordering is based off of testing against the Windows implementation.
if ((flags & X500DistinguishedNameFlags.UseSemicolons) == X500DistinguishedNameFlags.UseSemicolons)
{
// Just semicolon.
dnSeparators = UseSemicolonSeparators;
}
else if ((flags & X500DistinguishedNameFlags.UseCommas) == X500DistinguishedNameFlags.UseCommas)
{
// Just comma
dnSeparators = UseCommaSeparators;
}
else if ((flags & X500DistinguishedNameFlags.UseNewLines) == X500DistinguishedNameFlags.UseNewLines)
{
// CR or LF. Not "and". Whichever is first was the separator, the later one is trimmed as whitespace.
dnSeparators = UseNewlineSeparators;
}
else
{
// Comma or semicolon, but not CR or LF.
dnSeparators = DefaultSeparators;
}
Debug.Assert(dnSeparators.Length != 0);
List<byte[]> encodedSets = ParseDistinguishedName(stringForm, dnSeparators, noQuotes, forceUtf8Encoding);
if (reverse)
{
encodedSets.Reverse();
}
AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
using (writer.PushSequence())
{
foreach (byte[] encodedSet in encodedSets)
{
writer.WriteEncodedValue(encodedSet);
}
}
return writer.Encode();
}
private static bool NeedsQuoting(ReadOnlySpan<char> rdnValue)
{
if (rdnValue.IsEmpty ||
IsQuotableWhitespace(rdnValue[0]) ||
IsQuotableWhitespace(rdnValue[^1]))
{
return true;
}
const string QuoteNeedingChars = ",+=\"\n<>#;"; // \r is NOT in this list, because it isn't in Windows.
return rdnValue.IndexOfAny(QuoteNeedingChars) >= 0;
}
private static bool IsQuotableWhitespace(char c)
{
// There's a whole lot of Unicode whitespace that isn't covered here; but this
// matches what Windows deems quote-worthy.
//
// 0x20: Space
// 0x09: Character Tabulation (tab)
// 0x0A: Line Feed
// 0x0B: Line Tabulation (vertical tab)
// 0x0C: Form Feed
// 0x0D: Carriage Return
return (c == ' ' || (c >= 0x09 && c <= 0x0D));
}
private static void AppendOid(ref ValueStringBuilder decodedName, string oidValue)
{
Oid oid = new Oid(oidValue);
if (StringComparer.Ordinal.Equals(oid.FriendlyName, oidValue) ||
string.IsNullOrEmpty(oid.FriendlyName))
{
decodedName.Append(OidTagPrefix);
decodedName.Append(oid.Value);
}
else
{
decodedName.Append(oid.FriendlyName);
}
decodedName.Append('=');
}
private enum ParseState
{
Invalid,
SeekTag,
SeekTagEnd,
SeekEquals,
SeekValueStart,
SeekValueEnd,
SeekEndQuote,
MaybeEndQuote,
SeekComma,
}
private static List<byte[]> ParseDistinguishedName(
string stringForm,
string dnSeparators,
bool noQuotes,
bool forceUtf8Encoding)
{
// 16 is way more RDNs than we should ever need. A fairly standard set of values is
// { E, CN, O, OU, L, S, C } = 7;
// The EV values add in
// {
// STREET, PostalCode, SERIALNUMBER, 2.5.4.15,
// 1.3.6.1.4.1.311.60.2.1.2, 1.3.6.1.4.1.311.60.2.1.3
// } = 6
//
// 7 + 6 = 13, round up to the nearest power-of-two.
const int InitalRdnSize = 16;
List<byte[]> encodedSets = new List<byte[]>(InitalRdnSize);
ReadOnlySpan<char> chars = stringForm;
int pos;
int end = chars.Length;
int tagStart = -1;
int tagEnd = -1;
ReadOnlySpan<char> tagOid = default;
bool hasTagOid = false;
int valueStart = -1;
int valueEnd = -1;
bool hadEscapedQuote = false;
const char KeyValueSeparator = '=';
const char QuotedValueChar = '"';
ParseState state = ParseState.SeekTag;
for (pos = 0; pos < end; pos++)
{
char c = chars[pos];
switch (state)
{
case ParseState.SeekTag:
if (char.IsWhiteSpace(c))
{
continue;
}
if (char.IsControl(c))
{
state = ParseState.Invalid;
break;
}
// The first character in the tag start.
// We know that there's at least one valid
// character, so make end be start+1.
//
// Single letter values with no whitespace padding them
// (e.g. E=) would otherwise be ambiguous with length.
// (SeekEquals can't set the tagEnd value because it
// doesn't know if it was preceded by whitespace)
// Note that we make no check here for the dnSeparator(s).
// Two separators in a row is invalid (except for UseNewlines,
// and they are only allowed because they are whitespace).
//
// But the throw for an invalid value will come from when the
// OID fails to encode.
tagStart = pos;
tagEnd = pos + 1;
state = ParseState.SeekTagEnd;
break;
case ParseState.SeekTagEnd:
if (c == KeyValueSeparator)
{
goto case ParseState.SeekEquals;
}
if (char.IsWhiteSpace(c))
{
// Tag values aren't permitted whitespace, but there
// can be whitespace between the tag and the separator.
state = ParseState.SeekEquals;
break;
}
if (char.IsControl(c))
{
state = ParseState.Invalid;
break;
}
// We found another character in the tag, so move the
// end (non-inclusive) to the next character.
tagEnd = pos + 1;
break;
case ParseState.SeekEquals:
if (c == KeyValueSeparator)
{
Debug.Assert(tagStart >= 0);
tagOid = ParseOid(chars[tagStart..tagEnd]);
hasTagOid = true;
tagStart = -1;
state = ParseState.SeekValueStart;
break;
}
if (!char.IsWhiteSpace(c))
{
state = ParseState.Invalid;
break;
}
break;
case ParseState.SeekValueStart:
if (char.IsWhiteSpace(c))
{
continue;
}
// If the first non-whitespace character is a quote,
// this is a quoted string. Unless the flags say to
// not interpret quoted strings.
if (c == QuotedValueChar && !noQuotes)
{
state = ParseState.SeekEndQuote;
valueStart = pos + 1;
break;
}
// It's possible to just write "CN=,O=". So we might
// run into the RDN separator here.
if (dnSeparators.Contains(c))
{
valueStart = pos;
valueEnd = pos;
goto case ParseState.SeekComma;
}
state = ParseState.SeekValueEnd;
valueStart = pos;
valueEnd = pos + 1;
break;
case ParseState.SeekEndQuote:
// The only escape sequence in DN parsing is that a quoted
// value can embed quotes via "", the same as a C# verbatim
// string. So, if we see a quote while looking for a close
// quote we need to remember that this might have been the
// end, but be open to the possibility that there's another
// quote coming.
if (c == QuotedValueChar)
{
state = ParseState.MaybeEndQuote;
valueEnd = pos;
break;
}
// Everything else is okay.
break;
case ParseState.MaybeEndQuote:
if (c == QuotedValueChar)
{
state = ParseState.SeekEndQuote;
hadEscapedQuote = true;
valueEnd = -1;
break;
}
// If the character wasn't another quote:
// dnSeparator: process value, state transition to SeekTag
// whitespace: state transition to SeekComma
// anything else: invalid.
// since that's the same table as SeekComma, just change state
// and go there.
state = ParseState.SeekComma;
goto case ParseState.SeekComma;
case ParseState.SeekValueEnd:
// Every time we see a non-whitespace character we need to mark it
if (dnSeparators.Contains(c))
{
goto case ParseState.SeekComma;
}
if (char.IsWhiteSpace(c))
{
continue;
}
// Including control characters.
valueEnd = pos + 1;
break;
case ParseState.SeekComma:
if (dnSeparators.Contains(c))
{
Debug.Assert(hasTagOid);
Debug.Assert(valueEnd != -1);
Debug.Assert(valueStart != -1);
encodedSets.Add(ParseRdn(tagOid, chars[valueStart..valueEnd], hadEscapedQuote, forceUtf8Encoding));
hasTagOid = false;
valueStart = -1;
valueEnd = -1;
state = ParseState.SeekTag;
break;
}
if (!char.IsWhiteSpace(c))
{
state = ParseState.Invalid;
break;
}
break;
default:
Debug.Fail($"Invalid parser state. Position {pos}, State {state}, Character {c}, String \"{stringForm}\"");
throw new CryptographicException(SR.Cryptography_Invalid_X500Name);
}
if (state == ParseState.Invalid)
{
break;
}
}
// Okay, so we've run out of input. There are a couple of valid states we can be in.
// * 'CN='
// state: SeekValueStart. Neither valueStart nor valueEnd has a value yet.
// * 'CN=a'
// state: SeekValueEnd. valueEnd was set to pos(a) + 1, close it off.
// * 'CN=a '
// state: SeekValueEnd. valueEnd is marking at the start of the whitespace.
// * 'CN="a"'
// state: MaybeEndQuote. valueEnd is marking at the end-quote.
// * 'CN="a" '
// state: SeekComma. This is the same as MaybeEndQuote.
// * 'CN=a,'
// state: SeekTag. There's nothing to do here.
// * ''
// state: SeekTag. There's nothing to do here.
//
// And, of course, invalid ones.
// * 'CN="'
// state: SeekEndQuote. Throw.
// * 'CN':
// state: SeekEndTag. Throw.
switch (state)
{
// The last semantic character parsed was =.
case ParseState.SeekValueStart:
valueStart = chars.Length;
valueEnd = valueStart;
goto case ParseState.SeekComma;
// If we were in an unquoted value and just ran out of text
case ParseState.SeekValueEnd:
Debug.Assert(!hadEscapedQuote);
goto case ParseState.SeekComma;
// If the last character was a close quote, or it was a close quote
// then some whitespace.
case ParseState.MaybeEndQuote:
case ParseState.SeekComma:
Debug.Assert(tagOid != null);
Debug.Assert(valueStart != -1);
Debug.Assert(valueEnd != -1);
encodedSets.Add(ParseRdn(tagOid, chars[valueStart..valueEnd], hadEscapedQuote, forceUtf8Encoding));
break;
// If the entire string was empty, or ended in a dnSeparator.
case ParseState.SeekTag:
break;
default:
// While this is an error, it should be due to bad input, so no Debug.Fail.
throw new CryptographicException(SR.Cryptography_Invalid_X500Name);
}
return encodedSets;
}
private static ReadOnlySpan<char> ParseOid(ReadOnlySpan<char> str)
{
if (str.Length > OidTagPrefix.Length)
{
bool prefixed = str.StartsWith(OidTagPrefix, StringComparison.OrdinalIgnoreCase);
if (prefixed)
{
return str.Slice(OidTagPrefix.Length);
}
}
return new Oid(str.ToString()).Value; // Value can be null, but permit the null-to-empty conversion.
}
private static byte[] ParseRdn(ReadOnlySpan<char> tagOid, ReadOnlySpan<char> chars, bool hadEscapedQuote, bool forceUtf8Encoding)
{
scoped ReadOnlySpan<char> data;
if (hadEscapedQuote)
{
const int MaxStackAllocSize = 256;
Span<char> destination = chars.Length > MaxStackAllocSize ?
new char[chars.Length] :
stackalloc char[MaxStackAllocSize];
int written = ExtractValue(chars, destination);
data = destination.Slice(0, written);
}
else
{
data = chars;
}
AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
using (writer.PushSetOf())
using (writer.PushSequence())
{
try
{
writer.WriteObjectIdentifier(tagOid);
}
catch (ArgumentException e)
{
throw new CryptographicException(SR.Cryptography_Invalid_X500Name, e);
}
if (tagOid.SequenceEqual(Oids.EmailAddress))
{
try
{
// An email address with an invalid value will throw.
writer.WriteCharacterString(UniversalTagNumber.IA5String, data);
}
catch (EncoderFallbackException)
{
throw new CryptographicException(SR.Cryptography_Invalid_IA5String);
}
}
else if (forceUtf8Encoding)
{
writer.WriteCharacterString(UniversalTagNumber.UTF8String, data);
}
else
{
try
{
writer.WriteCharacterString(UniversalTagNumber.PrintableString, data);
}
catch (EncoderFallbackException)
{
writer.WriteCharacterString(UniversalTagNumber.UTF8String, data);
}
}
}
return writer.Encode();
}
private static int ExtractValue(ReadOnlySpan<char> chars, Span<char> destination)
{
Debug.Assert(destination.Length >= chars.Length);
bool skippedQuote = false;
int written = 0;
foreach (char c in chars)
{
if (c == '"' && !skippedQuote)
{
skippedQuote = true;
continue;
}
// If we just skipped a quote, this will be one.
// If this is a quote, we should have just skipped one.
Debug.Assert(skippedQuote == (c == '"'));
skippedQuote = false;
destination[written++] = c;
}
return written;
}
}
}