This repository has been archived by the owner on Oct 24, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpkixnames.cpp
2039 lines (1867 loc) · 73.2 KB
/
pkixnames.cpp
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This code is made available to you under your choice of the following sets
* of licensing terms:
*/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/* Copyright 2014 Mozilla Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This code implements RFC6125-ish name matching, RFC5280-ish name constraint
// checking, and related things.
//
// In this code, identifiers are classified as either "presented" or
// "reference" identifiers are defined in
// http://tools.ietf.org/html/rfc6125#section-1.8. A "presented identifier" is
// one in the subjectAltName of the certificate, or sometimes within a CN of
// the certificate's subject. The "reference identifier" is the one we are
// being asked to match the certificate against. When checking name
// constraints, the reference identifier is the entire encoded name constraint
// extension value.
#include "pkixcheck.h"
#include "pkixutil.h"
namespace mozilla { namespace pkix {
namespace {
// GeneralName ::= CHOICE {
// otherName [0] OtherName,
// rfc822Name [1] IA5String,
// dNSName [2] IA5String,
// x400Address [3] ORAddress,
// directoryName [4] Name,
// ediPartyName [5] EDIPartyName,
// uniformResourceIdentifier [6] IA5String,
// iPAddress [7] OCTET STRING,
// registeredID [8] OBJECT IDENTIFIER }
enum class GeneralNameType : uint8_t
{
// Note that these values are NOT contiguous. Some values have the
// der::CONSTRUCTED bit set while others do not.
// (The der::CONSTRUCTED bit is for types where the value is a SEQUENCE.)
otherName = der::CONTEXT_SPECIFIC | der::CONSTRUCTED | 0,
rfc822Name = der::CONTEXT_SPECIFIC | 1,
dNSName = der::CONTEXT_SPECIFIC | 2,
x400Address = der::CONTEXT_SPECIFIC | der::CONSTRUCTED | 3,
directoryName = der::CONTEXT_SPECIFIC | der::CONSTRUCTED | 4,
ediPartyName = der::CONTEXT_SPECIFIC | der::CONSTRUCTED | 5,
uniformResourceIdentifier = der::CONTEXT_SPECIFIC | 6,
iPAddress = der::CONTEXT_SPECIFIC | 7,
registeredID = der::CONTEXT_SPECIFIC | 8,
// nameConstraints is a pseudo-GeneralName used to signify that a
// reference ID is actually the entire name constraint extension.
nameConstraints = 0xff
};
inline Result
ReadGeneralName(Reader& reader,
/*out*/ GeneralNameType& generalNameType,
/*out*/ Input& value)
{
uint8_t tag;
Result rv = der::ReadTagAndGetValue(reader, tag, value);
if (rv != Success) {
return rv;
}
switch (tag) {
case static_cast<uint8_t>(GeneralNameType::otherName):
generalNameType = GeneralNameType::otherName;
break;
case static_cast<uint8_t>(GeneralNameType::rfc822Name):
generalNameType = GeneralNameType::rfc822Name;
break;
case static_cast<uint8_t>(GeneralNameType::dNSName):
generalNameType = GeneralNameType::dNSName;
break;
case static_cast<uint8_t>(GeneralNameType::x400Address):
generalNameType = GeneralNameType::x400Address;
break;
case static_cast<uint8_t>(GeneralNameType::directoryName):
generalNameType = GeneralNameType::directoryName;
break;
case static_cast<uint8_t>(GeneralNameType::ediPartyName):
generalNameType = GeneralNameType::ediPartyName;
break;
case static_cast<uint8_t>(GeneralNameType::uniformResourceIdentifier):
generalNameType = GeneralNameType::uniformResourceIdentifier;
break;
case static_cast<uint8_t>(GeneralNameType::iPAddress):
generalNameType = GeneralNameType::iPAddress;
break;
case static_cast<uint8_t>(GeneralNameType::registeredID):
generalNameType = GeneralNameType::registeredID;
break;
default:
return Result::ERROR_BAD_DER;
}
return Success;
}
enum class FallBackToSearchWithinSubject { No = 0, Yes = 1 };
enum class MatchResult
{
NoNamesOfGivenType = 0,
Mismatch = 1,
Match = 2
};
Result SearchNames(const Input* subjectAltName, Input subject,
GeneralNameType referenceIDType,
Input referenceID,
FallBackToSearchWithinSubject fallBackToCommonName,
/*out*/ MatchResult& match);
Result SearchWithinRDN(Reader& rdn,
GeneralNameType referenceIDType,
Input referenceID,
FallBackToSearchWithinSubject fallBackToEmailAddress,
FallBackToSearchWithinSubject fallBackToCommonName,
/*in/out*/ MatchResult& match);
Result MatchAVA(Input type,
uint8_t valueEncodingTag,
Input presentedID,
GeneralNameType referenceIDType,
Input referenceID,
FallBackToSearchWithinSubject fallBackToEmailAddress,
FallBackToSearchWithinSubject fallBackToCommonName,
/*in/out*/ MatchResult& match);
Result ReadAVA(Reader& rdn,
/*out*/ Input& type,
/*out*/ uint8_t& valueTag,
/*out*/ Input& value);
void MatchSubjectPresentedIDWithReferenceID(GeneralNameType presentedIDType,
Input presentedID,
GeneralNameType referenceIDType,
Input referenceID,
/*in/out*/ MatchResult& match);
Result MatchPresentedIDWithReferenceID(GeneralNameType presentedIDType,
Input presentedID,
GeneralNameType referenceIDType,
Input referenceID,
/*in/out*/ MatchResult& matchResult);
Result CheckPresentedIDConformsToConstraints(GeneralNameType referenceIDType,
Input presentedID,
Input nameConstraints);
uint8_t LocaleInsensitveToLower(uint8_t a);
bool StartsWithIDNALabel(Input id);
enum class IDRole
{
ReferenceID = 0,
PresentedID = 1,
NameConstraint = 2,
};
enum class AllowWildcards { No = 0, Yes = 1 };
// DNSName constraints implicitly allow subdomain matching when there is no
// leading dot ("foo.example.com" matches a constraint of "example.com"), but
// RFC822Name constraints only allow subdomain matching when there is a leading
// dot ("foo.example.com" does not match "example.com" but does match
// ".example.com").
enum class AllowDotlessSubdomainMatches { No = 0, Yes = 1 };
bool IsValidDNSID(Input hostname, IDRole idRole,
AllowWildcards allowWildcards);
Result MatchPresentedDNSIDWithReferenceDNSID(
Input presentedDNSID,
AllowWildcards allowWildcards,
AllowDotlessSubdomainMatches allowDotlessSubdomainMatches,
IDRole referenceDNSIDRole,
Input referenceDNSID,
/*out*/ bool& matches);
Result MatchPresentedRFC822NameWithReferenceRFC822Name(
Input presentedRFC822Name, IDRole referenceRFC822NameRole,
Input referenceRFC822Name, /*out*/ bool& matches);
} // unnamed namespace
bool IsValidReferenceDNSID(Input hostname);
bool IsValidPresentedDNSID(Input hostname);
bool ParseIPv4Address(Input hostname, /*out*/ uint8_t (&out)[4]);
bool ParseIPv6Address(Input hostname, /*out*/ uint8_t (&out)[16]);
// This is used by the pkixnames_tests.cpp tests.
Result
MatchPresentedDNSIDWithReferenceDNSID(Input presentedDNSID,
Input referenceDNSID,
/*out*/ bool& matches)
{
return MatchPresentedDNSIDWithReferenceDNSID(
presentedDNSID, AllowWildcards::Yes,
AllowDotlessSubdomainMatches::Yes, IDRole::ReferenceID,
referenceDNSID, matches);
}
// Verify that the given end-entity cert, which is assumed to have been already
// validated with BuildCertChain, is valid for the given hostname. hostname is
// assumed to be a string representation of an IPv4 address, an IPv6 addresss,
// or a normalized ASCII (possibly punycode) DNS name.
Result
CheckCertHostname(Input endEntityCertDER, Input hostname)
{
BackCert cert(endEntityCertDER, EndEntityOrCA::MustBeEndEntity, nullptr);
Result rv = cert.Init();
if (rv != Success) {
return rv;
}
const Input* subjectAltName(cert.GetSubjectAltName());
Input subject(cert.GetSubject());
// For backward compatibility with legacy certificates, we fall back to
// searching for a name match in the subject common name for DNS names and
// IPv4 addresses. We don't do so for IPv6 addresses because we do not think
// there are many certificates that would need such fallback, and because
// comparisons of string representations of IPv6 addresses are particularly
// error prone due to the syntactic flexibility that IPv6 addresses have.
//
// IPv4 and IPv6 addresses are represented using the same type of GeneralName
// (iPAddress); they are differentiated by the lengths of the values.
MatchResult match;
uint8_t ipv6[16];
uint8_t ipv4[4];
if (IsValidReferenceDNSID(hostname)) {
rv = SearchNames(subjectAltName, subject, GeneralNameType::dNSName,
hostname, FallBackToSearchWithinSubject::Yes, match);
} else if (ParseIPv6Address(hostname, ipv6)) {
rv = SearchNames(subjectAltName, subject, GeneralNameType::iPAddress,
Input(ipv6), FallBackToSearchWithinSubject::No, match);
} else if (ParseIPv4Address(hostname, ipv4)) {
rv = SearchNames(subjectAltName, subject, GeneralNameType::iPAddress,
Input(ipv4), FallBackToSearchWithinSubject::Yes, match);
} else {
return Result::ERROR_BAD_CERT_DOMAIN;
}
if (rv != Success) {
return rv;
}
switch (match) {
case MatchResult::NoNamesOfGivenType: // fall through
case MatchResult::Mismatch:
return Result::ERROR_BAD_CERT_DOMAIN;
case MatchResult::Match:
return Success;
MOZILLA_PKIX_UNREACHABLE_DEFAULT_ENUM
}
}
// 4.2.1.10. Name Constraints
Result
CheckNameConstraints(Input encodedNameConstraints,
const BackCert& firstChild,
KeyPurposeId requiredEKUIfPresent)
{
for (const BackCert* child = &firstChild; child; child = child->childCert) {
FallBackToSearchWithinSubject fallBackToCommonName
= (child->endEntityOrCA == EndEntityOrCA::MustBeEndEntity &&
requiredEKUIfPresent == KeyPurposeId::id_kp_serverAuth)
? FallBackToSearchWithinSubject::Yes
: FallBackToSearchWithinSubject::No;
MatchResult match;
Result rv = SearchNames(child->GetSubjectAltName(), child->GetSubject(),
GeneralNameType::nameConstraints,
encodedNameConstraints, fallBackToCommonName,
match);
if (rv != Success) {
return rv;
}
switch (match) {
case MatchResult::Match: // fall through
case MatchResult::NoNamesOfGivenType:
break;
case MatchResult::Mismatch:
return Result::ERROR_CERT_NOT_IN_NAME_SPACE;
}
}
return Success;
}
namespace {
// SearchNames is used by CheckCertHostname and CheckNameConstraints.
//
// When called during name constraint checking, referenceIDType is
// GeneralNameType::nameConstraints and referenceID is the entire encoded name
// constraints extension value.
//
// The main benefit of using the exact same code paths for both is that we
// ensure consistency between name validation and name constraint enforcement
// regarding thing like "Which CN attributes should be considered as potential
// CN-IDs" and "Which character sets are acceptable for CN-IDs?" If the name
// matching and the name constraint enforcement logic were out of sync on these
// issues (e.g. if name matching were to consider all subject CN attributes,
// but name constraints were only enforced on the most specific subject CN),
// trivial name constraint bypasses could result.
Result
SearchNames(/*optional*/ const Input* subjectAltName,
Input subject,
GeneralNameType referenceIDType,
Input referenceID,
FallBackToSearchWithinSubject fallBackToCommonName,
/*out*/ MatchResult& match)
{
Result rv;
match = MatchResult::NoNamesOfGivenType;
// RFC 6125 says "A client MUST NOT seek a match for a reference identifier
// of CN-ID if the presented identifiers include a DNS-ID, SRV-ID, URI-ID, or
// any application-specific identifier types supported by the client."
// Accordingly, we only consider CN-IDs if there are no DNS-IDs in the
// subjectAltName.
//
// RFC 6125 says that IP addresses are out of scope, but for backward
// compatibility we accept them, by considering IP addresses to be an
// "application-specific identifier type supported by the client."
//
// TODO(bug XXXXXXX): Consider strengthening this check to "A client MUST NOT
// seek a match for a reference identifier of CN-ID if the certificate
// contains a subjectAltName extension."
//
// TODO(bug XXXXXXX): Consider dropping support for IP addresses as
// identifiers completely.
if (subjectAltName) {
Reader altNames;
rv = der::ExpectTagAndGetValueAtEnd(*subjectAltName, der::SEQUENCE,
altNames);
if (rv != Success) {
return rv;
}
// According to RFC 5280, "If the subjectAltName extension is present, the
// sequence MUST contain at least one entry." For compatibility reasons, we
// do not enforce this. See bug 1143085.
while (!altNames.AtEnd()) {
GeneralNameType presentedIDType;
Input presentedID;
rv = ReadGeneralName(altNames, presentedIDType, presentedID);
if (rv != Success) {
return rv;
}
rv = MatchPresentedIDWithReferenceID(presentedIDType, presentedID,
referenceIDType, referenceID,
match);
if (rv != Success) {
return rv;
}
if (referenceIDType != GeneralNameType::nameConstraints &&
match == MatchResult::Match) {
return Success;
}
if (presentedIDType == GeneralNameType::dNSName ||
presentedIDType == GeneralNameType::iPAddress) {
fallBackToCommonName = FallBackToSearchWithinSubject::No;
}
}
}
if (referenceIDType == GeneralNameType::nameConstraints) {
rv = CheckPresentedIDConformsToConstraints(GeneralNameType::directoryName,
subject, referenceID);
if (rv != Success) {
return rv;
}
}
FallBackToSearchWithinSubject fallBackToEmailAddress;
if (!subjectAltName &&
(referenceIDType == GeneralNameType::rfc822Name ||
referenceIDType == GeneralNameType::nameConstraints)) {
fallBackToEmailAddress = FallBackToSearchWithinSubject::Yes;
} else {
fallBackToEmailAddress = FallBackToSearchWithinSubject::No;
}
// Short-circuit the parsing of the subject name if we're not going to match
// any names in it
if (fallBackToEmailAddress == FallBackToSearchWithinSubject::No &&
fallBackToCommonName == FallBackToSearchWithinSubject::No) {
return Success;
}
// Attempt to match the reference ID against the CN-ID, which we consider to
// be the most-specific CN AVA in the subject field.
//
// https://tools.ietf.org/html/rfc6125#section-2.3.1 says:
//
// To reduce confusion, in this specification we avoid such terms and
// instead use the terms provided under Section 1.8; in particular, we
// do not use the term "(most specific) Common Name field in the subject
// field" from [HTTP-TLS] and instead state that a CN-ID is a Relative
// Distinguished Name (RDN) in the certificate subject containing one
// and only one attribute-type-and-value pair of type Common Name (thus
// removing the possibility that an RDN might contain multiple AVAs
// (Attribute Value Assertions) of type CN, one of which could be
// considered "most specific").
//
// https://tools.ietf.org/html/rfc6125#section-7.4 says:
//
// [...] Although it would be preferable to
// forbid multiple CN-IDs entirely, there are several reasons at this
// time why this specification states that they SHOULD NOT (instead of
// MUST NOT) be included [...]
//
// Consequently, it is unclear what to do when there are multiple CNs in the
// subject, regardless of whether there "SHOULD NOT" be.
//
// NSS's CERT_VerifyCertName mostly follows RFC2818 in this instance, which
// says:
//
// If a subjectAltName extension of type dNSName is present, that MUST
// be used as the identity. Otherwise, the (most specific) Common Name
// field in the Subject field of the certificate MUST be used.
//
// [...]
//
// In some cases, the URI is specified as an IP address rather than a
// hostname. In this case, the iPAddress subjectAltName must be present
// in the certificate and must exactly match the IP in the URI.
//
// (The main difference from RFC2818 is that NSS's CERT_VerifyCertName also
// matches IP addresses in the most-specific CN.)
//
// NSS's CERT_VerifyCertName finds the most specific CN via
// CERT_GetCommoName, which uses CERT_GetLastNameElement. Note that many
// NSS-based applications, including Gecko, also use CERT_GetCommonName. It
// is likely that other, non-NSS-based, applications also expect only the
// most specific CN to be matched against the reference ID.
//
// "A Layman's Guide to a Subset of ASN.1, BER, and DER" and other sources
// agree that an RDNSequence is ordered from most significant (least
// specific) to least significant (most specific), as do other references.
//
// However, Chromium appears to use the least-specific (first) CN instead of
// the most-specific; see https://crbug.com/366957. Also, MSIE and some other
// popular implementations apparently attempt to match the reference ID
// against any/all CNs in the subject. Since we're trying to phase out the
// use of CN-IDs, we intentionally avoid trying to match MSIE's more liberal
// behavior.
// Name ::= CHOICE { -- only one possibility for now --
// rdnSequence RDNSequence }
//
// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
//
// RelativeDistinguishedName ::=
// SET SIZE (1..MAX) OF AttributeTypeAndValue
Reader subjectReader(subject);
return der::NestedOf(subjectReader, der::SEQUENCE, der::SET,
der::EmptyAllowed::Yes, [&](Reader& r) {
return SearchWithinRDN(r, referenceIDType, referenceID,
fallBackToEmailAddress, fallBackToCommonName, match);
});
}
// RelativeDistinguishedName ::=
// SET SIZE (1..MAX) OF AttributeTypeAndValue
//
// AttributeTypeAndValue ::= SEQUENCE {
// type AttributeType,
// value AttributeValue }
Result
SearchWithinRDN(Reader& rdn,
GeneralNameType referenceIDType,
Input referenceID,
FallBackToSearchWithinSubject fallBackToEmailAddress,
FallBackToSearchWithinSubject fallBackToCommonName,
/*in/out*/ MatchResult& match)
{
do {
Input type;
uint8_t valueTag;
Input value;
Result rv = ReadAVA(rdn, type, valueTag, value);
if (rv != Success) {
return rv;
}
rv = MatchAVA(type, valueTag, value, referenceIDType, referenceID,
fallBackToEmailAddress, fallBackToCommonName, match);
if (rv != Success) {
return rv;
}
} while (!rdn.AtEnd());
return Success;
}
// AttributeTypeAndValue ::= SEQUENCE {
// type AttributeType,
// value AttributeValue }
//
// AttributeType ::= OBJECT IDENTIFIER
//
// AttributeValue ::= ANY -- DEFINED BY AttributeType
//
// DirectoryString ::= CHOICE {
// teletexString TeletexString (SIZE (1..MAX)),
// printableString PrintableString (SIZE (1..MAX)),
// universalString UniversalString (SIZE (1..MAX)),
// utf8String UTF8String (SIZE (1..MAX)),
// bmpString BMPString (SIZE (1..MAX)) }
Result
MatchAVA(Input type, uint8_t valueEncodingTag, Input presentedID,
GeneralNameType referenceIDType,
Input referenceID,
FallBackToSearchWithinSubject fallBackToEmailAddress,
FallBackToSearchWithinSubject fallBackToCommonName,
/*in/out*/ MatchResult& match)
{
// Try to match the CN as a DNSName or an IPAddress.
//
// id-at-commonName AttributeType ::= { id-at 3 }
//
// -- Naming attributes of type X520CommonName:
// -- X520CommonName ::= DirectoryName (SIZE (1..ub-common-name))
// --
// -- Expanded to avoid parameterized type:
// X520CommonName ::= CHOICE {
// teletexString TeletexString (SIZE (1..ub-common-name)),
// printableString PrintableString (SIZE (1..ub-common-name)),
// universalString UniversalString (SIZE (1..ub-common-name)),
// utf8String UTF8String (SIZE (1..ub-common-name)),
// bmpString BMPString (SIZE (1..ub-common-name)) }
//
// python DottedOIDToCode.py id-at-commonName 2.5.4.3
static const uint8_t id_at_commonName[] = {
0x55, 0x04, 0x03
};
if (fallBackToCommonName == FallBackToSearchWithinSubject::Yes &&
InputsAreEqual(type, Input(id_at_commonName))) {
// We might have previously found a match. Now that we've found another CN,
// we no longer consider that previous match to be a match, so "forget" about
// it.
match = MatchResult::NoNamesOfGivenType;
// PrintableString is a subset of ASCII that contains all the characters
// allowed in CN-IDs except '*'. Although '*' is illegal, there are many
// real-world certificates that are encoded this way, so we accept it.
//
// In the case of UTF8String, we rely on the fact that in UTF-8 the octets in
// a multi-byte encoding of a code point are always distinct from ASCII. Any
// non-ASCII byte in a UTF-8 string causes us to fail to match. We make no
// attempt to detect or report malformed UTF-8 (e.g. incomplete or overlong
// encodings of code points, or encodings of invalid code points).
//
// TeletexString is supported as long as it does not contain any escape
// sequences, which are not supported. We'll reject escape sequences as
// invalid characters in names, which means we only accept strings that are
// in the default character set, which is a superset of ASCII. Note that NSS
// actually treats TeletexString as ISO-8859-1. Many certificates that have
// wildcard CN-IDs (e.g. "*.example.com") use TeletexString because
// PrintableString is defined to not allow '*' and because, at one point in
// history, UTF8String was too new to use for compatibility reasons.
//
// UniversalString and BMPString are also deprecated, and they are a little
// harder to support because they are not single-byte ASCII superset
// encodings, so we don't bother.
if (valueEncodingTag != der::PrintableString &&
valueEncodingTag != der::UTF8String &&
valueEncodingTag != der::TeletexString) {
return Success;
}
if (IsValidPresentedDNSID(presentedID)) {
MatchSubjectPresentedIDWithReferenceID(GeneralNameType::dNSName,
presentedID, referenceIDType,
referenceID, match);
} else {
// We don't match CN-IDs for IPv6 addresses.
// MatchSubjectPresentedIDWithReferenceID ensures that it won't match an
// IPv4 address with an IPv6 address, so we don't need to check that
// referenceID is an IPv4 address here.
uint8_t ipv4[4];
if (ParseIPv4Address(presentedID, ipv4)) {
MatchSubjectPresentedIDWithReferenceID(GeneralNameType::iPAddress,
Input(ipv4), referenceIDType,
referenceID, match);
}
}
// Regardless of whether there was a match, we keep going in case we find
// another CN later. If we do find another one, then this match/mismatch
// will be ignored, because we only care about the most specific CN.
return Success;
}
// Match an email address against an emailAddress attribute in the
// subject.
//
// id-emailAddress AttributeType ::= { pkcs-9 1 }
//
// EmailAddress ::= IA5String (SIZE (1..ub-emailaddress-length))
//
// python DottedOIDToCode.py id-emailAddress 1.2.840.113549.1.9.1
static const uint8_t id_emailAddress[] = {
0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01
};
if (fallBackToEmailAddress == FallBackToSearchWithinSubject::Yes &&
InputsAreEqual(type, Input(id_emailAddress))) {
if (referenceIDType == GeneralNameType::rfc822Name &&
match == MatchResult::Match) {
// We already found a match; we don't need to match another one
return Success;
}
if (valueEncodingTag != der::IA5String) {
return Result::ERROR_BAD_DER;
}
return MatchPresentedIDWithReferenceID(GeneralNameType::rfc822Name,
presentedID, referenceIDType,
referenceID, match);
}
return Success;
}
void
MatchSubjectPresentedIDWithReferenceID(GeneralNameType presentedIDType,
Input presentedID,
GeneralNameType referenceIDType,
Input referenceID,
/*in/out*/ MatchResult& match)
{
Result rv = MatchPresentedIDWithReferenceID(presentedIDType, presentedID,
referenceIDType, referenceID,
match);
if (rv != Success) {
match = MatchResult::Mismatch;
}
}
Result
MatchPresentedIDWithReferenceID(GeneralNameType presentedIDType,
Input presentedID,
GeneralNameType referenceIDType,
Input referenceID,
/*out*/ MatchResult& matchResult)
{
if (referenceIDType == GeneralNameType::nameConstraints) {
// matchResult is irrelevant when checking name constraints; only the
// pass/fail result of CheckPresentedIDConformsToConstraints matters.
return CheckPresentedIDConformsToConstraints(presentedIDType, presentedID,
referenceID);
}
if (presentedIDType != referenceIDType) {
matchResult = MatchResult::Mismatch;
return Success;
}
Result rv;
bool foundMatch;
switch (referenceIDType) {
case GeneralNameType::dNSName:
rv = MatchPresentedDNSIDWithReferenceDNSID(
presentedID, AllowWildcards::Yes,
AllowDotlessSubdomainMatches::Yes, IDRole::ReferenceID,
referenceID, foundMatch);
break;
case GeneralNameType::iPAddress:
foundMatch = InputsAreEqual(presentedID, referenceID);
rv = Success;
break;
case GeneralNameType::rfc822Name:
rv = MatchPresentedRFC822NameWithReferenceRFC822Name(
presentedID, IDRole::ReferenceID, referenceID, foundMatch);
break;
case GeneralNameType::directoryName:
// TODO: At some point, we may add APIs for matching DirectoryNames.
// fall through
case GeneralNameType::otherName: // fall through
case GeneralNameType::x400Address: // fall through
case GeneralNameType::ediPartyName: // fall through
case GeneralNameType::uniformResourceIdentifier: // fall through
case GeneralNameType::registeredID: // fall through
case GeneralNameType::nameConstraints:
return NotReached("unexpected nameType for SearchType::Match",
Result::FATAL_ERROR_INVALID_ARGS);
MOZILLA_PKIX_UNREACHABLE_DEFAULT_ENUM
}
if (rv != Success) {
return rv;
}
matchResult = foundMatch ? MatchResult::Match : MatchResult::Mismatch;
return Success;
}
enum class NameConstraintsSubtrees : uint8_t
{
permittedSubtrees = der::CONSTRUCTED | der::CONTEXT_SPECIFIC | 0,
excludedSubtrees = der::CONSTRUCTED | der::CONTEXT_SPECIFIC | 1
};
Result CheckPresentedIDConformsToNameConstraintsSubtrees(
GeneralNameType presentedIDType,
Input presentedID,
Reader& nameConstraints,
NameConstraintsSubtrees subtreesType);
Result MatchPresentedIPAddressWithConstraint(Input presentedID,
Input iPAddressConstraint,
/*out*/ bool& foundMatch);
Result MatchPresentedDirectoryNameWithConstraint(
NameConstraintsSubtrees subtreesType, Input presentedID,
Input directoryNameConstraint, /*out*/ bool& matches);
Result
CheckPresentedIDConformsToConstraints(
GeneralNameType presentedIDType,
Input presentedID,
Input encodedNameConstraints)
{
// NameConstraints ::= SEQUENCE {
// permittedSubtrees [0] GeneralSubtrees OPTIONAL,
// excludedSubtrees [1] GeneralSubtrees OPTIONAL }
Reader nameConstraints;
Result rv = der::ExpectTagAndGetValueAtEnd(encodedNameConstraints,
der::SEQUENCE, nameConstraints);
if (rv != Success) {
return rv;
}
// RFC 5280 says "Conforming CAs MUST NOT issue certificates where name
// constraints is an empty sequence. That is, either the permittedSubtrees
// field or the excludedSubtrees MUST be present."
if (nameConstraints.AtEnd()) {
return Result::ERROR_BAD_DER;
}
rv = CheckPresentedIDConformsToNameConstraintsSubtrees(
presentedIDType, presentedID, nameConstraints,
NameConstraintsSubtrees::permittedSubtrees);
if (rv != Success) {
return rv;
}
rv = CheckPresentedIDConformsToNameConstraintsSubtrees(
presentedIDType, presentedID, nameConstraints,
NameConstraintsSubtrees::excludedSubtrees);
if (rv != Success) {
return rv;
}
return der::End(nameConstraints);
}
Result
CheckPresentedIDConformsToNameConstraintsSubtrees(
GeneralNameType presentedIDType,
Input presentedID,
Reader& nameConstraints,
NameConstraintsSubtrees subtreesType)
{
if (!nameConstraints.Peek(static_cast<uint8_t>(subtreesType))) {
return Success;
}
Reader subtrees;
Result rv = der::ExpectTagAndGetValue(nameConstraints,
static_cast<uint8_t>(subtreesType),
subtrees);
if (rv != Success) {
return rv;
}
bool hasPermittedSubtreesMatch = false;
bool hasPermittedSubtreesMismatch = false;
// GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
//
// do { ... } while(...) because subtrees isn't allowed to be empty.
do {
// GeneralSubtree ::= SEQUENCE {
// base GeneralName,
// minimum [0] BaseDistance DEFAULT 0,
// maximum [1] BaseDistance OPTIONAL }
Reader subtree;
rv = ExpectTagAndGetValue(subtrees, der::SEQUENCE, subtree);
if (rv != Success) {
return rv;
}
GeneralNameType nameConstraintType;
Input base;
rv = ReadGeneralName(subtree, nameConstraintType, base);
if (rv != Success) {
return rv;
}
// http://tools.ietf.org/html/rfc5280#section-4.2.1.10: "Within this
// profile, the minimum and maximum fields are not used with any name
// forms, thus, the minimum MUST be zero, and maximum MUST be absent."
//
// Since the default value isn't allowed to be encoded according to the DER
// encoding rules for DEFAULT, this is equivalent to saying that neither
// minimum or maximum must be encoded.
rv = der::End(subtree);
if (rv != Success) {
return rv;
}
if (presentedIDType == nameConstraintType) {
bool matches;
switch (presentedIDType) {
case GeneralNameType::dNSName:
rv = MatchPresentedDNSIDWithReferenceDNSID(
presentedID, AllowWildcards::Yes,
AllowDotlessSubdomainMatches::Yes, IDRole::NameConstraint,
base, matches);
if (rv != Success) {
return rv;
}
break;
case GeneralNameType::iPAddress:
rv = MatchPresentedIPAddressWithConstraint(presentedID, base,
matches);
if (rv != Success) {
return rv;
}
break;
case GeneralNameType::directoryName:
rv = MatchPresentedDirectoryNameWithConstraint(subtreesType,
presentedID, base,
matches);
if (rv != Success) {
return rv;
}
break;
case GeneralNameType::rfc822Name:
rv = MatchPresentedRFC822NameWithReferenceRFC822Name(
presentedID, IDRole::NameConstraint, base, matches);
if (rv != Success) {
return rv;
}
break;
// RFC 5280 says "Conforming CAs [...] SHOULD NOT impose name
// constraints on the x400Address, ediPartyName, or registeredID
// name forms. It also says "Applications conforming to this profile
// [...] SHOULD be able to process name constraints that are imposed
// on [...] uniformResourceIdentifier [...]", but we don't bother.
//
// TODO: Ask to have spec updated to say ""Conforming CAs [...] SHOULD
// NOT impose name constraints on the otherName, x400Address,
// ediPartyName, uniformResourceIdentifier, or registeredID name
// forms."
case GeneralNameType::otherName: // fall through
case GeneralNameType::x400Address: // fall through
case GeneralNameType::ediPartyName: // fall through
case GeneralNameType::uniformResourceIdentifier: // fall through
case GeneralNameType::registeredID: // fall through
return Result::ERROR_CERT_NOT_IN_NAME_SPACE;
case GeneralNameType::nameConstraints:
return NotReached("invalid presentedIDType",
Result::FATAL_ERROR_LIBRARY_FAILURE);
MOZILLA_PKIX_UNREACHABLE_DEFAULT_ENUM
}
switch (subtreesType) {
case NameConstraintsSubtrees::permittedSubtrees:
if (matches) {
hasPermittedSubtreesMatch = true;
} else {
hasPermittedSubtreesMismatch = true;
}
break;
case NameConstraintsSubtrees::excludedSubtrees:
if (matches) {
return Result::ERROR_CERT_NOT_IN_NAME_SPACE;
}
break;
}
}
} while (!subtrees.AtEnd());
if (hasPermittedSubtreesMismatch && !hasPermittedSubtreesMatch) {
// If there was any entry of the given type in permittedSubtrees, then it
// required that at least one of them must match. Since none of them did,
// we have a failure.
return Result::ERROR_CERT_NOT_IN_NAME_SPACE;
}
return Success;
}
// We do not distinguish between a syntactically-invalid presentedDNSID and one
// that is syntactically valid but does not match referenceDNSID; in both
// cases, the result is false.
//
// We assume that both presentedDNSID and referenceDNSID are encoded in such a
// way that US-ASCII (7-bit) characters are encoded in one byte and no encoding
// of a non-US-ASCII character contains a code point in the range 0-127. For
// example, UTF-8 is OK but UTF-16 is not.
//
// RFC6125 says that a wildcard label may be of the form <x>*<y>.<DNSID>, where
// <x> and/or <y> may be empty. However, NSS requires <y> to be empty, and we
// follow NSS's stricter policy by accepting wildcards only of the form
// <x>*.<DNSID>, where <x> may be empty.
//
// An relative presented DNS ID matches both an absolute reference ID and a
// relative reference ID. Absolute presented DNS IDs are not supported:
//
// Presented ID Reference ID Result
// -------------------------------------
// example.com example.com Match
// example.com. example.com Mismatch
// example.com example.com. Match
// example.com. example.com. Mismatch
//
// There are more subtleties documented inline in the code.
//
// Name constraints ///////////////////////////////////////////////////////////
//
// This is all RFC 5280 has to say about DNSName constraints:
//
// DNS name restrictions are expressed as host.example.com. Any DNS
// name that can be constructed by simply adding zero or more labels to
// the left-hand side of the name satisfies the name constraint. For
// example, www.host.example.com would satisfy the constraint but
// host1.example.com would not.
//
// This lack of specificity has lead to a lot of uncertainty regarding
// subdomain matching. In particular, the following questions have been
// raised and answered:
//
// Q: Does a presented identifier equal (case insensitive) to the name
// constraint match the constraint? For example, does the presented
// ID "host.example.com" match a "host.example.com" constraint?
// A: Yes. RFC5280 says "by simply adding zero or more labels" and this
// is the case of adding zero labels.
//
// Q: When the name constraint does not start with ".", do subdomain
// presented identifiers match it? For example, does the presented
// ID "www.host.example.com" match a "host.example.com" constraint?
// A: Yes. RFC5280 says "by simply adding zero or more labels" and this
// is the case of adding more than zero labels. The example is the
// one from RFC 5280.
//
// Q: When the name constraint does not start with ".", does a
// non-subdomain prefix match it? For example, does "bigfoo.bar.com"
// match "foo.bar.com"? [4]
// A: No. We interpret RFC 5280's language of "adding zero or more labels"
// to mean that whole labels must be prefixed.
//
// (Note that the above three scenarios are the same as the RFC 6265
// domain matching rules [0].)
//
// Q: Is a name constraint that starts with "." valid, and if so, what
// semantics does it have? For example, does a presented ID of
// "www.example.com" match a constraint of ".example.com"? Does a
// presented ID of "example.com" match a constraint of ".example.com"?
// A: This implementation, NSS[1], and SChannel[2] all support a
// leading ".", but OpenSSL[3] does not yet. Amongst the
// implementations that support it, a leading "." is legal and means
// the same thing as when the "." is omitted, EXCEPT that a
// presented identifier equal (case insensitive) to the name
// constraint is not matched; i.e. presented DNSName identifiers
// must be subdomains. Some CAs in Mozilla's CA program (e.g. HARICA)
// have name constraints with the leading "." in their root
// certificates. The name constraints imposed on DCISS by Mozilla also
// have the it, so supporting this is a requirement for backward
// compatibility, even if it is not yet standardized. So, for example, a
// presented ID of "www.example.com" matches a constraint of
// ".example.com" but a presented ID of "example.com" does not.