pkixnames.cpp 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  5. */
  6. // This code implements RFC6125-ish name matching, RFC5280-ish name constraint
  7. // checking, and related things.
  8. //
  9. // In this code, identifiers are classified as either "presented" or
  10. // "reference" identifiers are defined in
  11. // http://tools.ietf.org/html/rfc6125#section-1.8. A "presented identifier" is
  12. // one in the subjectAltName of the certificate, or sometimes within a CN of
  13. // the certificate's subject. The "reference identifier" is the one we are
  14. // being asked to match the certificate against. When checking name
  15. // constraints, the reference identifier is the entire encoded name constraint
  16. // extension value.
  17. #include <algorithm>
  18. #include "pkix/pkixcheck.h"
  19. #include "pkix/pkixutil.h"
  20. namespace mozilla { namespace pkix {
  21. namespace {
  22. // GeneralName ::= CHOICE {
  23. // otherName [0] OtherName,
  24. // rfc822Name [1] IA5String,
  25. // dNSName [2] IA5String,
  26. // x400Address [3] ORAddress,
  27. // directoryName [4] Name,
  28. // ediPartyName [5] EDIPartyName,
  29. // uniformResourceIdentifier [6] IA5String,
  30. // iPAddress [7] OCTET STRING,
  31. // registeredID [8] OBJECT IDENTIFIER }
  32. enum class GeneralNameType : uint8_t
  33. {
  34. // Note that these values are NOT contiguous. Some values have the
  35. // der::CONSTRUCTED bit set while others do not.
  36. // (The der::CONSTRUCTED bit is for types where the value is a SEQUENCE.)
  37. otherName = der::CONTEXT_SPECIFIC | der::CONSTRUCTED | 0,
  38. rfc822Name = der::CONTEXT_SPECIFIC | 1,
  39. dNSName = der::CONTEXT_SPECIFIC | 2,
  40. x400Address = der::CONTEXT_SPECIFIC | der::CONSTRUCTED | 3,
  41. directoryName = der::CONTEXT_SPECIFIC | der::CONSTRUCTED | 4,
  42. ediPartyName = der::CONTEXT_SPECIFIC | der::CONSTRUCTED | 5,
  43. uniformResourceIdentifier = der::CONTEXT_SPECIFIC | 6,
  44. iPAddress = der::CONTEXT_SPECIFIC | 7,
  45. registeredID = der::CONTEXT_SPECIFIC | 8,
  46. // nameConstraints is a pseudo-GeneralName used to signify that a
  47. // reference ID is actually the entire name constraint extension.
  48. nameConstraints = 0xff
  49. };
  50. inline Result
  51. ReadGeneralName(Reader& reader,
  52. /*out*/ GeneralNameType& generalNameType,
  53. /*out*/ Input& value)
  54. {
  55. uint8_t tag;
  56. Result rv = der::ReadTagAndGetValue(reader, tag, value);
  57. if (rv != Success) {
  58. return rv;
  59. }
  60. switch (tag) {
  61. case static_cast<uint8_t>(GeneralNameType::otherName):
  62. generalNameType = GeneralNameType::otherName;
  63. break;
  64. case static_cast<uint8_t>(GeneralNameType::rfc822Name):
  65. generalNameType = GeneralNameType::rfc822Name;
  66. break;
  67. case static_cast<uint8_t>(GeneralNameType::dNSName):
  68. generalNameType = GeneralNameType::dNSName;
  69. break;
  70. case static_cast<uint8_t>(GeneralNameType::x400Address):
  71. generalNameType = GeneralNameType::x400Address;
  72. break;
  73. case static_cast<uint8_t>(GeneralNameType::directoryName):
  74. generalNameType = GeneralNameType::directoryName;
  75. break;
  76. case static_cast<uint8_t>(GeneralNameType::ediPartyName):
  77. generalNameType = GeneralNameType::ediPartyName;
  78. break;
  79. case static_cast<uint8_t>(GeneralNameType::uniformResourceIdentifier):
  80. generalNameType = GeneralNameType::uniformResourceIdentifier;
  81. break;
  82. case static_cast<uint8_t>(GeneralNameType::iPAddress):
  83. generalNameType = GeneralNameType::iPAddress;
  84. break;
  85. case static_cast<uint8_t>(GeneralNameType::registeredID):
  86. generalNameType = GeneralNameType::registeredID;
  87. break;
  88. default:
  89. return Result::ERROR_BAD_DER;
  90. }
  91. return Success;
  92. }
  93. enum class MatchResult
  94. {
  95. NoNamesOfGivenType = 0,
  96. Mismatch = 1,
  97. Match = 2
  98. };
  99. Result SearchNames(const Input* subjectAltName, Input subject,
  100. GeneralNameType referenceIDType,
  101. Input referenceID,
  102. FallBackToSearchWithinSubject fallBackToCommonName,
  103. /*out*/ MatchResult& match);
  104. Result SearchWithinRDN(Reader& rdn,
  105. GeneralNameType referenceIDType,
  106. Input referenceID,
  107. FallBackToSearchWithinSubject fallBackToEmailAddress,
  108. FallBackToSearchWithinSubject fallBackToCommonName,
  109. /*in/out*/ MatchResult& match);
  110. Result MatchAVA(Input type,
  111. uint8_t valueEncodingTag,
  112. Input presentedID,
  113. GeneralNameType referenceIDType,
  114. Input referenceID,
  115. FallBackToSearchWithinSubject fallBackToEmailAddress,
  116. FallBackToSearchWithinSubject fallBackToCommonName,
  117. /*in/out*/ MatchResult& match);
  118. Result ReadAVA(Reader& rdn,
  119. /*out*/ Input& type,
  120. /*out*/ uint8_t& valueTag,
  121. /*out*/ Input& value);
  122. void MatchSubjectPresentedIDWithReferenceID(GeneralNameType presentedIDType,
  123. Input presentedID,
  124. GeneralNameType referenceIDType,
  125. Input referenceID,
  126. /*in/out*/ MatchResult& match);
  127. Result MatchPresentedIDWithReferenceID(GeneralNameType presentedIDType,
  128. Input presentedID,
  129. GeneralNameType referenceIDType,
  130. Input referenceID,
  131. /*in/out*/ MatchResult& matchResult);
  132. Result CheckPresentedIDConformsToConstraints(GeneralNameType referenceIDType,
  133. Input presentedID,
  134. Input nameConstraints);
  135. uint8_t LocaleInsensitveToLower(uint8_t a);
  136. bool StartsWithIDNALabel(Input id);
  137. enum class IDRole
  138. {
  139. ReferenceID = 0,
  140. PresentedID = 1,
  141. NameConstraint = 2,
  142. };
  143. enum class AllowWildcards { No = 0, Yes = 1 };
  144. // DNSName constraints implicitly allow subdomain matching when there is no
  145. // leading dot ("foo.example.com" matches a constraint of "example.com"), but
  146. // RFC822Name constraints only allow subdomain matching when there is a leading
  147. // dot ("foo.example.com" does not match "example.com" but does match
  148. // ".example.com").
  149. enum class AllowDotlessSubdomainMatches { No = 0, Yes = 1 };
  150. bool IsValidDNSID(Input hostname, IDRole idRole,
  151. AllowWildcards allowWildcards);
  152. Result MatchPresentedDNSIDWithReferenceDNSID(
  153. Input presentedDNSID,
  154. AllowWildcards allowWildcards,
  155. AllowDotlessSubdomainMatches allowDotlessSubdomainMatches,
  156. IDRole referenceDNSIDRole,
  157. Input referenceDNSID,
  158. /*out*/ bool& matches);
  159. Result MatchPresentedRFC822NameWithReferenceRFC822Name(
  160. Input presentedRFC822Name, IDRole referenceRFC822NameRole,
  161. Input referenceRFC822Name, /*out*/ bool& matches);
  162. } // namespace
  163. bool IsValidReferenceDNSID(Input hostname);
  164. bool IsValidPresentedDNSID(Input hostname);
  165. bool ParseIPv4Address(Input hostname, /*out*/ uint8_t (&out)[4]);
  166. bool ParseIPv6Address(Input hostname, /*out*/ uint8_t (&out)[16]);
  167. // This is used by the pkixnames_tests.cpp tests.
  168. Result
  169. MatchPresentedDNSIDWithReferenceDNSID(Input presentedDNSID,
  170. Input referenceDNSID,
  171. /*out*/ bool& matches)
  172. {
  173. return MatchPresentedDNSIDWithReferenceDNSID(
  174. presentedDNSID, AllowWildcards::Yes,
  175. AllowDotlessSubdomainMatches::Yes, IDRole::ReferenceID,
  176. referenceDNSID, matches);
  177. }
  178. // Verify that the given end-entity cert, which is assumed to have been already
  179. // validated with BuildCertChain, is valid for the given hostname. hostname is
  180. // assumed to be a string representation of an IPv4 address, an IPv6 addresss,
  181. // or a normalized ASCII (possibly punycode) DNS name.
  182. Result
  183. CheckCertHostname(Input endEntityCertDER, Input hostname,
  184. NameMatchingPolicy& nameMatchingPolicy)
  185. {
  186. BackCert cert(endEntityCertDER, EndEntityOrCA::MustBeEndEntity, nullptr);
  187. Result rv = cert.Init();
  188. if (rv != Success) {
  189. return rv;
  190. }
  191. Time notBefore(Time::uninitialized);
  192. rv = ParseValidity(cert.GetValidity(), &notBefore);
  193. if (rv != Success) {
  194. return rv;
  195. }
  196. FallBackToSearchWithinSubject fallBackToSearchWithinSubject;
  197. rv = nameMatchingPolicy.FallBackToCommonName(notBefore,
  198. fallBackToSearchWithinSubject);
  199. if (rv != Success) {
  200. return rv;
  201. }
  202. const Input* subjectAltName(cert.GetSubjectAltName());
  203. Input subject(cert.GetSubject());
  204. // For backward compatibility with legacy certificates, we may fall back to
  205. // searching for a name match in the subject common name for DNS names and
  206. // IPv4 addresses. We don't do so for IPv6 addresses because we do not think
  207. // there are many certificates that would need such fallback, and because
  208. // comparisons of string representations of IPv6 addresses are particularly
  209. // error prone due to the syntactic flexibility that IPv6 addresses have.
  210. //
  211. // IPv4 and IPv6 addresses are represented using the same type of GeneralName
  212. // (iPAddress); they are differentiated by the lengths of the values.
  213. MatchResult match;
  214. uint8_t ipv6[16];
  215. uint8_t ipv4[4];
  216. if (IsValidReferenceDNSID(hostname)) {
  217. rv = SearchNames(subjectAltName, subject, GeneralNameType::dNSName,
  218. hostname, fallBackToSearchWithinSubject, match);
  219. } else if (ParseIPv6Address(hostname, ipv6)) {
  220. rv = SearchNames(subjectAltName, subject, GeneralNameType::iPAddress,
  221. Input(ipv6), FallBackToSearchWithinSubject::No, match);
  222. } else if (ParseIPv4Address(hostname, ipv4)) {
  223. rv = SearchNames(subjectAltName, subject, GeneralNameType::iPAddress,
  224. Input(ipv4), fallBackToSearchWithinSubject, match);
  225. } else {
  226. return Result::ERROR_BAD_CERT_DOMAIN;
  227. }
  228. if (rv != Success) {
  229. return rv;
  230. }
  231. switch (match) {
  232. case MatchResult::NoNamesOfGivenType: // fall through
  233. case MatchResult::Mismatch:
  234. return Result::ERROR_BAD_CERT_DOMAIN;
  235. case MatchResult::Match:
  236. return Success;
  237. MOZILLA_PKIX_UNREACHABLE_DEFAULT_ENUM
  238. }
  239. }
  240. // 4.2.1.10. Name Constraints
  241. Result
  242. CheckNameConstraints(Input encodedNameConstraints,
  243. const BackCert& firstChild,
  244. KeyPurposeId requiredEKUIfPresent)
  245. {
  246. for (const BackCert* child = &firstChild; child; child = child->childCert) {
  247. FallBackToSearchWithinSubject fallBackToCommonName
  248. = (child->endEntityOrCA == EndEntityOrCA::MustBeEndEntity &&
  249. requiredEKUIfPresent == KeyPurposeId::id_kp_serverAuth)
  250. ? FallBackToSearchWithinSubject::Yes
  251. : FallBackToSearchWithinSubject::No;
  252. MatchResult match;
  253. Result rv = SearchNames(child->GetSubjectAltName(), child->GetSubject(),
  254. GeneralNameType::nameConstraints,
  255. encodedNameConstraints, fallBackToCommonName,
  256. match);
  257. if (rv != Success) {
  258. return rv;
  259. }
  260. switch (match) {
  261. case MatchResult::Match: // fall through
  262. case MatchResult::NoNamesOfGivenType:
  263. break;
  264. case MatchResult::Mismatch:
  265. return Result::ERROR_CERT_NOT_IN_NAME_SPACE;
  266. }
  267. }
  268. return Success;
  269. }
  270. namespace {
  271. // SearchNames is used by CheckCertHostname and CheckNameConstraints.
  272. //
  273. // When called during name constraint checking, referenceIDType is
  274. // GeneralNameType::nameConstraints and referenceID is the entire encoded name
  275. // constraints extension value.
  276. //
  277. // The main benefit of using the exact same code paths for both is that we
  278. // ensure consistency between name validation and name constraint enforcement
  279. // regarding thing like "Which CN attributes should be considered as potential
  280. // CN-IDs" and "Which character sets are acceptable for CN-IDs?" If the name
  281. // matching and the name constraint enforcement logic were out of sync on these
  282. // issues (e.g. if name matching were to consider all subject CN attributes,
  283. // but name constraints were only enforced on the most specific subject CN),
  284. // trivial name constraint bypasses could result.
  285. Result
  286. SearchNames(/*optional*/ const Input* subjectAltName,
  287. Input subject,
  288. GeneralNameType referenceIDType,
  289. Input referenceID,
  290. FallBackToSearchWithinSubject fallBackToCommonName,
  291. /*out*/ MatchResult& match)
  292. {
  293. Result rv;
  294. match = MatchResult::NoNamesOfGivenType;
  295. // RFC 6125 says "A client MUST NOT seek a match for a reference identifier
  296. // of CN-ID if the presented identifiers include a DNS-ID, SRV-ID, URI-ID, or
  297. // any application-specific identifier types supported by the client."
  298. // Accordingly, we only consider CN-IDs if there are no DNS-IDs in the
  299. // subjectAltName.
  300. //
  301. // RFC 6125 says that IP addresses are out of scope, but for backward
  302. // compatibility we accept them, by considering IP addresses to be an
  303. // "application-specific identifier type supported by the client."
  304. //
  305. // TODO(bug XXXXXXX): Consider strengthening this check to "A client MUST NOT
  306. // seek a match for a reference identifier of CN-ID if the certificate
  307. // contains a subjectAltName extension."
  308. //
  309. // TODO(bug XXXXXXX): Consider dropping support for IP addresses as
  310. // identifiers completely.
  311. if (subjectAltName) {
  312. Reader altNames;
  313. rv = der::ExpectTagAndGetValueAtEnd(*subjectAltName, der::SEQUENCE,
  314. altNames);
  315. if (rv != Success) {
  316. return rv;
  317. }
  318. // According to RFC 5280, "If the subjectAltName extension is present, the
  319. // sequence MUST contain at least one entry." For compatibility reasons, we
  320. // do not enforce this. See bug 1143085.
  321. while (!altNames.AtEnd()) {
  322. GeneralNameType presentedIDType;
  323. Input presentedID;
  324. rv = ReadGeneralName(altNames, presentedIDType, presentedID);
  325. if (rv != Success) {
  326. return rv;
  327. }
  328. rv = MatchPresentedIDWithReferenceID(presentedIDType, presentedID,
  329. referenceIDType, referenceID,
  330. match);
  331. if (rv != Success) {
  332. return rv;
  333. }
  334. if (referenceIDType != GeneralNameType::nameConstraints &&
  335. match == MatchResult::Match) {
  336. return Success;
  337. }
  338. if (presentedIDType == GeneralNameType::dNSName ||
  339. presentedIDType == GeneralNameType::iPAddress) {
  340. fallBackToCommonName = FallBackToSearchWithinSubject::No;
  341. }
  342. }
  343. }
  344. if (referenceIDType == GeneralNameType::nameConstraints) {
  345. rv = CheckPresentedIDConformsToConstraints(GeneralNameType::directoryName,
  346. subject, referenceID);
  347. if (rv != Success) {
  348. return rv;
  349. }
  350. }
  351. FallBackToSearchWithinSubject fallBackToEmailAddress;
  352. if (!subjectAltName &&
  353. (referenceIDType == GeneralNameType::rfc822Name ||
  354. referenceIDType == GeneralNameType::nameConstraints)) {
  355. fallBackToEmailAddress = FallBackToSearchWithinSubject::Yes;
  356. } else {
  357. fallBackToEmailAddress = FallBackToSearchWithinSubject::No;
  358. }
  359. // Short-circuit the parsing of the subject name if we're not going to match
  360. // any names in it
  361. if (fallBackToEmailAddress == FallBackToSearchWithinSubject::No &&
  362. fallBackToCommonName == FallBackToSearchWithinSubject::No) {
  363. return Success;
  364. }
  365. // Attempt to match the reference ID against the CN-ID, which we consider to
  366. // be the most-specific CN AVA in the subject field.
  367. //
  368. // https://tools.ietf.org/html/rfc6125#section-2.3.1 says:
  369. //
  370. // To reduce confusion, in this specification we avoid such terms and
  371. // instead use the terms provided under Section 1.8; in particular, we
  372. // do not use the term "(most specific) Common Name field in the subject
  373. // field" from [HTTP-TLS] and instead state that a CN-ID is a Relative
  374. // Distinguished Name (RDN) in the certificate subject containing one
  375. // and only one attribute-type-and-value pair of type Common Name (thus
  376. // removing the possibility that an RDN might contain multiple AVAs
  377. // (Attribute Value Assertions) of type CN, one of which could be
  378. // considered "most specific").
  379. //
  380. // https://tools.ietf.org/html/rfc6125#section-7.4 says:
  381. //
  382. // [...] Although it would be preferable to
  383. // forbid multiple CN-IDs entirely, there are several reasons at this
  384. // time why this specification states that they SHOULD NOT (instead of
  385. // MUST NOT) be included [...]
  386. //
  387. // Consequently, it is unclear what to do when there are multiple CNs in the
  388. // subject, regardless of whether there "SHOULD NOT" be.
  389. //
  390. // NSS's CERT_VerifyCertName mostly follows RFC2818 in this instance, which
  391. // says:
  392. //
  393. // If a subjectAltName extension of type dNSName is present, that MUST
  394. // be used as the identity. Otherwise, the (most specific) Common Name
  395. // field in the Subject field of the certificate MUST be used.
  396. //
  397. // [...]
  398. //
  399. // In some cases, the URI is specified as an IP address rather than a
  400. // hostname. In this case, the iPAddress subjectAltName must be present
  401. // in the certificate and must exactly match the IP in the URI.
  402. //
  403. // (The main difference from RFC2818 is that NSS's CERT_VerifyCertName also
  404. // matches IP addresses in the most-specific CN.)
  405. //
  406. // NSS's CERT_VerifyCertName finds the most specific CN via
  407. // CERT_GetCommoName, which uses CERT_GetLastNameElement. Note that many
  408. // NSS-based applications, including Gecko, also use CERT_GetCommonName. It
  409. // is likely that other, non-NSS-based, applications also expect only the
  410. // most specific CN to be matched against the reference ID.
  411. //
  412. // "A Layman's Guide to a Subset of ASN.1, BER, and DER" and other sources
  413. // agree that an RDNSequence is ordered from most significant (least
  414. // specific) to least significant (most specific), as do other references.
  415. //
  416. // However, Chromium appears to use the least-specific (first) CN instead of
  417. // the most-specific; see https://crbug.com/366957. Also, MSIE and some other
  418. // popular implementations apparently attempt to match the reference ID
  419. // against any/all CNs in the subject. Since we're trying to phase out the
  420. // use of CN-IDs, we intentionally avoid trying to match MSIE's more liberal
  421. // behavior.
  422. // Name ::= CHOICE { -- only one possibility for now --
  423. // rdnSequence RDNSequence }
  424. //
  425. // RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
  426. //
  427. // RelativeDistinguishedName ::=
  428. // SET SIZE (1..MAX) OF AttributeTypeAndValue
  429. Reader subjectReader(subject);
  430. return der::NestedOf(subjectReader, der::SEQUENCE, der::SET,
  431. der::EmptyAllowed::Yes, [&](Reader& r) {
  432. return SearchWithinRDN(r, referenceIDType, referenceID,
  433. fallBackToEmailAddress, fallBackToCommonName, match);
  434. });
  435. }
  436. // RelativeDistinguishedName ::=
  437. // SET SIZE (1..MAX) OF AttributeTypeAndValue
  438. //
  439. // AttributeTypeAndValue ::= SEQUENCE {
  440. // type AttributeType,
  441. // value AttributeValue }
  442. Result
  443. SearchWithinRDN(Reader& rdn,
  444. GeneralNameType referenceIDType,
  445. Input referenceID,
  446. FallBackToSearchWithinSubject fallBackToEmailAddress,
  447. FallBackToSearchWithinSubject fallBackToCommonName,
  448. /*in/out*/ MatchResult& match)
  449. {
  450. do {
  451. Input type;
  452. uint8_t valueTag;
  453. Input value;
  454. Result rv = ReadAVA(rdn, type, valueTag, value);
  455. if (rv != Success) {
  456. return rv;
  457. }
  458. rv = MatchAVA(type, valueTag, value, referenceIDType, referenceID,
  459. fallBackToEmailAddress, fallBackToCommonName, match);
  460. if (rv != Success) {
  461. return rv;
  462. }
  463. } while (!rdn.AtEnd());
  464. return Success;
  465. }
  466. // AttributeTypeAndValue ::= SEQUENCE {
  467. // type AttributeType,
  468. // value AttributeValue }
  469. //
  470. // AttributeType ::= OBJECT IDENTIFIER
  471. //
  472. // AttributeValue ::= ANY -- DEFINED BY AttributeType
  473. //
  474. // DirectoryString ::= CHOICE {
  475. // teletexString TeletexString (SIZE (1..MAX)),
  476. // printableString PrintableString (SIZE (1..MAX)),
  477. // universalString UniversalString (SIZE (1..MAX)),
  478. // utf8String UTF8String (SIZE (1..MAX)),
  479. // bmpString BMPString (SIZE (1..MAX)) }
  480. Result
  481. MatchAVA(Input type, uint8_t valueEncodingTag, Input presentedID,
  482. GeneralNameType referenceIDType,
  483. Input referenceID,
  484. FallBackToSearchWithinSubject fallBackToEmailAddress,
  485. FallBackToSearchWithinSubject fallBackToCommonName,
  486. /*in/out*/ MatchResult& match)
  487. {
  488. // Try to match the CN as a DNSName or an IPAddress.
  489. //
  490. // id-at-commonName AttributeType ::= { id-at 3 }
  491. //
  492. // -- Naming attributes of type X520CommonName:
  493. // -- X520CommonName ::= DirectoryName (SIZE (1..ub-common-name))
  494. // --
  495. // -- Expanded to avoid parameterized type:
  496. // X520CommonName ::= CHOICE {
  497. // teletexString TeletexString (SIZE (1..ub-common-name)),
  498. // printableString PrintableString (SIZE (1..ub-common-name)),
  499. // universalString UniversalString (SIZE (1..ub-common-name)),
  500. // utf8String UTF8String (SIZE (1..ub-common-name)),
  501. // bmpString BMPString (SIZE (1..ub-common-name)) }
  502. //
  503. // python DottedOIDToCode.py id-at-commonName 2.5.4.3
  504. static const uint8_t id_at_commonName[] = {
  505. 0x55, 0x04, 0x03
  506. };
  507. if (fallBackToCommonName == FallBackToSearchWithinSubject::Yes &&
  508. InputsAreEqual(type, Input(id_at_commonName))) {
  509. // We might have previously found a match. Now that we've found another CN,
  510. // we no longer consider that previous match to be a match, so "forget" about
  511. // it.
  512. match = MatchResult::NoNamesOfGivenType;
  513. // PrintableString is a subset of ASCII that contains all the characters
  514. // allowed in CN-IDs except '*'. Although '*' is illegal, there are many
  515. // real-world certificates that are encoded this way, so we accept it.
  516. //
  517. // In the case of UTF8String, we rely on the fact that in UTF-8 the octets in
  518. // a multi-byte encoding of a code point are always distinct from ASCII. Any
  519. // non-ASCII byte in a UTF-8 string causes us to fail to match. We make no
  520. // attempt to detect or report malformed UTF-8 (e.g. incomplete or overlong
  521. // encodings of code points, or encodings of invalid code points).
  522. //
  523. // TeletexString is supported as long as it does not contain any escape
  524. // sequences, which are not supported. We'll reject escape sequences as
  525. // invalid characters in names, which means we only accept strings that are
  526. // in the default character set, which is a superset of ASCII. Note that NSS
  527. // actually treats TeletexString as ISO-8859-1. Many certificates that have
  528. // wildcard CN-IDs (e.g. "*.example.com") use TeletexString because
  529. // PrintableString is defined to not allow '*' and because, at one point in
  530. // history, UTF8String was too new to use for compatibility reasons.
  531. //
  532. // UniversalString and BMPString are also deprecated, and they are a little
  533. // harder to support because they are not single-byte ASCII superset
  534. // encodings, so we don't bother.
  535. if (valueEncodingTag != der::PrintableString &&
  536. valueEncodingTag != der::UTF8String &&
  537. valueEncodingTag != der::TeletexString) {
  538. return Success;
  539. }
  540. if (IsValidPresentedDNSID(presentedID)) {
  541. MatchSubjectPresentedIDWithReferenceID(GeneralNameType::dNSName,
  542. presentedID, referenceIDType,
  543. referenceID, match);
  544. } else {
  545. // We don't match CN-IDs for IPv6 addresses.
  546. // MatchSubjectPresentedIDWithReferenceID ensures that it won't match an
  547. // IPv4 address with an IPv6 address, so we don't need to check that
  548. // referenceID is an IPv4 address here.
  549. uint8_t ipv4[4];
  550. if (ParseIPv4Address(presentedID, ipv4)) {
  551. MatchSubjectPresentedIDWithReferenceID(GeneralNameType::iPAddress,
  552. Input(ipv4), referenceIDType,
  553. referenceID, match);
  554. }
  555. }
  556. // Regardless of whether there was a match, we keep going in case we find
  557. // another CN later. If we do find another one, then this match/mismatch
  558. // will be ignored, because we only care about the most specific CN.
  559. return Success;
  560. }
  561. // Match an email address against an emailAddress attribute in the
  562. // subject.
  563. //
  564. // id-emailAddress AttributeType ::= { pkcs-9 1 }
  565. //
  566. // EmailAddress ::= IA5String (SIZE (1..ub-emailaddress-length))
  567. //
  568. // python DottedOIDToCode.py id-emailAddress 1.2.840.113549.1.9.1
  569. static const uint8_t id_emailAddress[] = {
  570. 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01
  571. };
  572. if (fallBackToEmailAddress == FallBackToSearchWithinSubject::Yes &&
  573. InputsAreEqual(type, Input(id_emailAddress))) {
  574. if (referenceIDType == GeneralNameType::rfc822Name &&
  575. match == MatchResult::Match) {
  576. // We already found a match; we don't need to match another one
  577. return Success;
  578. }
  579. if (valueEncodingTag != der::IA5String) {
  580. return Result::ERROR_BAD_DER;
  581. }
  582. return MatchPresentedIDWithReferenceID(GeneralNameType::rfc822Name,
  583. presentedID, referenceIDType,
  584. referenceID, match);
  585. }
  586. return Success;
  587. }
  588. void
  589. MatchSubjectPresentedIDWithReferenceID(GeneralNameType presentedIDType,
  590. Input presentedID,
  591. GeneralNameType referenceIDType,
  592. Input referenceID,
  593. /*in/out*/ MatchResult& match)
  594. {
  595. Result rv = MatchPresentedIDWithReferenceID(presentedIDType, presentedID,
  596. referenceIDType, referenceID,
  597. match);
  598. if (rv != Success) {
  599. match = MatchResult::Mismatch;
  600. }
  601. }
  602. Result
  603. MatchPresentedIDWithReferenceID(GeneralNameType presentedIDType,
  604. Input presentedID,
  605. GeneralNameType referenceIDType,
  606. Input referenceID,
  607. /*out*/ MatchResult& matchResult)
  608. {
  609. if (referenceIDType == GeneralNameType::nameConstraints) {
  610. // matchResult is irrelevant when checking name constraints; only the
  611. // pass/fail result of CheckPresentedIDConformsToConstraints matters.
  612. return CheckPresentedIDConformsToConstraints(presentedIDType, presentedID,
  613. referenceID);
  614. }
  615. if (presentedIDType != referenceIDType) {
  616. matchResult = MatchResult::Mismatch;
  617. return Success;
  618. }
  619. Result rv;
  620. bool foundMatch;
  621. switch (referenceIDType) {
  622. case GeneralNameType::dNSName:
  623. rv = MatchPresentedDNSIDWithReferenceDNSID(
  624. presentedID, AllowWildcards::Yes,
  625. AllowDotlessSubdomainMatches::Yes, IDRole::ReferenceID,
  626. referenceID, foundMatch);
  627. break;
  628. case GeneralNameType::iPAddress:
  629. foundMatch = InputsAreEqual(presentedID, referenceID);
  630. rv = Success;
  631. break;
  632. case GeneralNameType::rfc822Name:
  633. rv = MatchPresentedRFC822NameWithReferenceRFC822Name(
  634. presentedID, IDRole::ReferenceID, referenceID, foundMatch);
  635. break;
  636. case GeneralNameType::directoryName:
  637. // TODO: At some point, we may add APIs for matching DirectoryNames.
  638. // fall through
  639. case GeneralNameType::otherName: // fall through
  640. case GeneralNameType::x400Address: // fall through
  641. case GeneralNameType::ediPartyName: // fall through
  642. case GeneralNameType::uniformResourceIdentifier: // fall through
  643. case GeneralNameType::registeredID: // fall through
  644. case GeneralNameType::nameConstraints:
  645. return NotReached("unexpected nameType for SearchType::Match",
  646. Result::FATAL_ERROR_INVALID_ARGS);
  647. MOZILLA_PKIX_UNREACHABLE_DEFAULT_ENUM
  648. }
  649. if (rv != Success) {
  650. return rv;
  651. }
  652. matchResult = foundMatch ? MatchResult::Match : MatchResult::Mismatch;
  653. return Success;
  654. }
  655. enum class NameConstraintsSubtrees : uint8_t
  656. {
  657. permittedSubtrees = der::CONSTRUCTED | der::CONTEXT_SPECIFIC | 0,
  658. excludedSubtrees = der::CONSTRUCTED | der::CONTEXT_SPECIFIC | 1
  659. };
  660. Result CheckPresentedIDConformsToNameConstraintsSubtrees(
  661. GeneralNameType presentedIDType,
  662. Input presentedID,
  663. Reader& nameConstraints,
  664. NameConstraintsSubtrees subtreesType);
  665. Result MatchPresentedIPAddressWithConstraint(Input presentedID,
  666. Input iPAddressConstraint,
  667. /*out*/ bool& foundMatch);
  668. Result MatchPresentedDirectoryNameWithConstraint(
  669. NameConstraintsSubtrees subtreesType, Input presentedID,
  670. Input directoryNameConstraint, /*out*/ bool& matches);
  671. Result
  672. CheckPresentedIDConformsToConstraints(
  673. GeneralNameType presentedIDType,
  674. Input presentedID,
  675. Input encodedNameConstraints)
  676. {
  677. // NameConstraints ::= SEQUENCE {
  678. // permittedSubtrees [0] GeneralSubtrees OPTIONAL,
  679. // excludedSubtrees [1] GeneralSubtrees OPTIONAL }
  680. Reader nameConstraints;
  681. Result rv = der::ExpectTagAndGetValueAtEnd(encodedNameConstraints,
  682. der::SEQUENCE, nameConstraints);
  683. if (rv != Success) {
  684. return rv;
  685. }
  686. // RFC 5280 says "Conforming CAs MUST NOT issue certificates where name
  687. // constraints is an empty sequence. That is, either the permittedSubtrees
  688. // field or the excludedSubtrees MUST be present."
  689. if (nameConstraints.AtEnd()) {
  690. return Result::ERROR_BAD_DER;
  691. }
  692. rv = CheckPresentedIDConformsToNameConstraintsSubtrees(
  693. presentedIDType, presentedID, nameConstraints,
  694. NameConstraintsSubtrees::permittedSubtrees);
  695. if (rv != Success) {
  696. return rv;
  697. }
  698. rv = CheckPresentedIDConformsToNameConstraintsSubtrees(
  699. presentedIDType, presentedID, nameConstraints,
  700. NameConstraintsSubtrees::excludedSubtrees);
  701. if (rv != Success) {
  702. return rv;
  703. }
  704. return der::End(nameConstraints);
  705. }
  706. Result
  707. CheckPresentedIDConformsToNameConstraintsSubtrees(
  708. GeneralNameType presentedIDType,
  709. Input presentedID,
  710. Reader& nameConstraints,
  711. NameConstraintsSubtrees subtreesType)
  712. {
  713. if (!nameConstraints.Peek(static_cast<uint8_t>(subtreesType))) {
  714. return Success;
  715. }
  716. Reader subtrees;
  717. Result rv = der::ExpectTagAndGetValue(nameConstraints,
  718. static_cast<uint8_t>(subtreesType),
  719. subtrees);
  720. if (rv != Success) {
  721. return rv;
  722. }
  723. bool hasPermittedSubtreesMatch = false;
  724. bool hasPermittedSubtreesMismatch = false;
  725. // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
  726. //
  727. // do { ... } while(...) because subtrees isn't allowed to be empty.
  728. do {
  729. // GeneralSubtree ::= SEQUENCE {
  730. // base GeneralName,
  731. // minimum [0] BaseDistance DEFAULT 0,
  732. // maximum [1] BaseDistance OPTIONAL }
  733. Reader subtree;
  734. rv = ExpectTagAndGetValue(subtrees, der::SEQUENCE, subtree);
  735. if (rv != Success) {
  736. return rv;
  737. }
  738. GeneralNameType nameConstraintType;
  739. Input base;
  740. rv = ReadGeneralName(subtree, nameConstraintType, base);
  741. if (rv != Success) {
  742. return rv;
  743. }
  744. // http://tools.ietf.org/html/rfc5280#section-4.2.1.10: "Within this
  745. // profile, the minimum and maximum fields are not used with any name
  746. // forms, thus, the minimum MUST be zero, and maximum MUST be absent."
  747. //
  748. // Since the default value isn't allowed to be encoded according to the DER
  749. // encoding rules for DEFAULT, this is equivalent to saying that neither
  750. // minimum or maximum must be encoded.
  751. rv = der::End(subtree);
  752. if (rv != Success) {
  753. return rv;
  754. }
  755. if (presentedIDType == nameConstraintType) {
  756. bool matches;
  757. switch (presentedIDType) {
  758. case GeneralNameType::dNSName:
  759. rv = MatchPresentedDNSIDWithReferenceDNSID(
  760. presentedID, AllowWildcards::Yes,
  761. AllowDotlessSubdomainMatches::Yes, IDRole::NameConstraint,
  762. base, matches);
  763. if (rv != Success) {
  764. return rv;
  765. }
  766. break;
  767. case GeneralNameType::iPAddress:
  768. rv = MatchPresentedIPAddressWithConstraint(presentedID, base,
  769. matches);
  770. if (rv != Success) {
  771. return rv;
  772. }
  773. break;
  774. case GeneralNameType::directoryName:
  775. rv = MatchPresentedDirectoryNameWithConstraint(subtreesType,
  776. presentedID, base,
  777. matches);
  778. if (rv != Success) {
  779. return rv;
  780. }
  781. break;
  782. case GeneralNameType::rfc822Name:
  783. rv = MatchPresentedRFC822NameWithReferenceRFC822Name(
  784. presentedID, IDRole::NameConstraint, base, matches);
  785. if (rv != Success) {
  786. return rv;
  787. }
  788. break;
  789. // RFC 5280 says "Conforming CAs [...] SHOULD NOT impose name
  790. // constraints on the x400Address, ediPartyName, or registeredID
  791. // name forms. It also says "Applications conforming to this profile
  792. // [...] SHOULD be able to process name constraints that are imposed
  793. // on [...] uniformResourceIdentifier [...]", but we don't bother.
  794. //
  795. // TODO: Ask to have spec updated to say ""Conforming CAs [...] SHOULD
  796. // NOT impose name constraints on the otherName, x400Address,
  797. // ediPartyName, uniformResourceIdentifier, or registeredID name
  798. // forms."
  799. case GeneralNameType::otherName: // fall through
  800. case GeneralNameType::x400Address: // fall through
  801. case GeneralNameType::ediPartyName: // fall through
  802. case GeneralNameType::uniformResourceIdentifier: // fall through
  803. case GeneralNameType::registeredID: // fall through
  804. return Result::ERROR_CERT_NOT_IN_NAME_SPACE;
  805. case GeneralNameType::nameConstraints:
  806. return NotReached("invalid presentedIDType",
  807. Result::FATAL_ERROR_LIBRARY_FAILURE);
  808. MOZILLA_PKIX_UNREACHABLE_DEFAULT_ENUM
  809. }
  810. switch (subtreesType) {
  811. case NameConstraintsSubtrees::permittedSubtrees:
  812. if (matches) {
  813. hasPermittedSubtreesMatch = true;
  814. } else {
  815. hasPermittedSubtreesMismatch = true;
  816. }
  817. break;
  818. case NameConstraintsSubtrees::excludedSubtrees:
  819. if (matches) {
  820. return Result::ERROR_CERT_NOT_IN_NAME_SPACE;
  821. }
  822. break;
  823. }
  824. }
  825. } while (!subtrees.AtEnd());
  826. if (hasPermittedSubtreesMismatch && !hasPermittedSubtreesMatch) {
  827. // If there was any entry of the given type in permittedSubtrees, then it
  828. // required that at least one of them must match. Since none of them did,
  829. // we have a failure.
  830. return Result::ERROR_CERT_NOT_IN_NAME_SPACE;
  831. }
  832. return Success;
  833. }
  834. // We do not distinguish between a syntactically-invalid presentedDNSID and one
  835. // that is syntactically valid but does not match referenceDNSID; in both
  836. // cases, the result is false.
  837. //
  838. // We assume that both presentedDNSID and referenceDNSID are encoded in such a
  839. // way that US-ASCII (7-bit) characters are encoded in one byte and no encoding
  840. // of a non-US-ASCII character contains a code point in the range 0-127. For
  841. // example, UTF-8 is OK but UTF-16 is not.
  842. //
  843. // RFC6125 says that a wildcard label may be of the form <x>*<y>.<DNSID>, where
  844. // <x> and/or <y> may be empty. However, NSS requires <y> to be empty, and we
  845. // follow NSS's stricter policy by accepting wildcards only of the form
  846. // <x>*.<DNSID>, where <x> may be empty.
  847. //
  848. // An relative presented DNS ID matches both an absolute reference ID and a
  849. // relative reference ID. Absolute presented DNS IDs are not supported:
  850. //
  851. // Presented ID Reference ID Result
  852. // -------------------------------------
  853. // example.com example.com Match
  854. // example.com. example.com Mismatch
  855. // example.com example.com. Match
  856. // example.com. example.com. Mismatch
  857. //
  858. // There are more subtleties documented inline in the code.
  859. //
  860. // Name constraints ///////////////////////////////////////////////////////////
  861. //
  862. // This is all RFC 5280 has to say about DNSName constraints:
  863. //
  864. // DNS name restrictions are expressed as host.example.com. Any DNS
  865. // name that can be constructed by simply adding zero or more labels to
  866. // the left-hand side of the name satisfies the name constraint. For
  867. // example, www.host.example.com would satisfy the constraint but
  868. // host1.example.com would not.
  869. //
  870. // This lack of specificity has lead to a lot of uncertainty regarding
  871. // subdomain matching. In particular, the following questions have been
  872. // raised and answered:
  873. //
  874. // Q: Does a presented identifier equal (case insensitive) to the name
  875. // constraint match the constraint? For example, does the presented
  876. // ID "host.example.com" match a "host.example.com" constraint?
  877. // A: Yes. RFC5280 says "by simply adding zero or more labels" and this
  878. // is the case of adding zero labels.
  879. //
  880. // Q: When the name constraint does not start with ".", do subdomain
  881. // presented identifiers match it? For example, does the presented
  882. // ID "www.host.example.com" match a "host.example.com" constraint?
  883. // A: Yes. RFC5280 says "by simply adding zero or more labels" and this
  884. // is the case of adding more than zero labels. The example is the
  885. // one from RFC 5280.
  886. //
  887. // Q: When the name constraint does not start with ".", does a
  888. // non-subdomain prefix match it? For example, does "bigfoo.bar.com"
  889. // match "foo.bar.com"? [4]
  890. // A: No. We interpret RFC 5280's language of "adding zero or more labels"
  891. // to mean that whole labels must be prefixed.
  892. //
  893. // (Note that the above three scenarios are the same as the RFC 6265
  894. // domain matching rules [0].)
  895. //
  896. // Q: Is a name constraint that starts with "." valid, and if so, what
  897. // semantics does it have? For example, does a presented ID of
  898. // "www.example.com" match a constraint of ".example.com"? Does a
  899. // presented ID of "example.com" match a constraint of ".example.com"?
  900. // A: This implementation, NSS[1], and SChannel[2] all support a
  901. // leading ".", but OpenSSL[3] does not yet. Amongst the
  902. // implementations that support it, a leading "." is legal and means
  903. // the same thing as when the "." is omitted, EXCEPT that a
  904. // presented identifier equal (case insensitive) to the name
  905. // constraint is not matched; i.e. presented DNSName identifiers
  906. // must be subdomains. Some CAs in Mozilla's CA program (e.g. HARICA)
  907. // have name constraints with the leading "." in their root
  908. // certificates. The name constraints imposed on DCISS by Mozilla also
  909. // have the it, so supporting this is a requirement for backward
  910. // compatibility, even if it is not yet standardized. So, for example, a
  911. // presented ID of "www.example.com" matches a constraint of
  912. // ".example.com" but a presented ID of "example.com" does not.
  913. //
  914. // Q: Is there a way to prevent subdomain matches?
  915. // A: Yes.
  916. //
  917. // Some people have proposed that dNSName constraints that do not
  918. // start with a "." should be restricted to exact (case insensitive)
  919. // matches. However, such a change of semantics from what RFC5280
  920. // specifies would be a non-backward-compatible change in the case of
  921. // permittedSubtrees constraints, and it would be a security issue for
  922. // excludedSubtrees constraints.
  923. //
  924. // However, it can be done with a combination of permittedSubtrees and
  925. // excludedSubtrees, e.g. "example.com" in permittedSubtrees and
  926. // ".example.com" in excudedSubtrees.
  927. //
  928. // Q: Are name constraints allowed to be specified as absolute names?
  929. // For example, does a presented ID of "example.com" match a name
  930. // constraint of "example.com." and vice versa.
  931. // A: Absolute names are not supported as presented IDs or name
  932. // constraints. Only reference IDs may be absolute.
  933. //
  934. // Q: Is "" a valid DNSName constraints? If so, what does it mean?
  935. // A: Yes. Any valid presented DNSName can be formed "by simply adding zero
  936. // or more labels to the left-hand side" of "". In particular, an
  937. // excludedSubtrees DNSName constraint of "" forbids all DNSNames.
  938. //
  939. // Q: Is "." a valid DNSName constraints? If so, what does it mean?
  940. // A: No, because absolute names are not allowed (see above).
  941. //
  942. // [0] RFC 6265 (Cookies) Domain Matching rules:
  943. // http://tools.ietf.org/html/rfc6265#section-5.1.3
  944. // [1] NSS source code:
  945. // https://mxr.mozilla.org/nss/source/lib/certdb/genname.c?rev=2a7348f013cb#1209
  946. // [2] Description of SChannel's behavior from Microsoft:
  947. // http://www.imc.org/ietf-pkix/mail-archive/msg04668.html
  948. // [3] Proposal to add such support to OpenSSL:
  949. // http://www.mail-archive.com/openssl-dev%40openssl.org/msg36204.html
  950. // https://rt.openssl.org/Ticket/Display.html?id=3562
  951. // [4] Feedback on the lack of clarify in the definition that never got
  952. // incorporated into the spec:
  953. // https://www.ietf.org/mail-archive/web/pkix/current/msg21192.html
  954. Result
  955. MatchPresentedDNSIDWithReferenceDNSID(
  956. Input presentedDNSID,
  957. AllowWildcards allowWildcards,
  958. AllowDotlessSubdomainMatches allowDotlessSubdomainMatches,
  959. IDRole referenceDNSIDRole,
  960. Input referenceDNSID,
  961. /*out*/ bool& matches)
  962. {
  963. if (!IsValidDNSID(presentedDNSID, IDRole::PresentedID, allowWildcards)) {
  964. return Result::ERROR_BAD_DER;
  965. }
  966. if (!IsValidDNSID(referenceDNSID, referenceDNSIDRole, AllowWildcards::No)) {
  967. return Result::ERROR_BAD_DER;
  968. }
  969. Reader presented(presentedDNSID);
  970. Reader reference(referenceDNSID);
  971. switch (referenceDNSIDRole)
  972. {
  973. case IDRole::ReferenceID:
  974. break;
  975. case IDRole::NameConstraint:
  976. {
  977. if (presentedDNSID.GetLength() > referenceDNSID.GetLength()) {
  978. if (referenceDNSID.GetLength() == 0) {
  979. // An empty constraint matches everything.
  980. matches = true;
  981. return Success;
  982. }
  983. // If the reference ID starts with a dot then skip the prefix of
  984. // of the presented ID and start the comparison at the position of that
  985. // dot. Examples:
  986. //
  987. // Matches Doesn't Match
  988. // -----------------------------------------------------------
  989. // original presented ID: www.example.com badexample.com
  990. // skipped: www ba
  991. // presented ID w/o prefix: .example.com dexample.com
  992. // reference ID: .example.com .example.com
  993. //
  994. // If the reference ID does not start with a dot then we skip the
  995. // prefix of the presented ID but also verify that the prefix ends with
  996. // a dot. Examples:
  997. //
  998. // Matches Doesn't Match
  999. // -----------------------------------------------------------
  1000. // original presented ID: www.example.com badexample.com
  1001. // skipped: www ba
  1002. // must be '.': . d
  1003. // presented ID w/o prefix: example.com example.com
  1004. // reference ID: example.com example.com
  1005. //
  1006. if (reference.Peek('.')) {
  1007. if (presented.Skip(static_cast<Input::size_type>(
  1008. presentedDNSID.GetLength() -
  1009. referenceDNSID.GetLength())) != Success) {
  1010. return NotReached("skipping subdomain failed",
  1011. Result::FATAL_ERROR_LIBRARY_FAILURE);
  1012. }
  1013. } else if (allowDotlessSubdomainMatches ==
  1014. AllowDotlessSubdomainMatches::Yes) {
  1015. if (presented.Skip(static_cast<Input::size_type>(
  1016. presentedDNSID.GetLength() -
  1017. referenceDNSID.GetLength() - 1)) != Success) {
  1018. return NotReached("skipping subdomains failed",
  1019. Result::FATAL_ERROR_LIBRARY_FAILURE);
  1020. }
  1021. uint8_t b;
  1022. if (presented.Read(b) != Success) {
  1023. return NotReached("reading from presentedDNSID failed",
  1024. Result::FATAL_ERROR_LIBRARY_FAILURE);
  1025. }
  1026. if (b != '.') {
  1027. matches = false;
  1028. return Success;
  1029. }
  1030. }
  1031. }
  1032. break;
  1033. }
  1034. case IDRole::PresentedID: // fall through
  1035. return NotReached("IDRole::PresentedID is not a valid referenceDNSIDRole",
  1036. Result::FATAL_ERROR_INVALID_ARGS);
  1037. }
  1038. // We only allow wildcard labels that consist only of '*'.
  1039. if (presented.Peek('*')) {
  1040. if (presented.Skip(1) != Success) {
  1041. return NotReached("Skipping '*' failed",
  1042. Result::FATAL_ERROR_LIBRARY_FAILURE);
  1043. }
  1044. do {
  1045. // This will happen if reference is a single, relative label
  1046. if (reference.AtEnd()) {
  1047. matches = false;
  1048. return Success;
  1049. }
  1050. uint8_t referenceByte;
  1051. if (reference.Read(referenceByte) != Success) {
  1052. return NotReached("invalid reference ID",
  1053. Result::FATAL_ERROR_INVALID_ARGS);
  1054. }
  1055. } while (!reference.Peek('.'));
  1056. }
  1057. for (;;) {
  1058. uint8_t presentedByte;
  1059. if (presented.Read(presentedByte) != Success) {
  1060. matches = false;
  1061. return Success;
  1062. }
  1063. uint8_t referenceByte;
  1064. if (reference.Read(referenceByte) != Success) {
  1065. matches = false;
  1066. return Success;
  1067. }
  1068. if (LocaleInsensitveToLower(presentedByte) !=
  1069. LocaleInsensitveToLower(referenceByte)) {
  1070. matches = false;
  1071. return Success;
  1072. }
  1073. if (presented.AtEnd()) {
  1074. // Don't allow presented IDs to be absolute.
  1075. if (presentedByte == '.') {
  1076. return Result::ERROR_BAD_DER;
  1077. }
  1078. break;
  1079. }
  1080. }
  1081. // Allow a relative presented DNS ID to match an absolute reference DNS ID,
  1082. // unless we're matching a name constraint.
  1083. if (!reference.AtEnd()) {
  1084. if (referenceDNSIDRole != IDRole::NameConstraint) {
  1085. uint8_t referenceByte;
  1086. if (reference.Read(referenceByte) != Success) {
  1087. return NotReached("read failed but not at end",
  1088. Result::FATAL_ERROR_LIBRARY_FAILURE);
  1089. }
  1090. if (referenceByte != '.') {
  1091. matches = false;
  1092. return Success;
  1093. }
  1094. }
  1095. if (!reference.AtEnd()) {
  1096. matches = false;
  1097. return Success;
  1098. }
  1099. }
  1100. matches = true;
  1101. return Success;
  1102. }
  1103. // https://tools.ietf.org/html/rfc5280#section-4.2.1.10 says:
  1104. //
  1105. // For IPv4 addresses, the iPAddress field of GeneralName MUST contain
  1106. // eight (8) octets, encoded in the style of RFC 4632 (CIDR) to represent
  1107. // an address range [RFC4632]. For IPv6 addresses, the iPAddress field
  1108. // MUST contain 32 octets similarly encoded. For example, a name
  1109. // constraint for "class C" subnet 192.0.2.0 is represented as the
  1110. // octets C0 00 02 00 FF FF FF 00, representing the CIDR notation
  1111. // 192.0.2.0/24 (mask 255.255.255.0).
  1112. Result
  1113. MatchPresentedIPAddressWithConstraint(Input presentedID,
  1114. Input iPAddressConstraint,
  1115. /*out*/ bool& foundMatch)
  1116. {
  1117. if (presentedID.GetLength() != 4 && presentedID.GetLength() != 16) {
  1118. return Result::ERROR_BAD_DER;
  1119. }
  1120. if (iPAddressConstraint.GetLength() != 8 &&
  1121. iPAddressConstraint.GetLength() != 32) {
  1122. return Result::ERROR_BAD_DER;
  1123. }
  1124. // an IPv4 address never matches an IPv6 constraint, and vice versa.
  1125. if (presentedID.GetLength() * 2 != iPAddressConstraint.GetLength()) {
  1126. foundMatch = false;
  1127. return Success;
  1128. }
  1129. Reader constraint(iPAddressConstraint);
  1130. Reader constraintAddress;
  1131. Result rv = constraint.Skip(iPAddressConstraint.GetLength() / 2u,
  1132. constraintAddress);
  1133. if (rv != Success) {
  1134. return rv;
  1135. }
  1136. Reader constraintMask;
  1137. rv = constraint.Skip(iPAddressConstraint.GetLength() / 2u, constraintMask);
  1138. if (rv != Success) {
  1139. return rv;
  1140. }
  1141. rv = der::End(constraint);
  1142. if (rv != Success) {
  1143. return rv;
  1144. }
  1145. Reader presented(presentedID);
  1146. do {
  1147. uint8_t presentedByte;
  1148. rv = presented.Read(presentedByte);
  1149. if (rv != Success) {
  1150. return rv;
  1151. }
  1152. uint8_t constraintAddressByte;
  1153. rv = constraintAddress.Read(constraintAddressByte);
  1154. if (rv != Success) {
  1155. return rv;
  1156. }
  1157. uint8_t constraintMaskByte;
  1158. rv = constraintMask.Read(constraintMaskByte);
  1159. if (rv != Success) {
  1160. return rv;
  1161. }
  1162. foundMatch =
  1163. ((presentedByte ^ constraintAddressByte) & constraintMaskByte) == 0;
  1164. } while (foundMatch && !presented.AtEnd());
  1165. return Success;
  1166. }
  1167. // AttributeTypeAndValue ::= SEQUENCE {
  1168. // type AttributeType,
  1169. // value AttributeValue }
  1170. //
  1171. // AttributeType ::= OBJECT IDENTIFIER
  1172. //
  1173. // AttributeValue ::= ANY -- DEFINED BY AttributeType
  1174. Result
  1175. ReadAVA(Reader& rdn,
  1176. /*out*/ Input& type,
  1177. /*out*/ uint8_t& valueTag,
  1178. /*out*/ Input& value)
  1179. {
  1180. return der::Nested(rdn, der::SEQUENCE, [&](Reader& ava) -> Result {
  1181. Result rv = der::ExpectTagAndGetValue(ava, der::OIDTag, type);
  1182. if (rv != Success) {
  1183. return rv;
  1184. }
  1185. rv = der::ReadTagAndGetValue(ava, valueTag, value);
  1186. if (rv != Success) {
  1187. return rv;
  1188. }
  1189. return Success;
  1190. });
  1191. }
  1192. // Names are sequences of RDNs. RDNS are sets of AVAs. That means that RDNs are
  1193. // unordered, so in theory we should match RDNs with equivalent AVAs that are
  1194. // in different orders. Within the AVAs are DirectoryNames that are supposed to
  1195. // be compared according to LDAP stringprep normalization rules (e.g.
  1196. // normalizing whitespace), consideration of different character encodings,
  1197. // etc. Indeed, RFC 5280 says we MUST deal with all of that.
  1198. //
  1199. // In practice, many implementations, including NSS, only match Names in a way
  1200. // that only meets a subset of the requirements of RFC 5280. Those
  1201. // normalization and character encoding conversion steps appear to be
  1202. // unnecessary for processing real-world certificates, based on experience from
  1203. // having used NSS in Firefox for many years.
  1204. //
  1205. // RFC 5280 also says "CAs issuing certificates with a restriction of the form
  1206. // directoryName SHOULD NOT rely on implementation of the full
  1207. // ISO DN name comparison algorithm. This implies name restrictions MUST
  1208. // be stated identically to the encoding used in the subject field or
  1209. // subjectAltName extension." It goes on to say, in the security
  1210. // considerations:
  1211. //
  1212. // In addition, name constraints for distinguished names MUST be stated
  1213. // identically to the encoding used in the subject field or
  1214. // subjectAltName extension. If not, then name constraints stated as
  1215. // excludedSubtrees will not match and invalid paths will be accepted
  1216. // and name constraints expressed as permittedSubtrees will not match
  1217. // and valid paths will be rejected. To avoid acceptance of invalid
  1218. // paths, CAs SHOULD state name constraints for distinguished names as
  1219. // permittedSubtrees wherever possible.
  1220. //
  1221. // For permittedSubtrees, the MUST-level requirement is relaxed for
  1222. // compatibility in the case of PrintableString and UTF8String. That is, if a
  1223. // name constraint has been encoded using UTF8String and the presented ID has
  1224. // been encoded with a PrintableString (or vice-versa), they are considered to
  1225. // match if they are equal everywhere except for the tag identifying the
  1226. // encoding. See bug 1150114.
  1227. //
  1228. // For excludedSubtrees, we simply prohibit any non-empty directoryName
  1229. // constraint to ensure we are not being too lenient. We support empty
  1230. // DirectoryName constraints in excludedSubtrees so that a CA can say "Do not
  1231. // allow any DirectoryNames in issued certificates."
  1232. Result
  1233. MatchPresentedDirectoryNameWithConstraint(NameConstraintsSubtrees subtreesType,
  1234. Input presentedID,
  1235. Input directoryNameConstraint,
  1236. /*out*/ bool& matches)
  1237. {
  1238. Reader constraintRDNs;
  1239. Result rv = der::ExpectTagAndGetValueAtEnd(directoryNameConstraint,
  1240. der::SEQUENCE, constraintRDNs);
  1241. if (rv != Success) {
  1242. return rv;
  1243. }
  1244. Reader presentedRDNs;
  1245. rv = der::ExpectTagAndGetValueAtEnd(presentedID, der::SEQUENCE,
  1246. presentedRDNs);
  1247. if (rv != Success) {
  1248. return rv;
  1249. }
  1250. switch (subtreesType) {
  1251. case NameConstraintsSubtrees::permittedSubtrees:
  1252. break; // dealt with below
  1253. case NameConstraintsSubtrees::excludedSubtrees:
  1254. if (!constraintRDNs.AtEnd() || !presentedRDNs.AtEnd()) {
  1255. return Result::ERROR_CERT_NOT_IN_NAME_SPACE;
  1256. }
  1257. matches = true;
  1258. return Success;
  1259. }
  1260. for (;;) {
  1261. // The AVAs have to be fully equal, but the constraint RDNs just need to be
  1262. // a prefix of the presented RDNs.
  1263. if (constraintRDNs.AtEnd()) {
  1264. matches = true;
  1265. return Success;
  1266. }
  1267. if (presentedRDNs.AtEnd()) {
  1268. matches = false;
  1269. return Success;
  1270. }
  1271. Reader constraintRDN;
  1272. rv = der::ExpectTagAndGetValue(constraintRDNs, der::SET, constraintRDN);
  1273. if (rv != Success) {
  1274. return rv;
  1275. }
  1276. Reader presentedRDN;
  1277. rv = der::ExpectTagAndGetValue(presentedRDNs, der::SET, presentedRDN);
  1278. if (rv != Success) {
  1279. return rv;
  1280. }
  1281. while (!constraintRDN.AtEnd() && !presentedRDN.AtEnd()) {
  1282. Input constraintType;
  1283. uint8_t constraintValueTag;
  1284. Input constraintValue;
  1285. rv = ReadAVA(constraintRDN, constraintType, constraintValueTag,
  1286. constraintValue);
  1287. if (rv != Success) {
  1288. return rv;
  1289. }
  1290. Input presentedType;
  1291. uint8_t presentedValueTag;
  1292. Input presentedValue;
  1293. rv = ReadAVA(presentedRDN, presentedType, presentedValueTag,
  1294. presentedValue);
  1295. if (rv != Success) {
  1296. return rv;
  1297. }
  1298. // TODO (bug 1155767): verify that if an AVA is a PrintableString it
  1299. // consists only of characters valid for PrintableStrings.
  1300. bool avasMatch =
  1301. InputsAreEqual(constraintType, presentedType) &&
  1302. InputsAreEqual(constraintValue, presentedValue) &&
  1303. (constraintValueTag == presentedValueTag ||
  1304. (constraintValueTag == der::Tag::UTF8String &&
  1305. presentedValueTag == der::Tag::PrintableString) ||
  1306. (constraintValueTag == der::Tag::PrintableString &&
  1307. presentedValueTag == der::Tag::UTF8String));
  1308. if (!avasMatch) {
  1309. matches = false;
  1310. return Success;
  1311. }
  1312. }
  1313. if (!constraintRDN.AtEnd() || !presentedRDN.AtEnd()) {
  1314. matches = false;
  1315. return Success;
  1316. }
  1317. }
  1318. }
  1319. // RFC 5280 says:
  1320. //
  1321. // The format of an rfc822Name is a "Mailbox" as defined in Section 4.1.2
  1322. // of [RFC2821]. A Mailbox has the form "Local-part@Domain". Note that a
  1323. // Mailbox has no phrase (such as a common name) before it, has no comment
  1324. // (text surrounded in parentheses) after it, and is not surrounded by "<"
  1325. // and ">". Rules for encoding Internet mail addresses that include
  1326. // internationalized domain names are specified in Section 7.5.
  1327. //
  1328. // and:
  1329. //
  1330. // A name constraint for Internet mail addresses MAY specify a
  1331. // particular mailbox, all addresses at a particular host, or all
  1332. // mailboxes in a domain. To indicate a particular mailbox, the
  1333. // constraint is the complete mail address. For example,
  1334. // "root@example.com" indicates the root mailbox on the host
  1335. // "example.com". To indicate all Internet mail addresses on a
  1336. // particular host, the constraint is specified as the host name. For
  1337. // example, the constraint "example.com" is satisfied by any mail
  1338. // address at the host "example.com". To specify any address within a
  1339. // domain, the constraint is specified with a leading period (as with
  1340. // URIs). For example, ".example.com" indicates all the Internet mail
  1341. // addresses in the domain "example.com", but not Internet mail
  1342. // addresses on the host "example.com".
  1343. bool
  1344. IsValidRFC822Name(Input input)
  1345. {
  1346. Reader reader(input);
  1347. // Local-part@.
  1348. bool startOfAtom = true;
  1349. for (;;) {
  1350. uint8_t presentedByte;
  1351. if (reader.Read(presentedByte) != Success) {
  1352. return false;
  1353. }
  1354. switch (presentedByte) {
  1355. // atext is defined in https://tools.ietf.org/html/rfc2822#section-3.2.4
  1356. case 'A': case 'a': case 'N': case 'n': case '0': case '!': case '#':
  1357. case 'B': case 'b': case 'O': case 'o': case '1': case '$': case '%':
  1358. case 'C': case 'c': case 'P': case 'p': case '2': case '&': case '\'':
  1359. case 'D': case 'd': case 'Q': case 'q': case '3': case '*': case '+':
  1360. case 'E': case 'e': case 'R': case 'r': case '4': case '-': case '/':
  1361. case 'F': case 'f': case 'S': case 's': case '5': case '=': case '?':
  1362. case 'G': case 'g': case 'T': case 't': case '6': case '^': case '_':
  1363. case 'H': case 'h': case 'U': case 'u': case '7': case '`': case '{':
  1364. case 'I': case 'i': case 'V': case 'v': case '8': case '|': case '}':
  1365. case 'J': case 'j': case 'W': case 'w': case '9': case '~':
  1366. case 'K': case 'k': case 'X': case 'x':
  1367. case 'L': case 'l': case 'Y': case 'y':
  1368. case 'M': case 'm': case 'Z': case 'z':
  1369. startOfAtom = false;
  1370. break;
  1371. case '.':
  1372. if (startOfAtom) {
  1373. return false;
  1374. }
  1375. startOfAtom = true;
  1376. break;
  1377. case '@':
  1378. {
  1379. if (startOfAtom) {
  1380. return false;
  1381. }
  1382. Input domain;
  1383. if (reader.SkipToEnd(domain) != Success) {
  1384. return false;
  1385. }
  1386. return IsValidDNSID(domain, IDRole::PresentedID, AllowWildcards::No);
  1387. }
  1388. default:
  1389. return false;
  1390. }
  1391. }
  1392. }
  1393. Result
  1394. MatchPresentedRFC822NameWithReferenceRFC822Name(Input presentedRFC822Name,
  1395. IDRole referenceRFC822NameRole,
  1396. Input referenceRFC822Name,
  1397. /*out*/ bool& matches)
  1398. {
  1399. if (!IsValidRFC822Name(presentedRFC822Name)) {
  1400. return Result::ERROR_BAD_DER;
  1401. }
  1402. Reader presented(presentedRFC822Name);
  1403. switch (referenceRFC822NameRole)
  1404. {
  1405. case IDRole::PresentedID:
  1406. return Result::FATAL_ERROR_INVALID_ARGS;
  1407. case IDRole::ReferenceID:
  1408. break;
  1409. case IDRole::NameConstraint:
  1410. {
  1411. if (InputContains(referenceRFC822Name, '@')) {
  1412. // The constraint is of the form "Local-part@Domain".
  1413. break;
  1414. }
  1415. // The constraint is of the form "example.com" or ".example.com".
  1416. // Skip past the '@' in the presented ID.
  1417. for (;;) {
  1418. uint8_t presentedByte;
  1419. if (presented.Read(presentedByte) != Success) {
  1420. return Result::FATAL_ERROR_LIBRARY_FAILURE;
  1421. }
  1422. if (presentedByte == '@') {
  1423. break;
  1424. }
  1425. }
  1426. Input presentedDNSID;
  1427. if (presented.SkipToEnd(presentedDNSID) != Success) {
  1428. return Result::FATAL_ERROR_LIBRARY_FAILURE;
  1429. }
  1430. return MatchPresentedDNSIDWithReferenceDNSID(
  1431. presentedDNSID, AllowWildcards::No,
  1432. AllowDotlessSubdomainMatches::No, IDRole::NameConstraint,
  1433. referenceRFC822Name, matches);
  1434. }
  1435. }
  1436. if (!IsValidRFC822Name(referenceRFC822Name)) {
  1437. return Result::ERROR_BAD_DER;
  1438. }
  1439. Reader reference(referenceRFC822Name);
  1440. for (;;) {
  1441. uint8_t presentedByte;
  1442. if (presented.Read(presentedByte) != Success) {
  1443. matches = reference.AtEnd();
  1444. return Success;
  1445. }
  1446. uint8_t referenceByte;
  1447. if (reference.Read(referenceByte) != Success) {
  1448. matches = false;
  1449. return Success;
  1450. }
  1451. if (LocaleInsensitveToLower(presentedByte) !=
  1452. LocaleInsensitveToLower(referenceByte)) {
  1453. matches = false;
  1454. return Success;
  1455. }
  1456. }
  1457. }
  1458. // We avoid isdigit because it is locale-sensitive. See
  1459. // http://pubs.opengroup.org/onlinepubs/009695399/functions/tolower.html.
  1460. inline uint8_t
  1461. LocaleInsensitveToLower(uint8_t a)
  1462. {
  1463. if (a >= 'A' && a <= 'Z') { // unlikely
  1464. return static_cast<uint8_t>(
  1465. static_cast<uint8_t>(a - static_cast<uint8_t>('A')) +
  1466. static_cast<uint8_t>('a'));
  1467. }
  1468. return a;
  1469. }
  1470. bool
  1471. StartsWithIDNALabel(Input id)
  1472. {
  1473. static const uint8_t IDN_ALABEL_PREFIX[4] = { 'x', 'n', '-', '-' };
  1474. Reader input(id);
  1475. for (const uint8_t prefixByte : IDN_ALABEL_PREFIX) {
  1476. uint8_t b;
  1477. if (input.Read(b) != Success) {
  1478. return false;
  1479. }
  1480. if (b != prefixByte) {
  1481. return false;
  1482. }
  1483. }
  1484. return true;
  1485. }
  1486. bool
  1487. ReadIPv4AddressComponent(Reader& input, bool lastComponent,
  1488. /*out*/ uint8_t& valueOut)
  1489. {
  1490. size_t length = 0;
  1491. unsigned int value = 0; // Must be larger than uint8_t.
  1492. for (;;) {
  1493. if (input.AtEnd() && lastComponent) {
  1494. break;
  1495. }
  1496. uint8_t b;
  1497. if (input.Read(b) != Success) {
  1498. return false;
  1499. }
  1500. if (b >= '0' && b <= '9') {
  1501. if (value == 0 && length > 0) {
  1502. return false; // Leading zeros are not allowed.
  1503. }
  1504. value = (value * 10) + (b - '0');
  1505. if (value > 255) {
  1506. return false; // Component's value is too large.
  1507. }
  1508. ++length;
  1509. } else if (!lastComponent && b == '.') {
  1510. break;
  1511. } else {
  1512. return false; // Invalid character.
  1513. }
  1514. }
  1515. if (length == 0) {
  1516. return false; // empty components not allowed
  1517. }
  1518. valueOut = static_cast<uint8_t>(value);
  1519. return true;
  1520. }
  1521. } // namespace
  1522. // On Windows and maybe other platforms, OS-provided IP address parsing
  1523. // functions might fail if the protocol (IPv4 or IPv6) has been disabled, so we
  1524. // can't rely on them.
  1525. bool
  1526. ParseIPv4Address(Input hostname, /*out*/ uint8_t (&out)[4])
  1527. {
  1528. Reader input(hostname);
  1529. return ReadIPv4AddressComponent(input, false, out[0]) &&
  1530. ReadIPv4AddressComponent(input, false, out[1]) &&
  1531. ReadIPv4AddressComponent(input, false, out[2]) &&
  1532. ReadIPv4AddressComponent(input, true, out[3]);
  1533. }
  1534. namespace {
  1535. bool
  1536. FinishIPv6Address(/*in/out*/ uint8_t (&address)[16], int numComponents,
  1537. int contractionIndex)
  1538. {
  1539. assert(numComponents >= 0);
  1540. assert(numComponents <= 8);
  1541. assert(contractionIndex >= -1);
  1542. assert(contractionIndex <= 8);
  1543. assert(contractionIndex <= numComponents);
  1544. if (!(numComponents >= 0 &&
  1545. numComponents <= 8 &&
  1546. contractionIndex >= -1 &&
  1547. contractionIndex <= 8 &&
  1548. contractionIndex <= numComponents)) {
  1549. return false;
  1550. }
  1551. if (contractionIndex == -1) {
  1552. // no contraction
  1553. return numComponents == 8;
  1554. }
  1555. if (numComponents >= 8) {
  1556. return false; // no room left to expand the contraction.
  1557. }
  1558. // Shift components that occur after the contraction over.
  1559. std::copy_backward(address + (2u * static_cast<size_t>(contractionIndex)),
  1560. address + (2u * static_cast<size_t>(numComponents)),
  1561. address + (2u * 8u));
  1562. // Fill in the contracted area with zeros.
  1563. std::fill_n(address + 2u * static_cast<size_t>(contractionIndex),
  1564. (8u - static_cast<size_t>(numComponents)) * 2u, static_cast<uint8_t>(0u));
  1565. return true;
  1566. }
  1567. } // namespace
  1568. // On Windows and maybe other platforms, OS-provided IP address parsing
  1569. // functions might fail if the protocol (IPv4 or IPv6) has been disabled, so we
  1570. // can't rely on them.
  1571. bool
  1572. ParseIPv6Address(Input hostname, /*out*/ uint8_t (&out)[16])
  1573. {
  1574. Reader input(hostname);
  1575. int currentComponentIndex = 0;
  1576. int contractionIndex = -1;
  1577. if (input.Peek(':')) {
  1578. // A valid input can only start with ':' if there is a contraction at the
  1579. // beginning.
  1580. uint8_t b;
  1581. if (input.Read(b) != Success || b != ':') {
  1582. assert(false);
  1583. return false;
  1584. }
  1585. if (input.Read(b) != Success) {
  1586. return false;
  1587. }
  1588. if (b != ':') {
  1589. return false;
  1590. }
  1591. contractionIndex = 0;
  1592. }
  1593. for (;;) {
  1594. // If we encounter a '.' then we'll have to backtrack to parse the input
  1595. // from startOfComponent to the end of the input as an IPv4 address.
  1596. Reader::Mark startOfComponent(input.GetMark());
  1597. uint16_t componentValue = 0;
  1598. size_t componentLength = 0;
  1599. while (!input.AtEnd() && !input.Peek(':')) {
  1600. uint8_t value;
  1601. uint8_t b;
  1602. if (input.Read(b) != Success) {
  1603. assert(false);
  1604. return false;
  1605. }
  1606. switch (b) {
  1607. case '0': case '1': case '2': case '3': case '4':
  1608. case '5': case '6': case '7': case '8': case '9':
  1609. value = static_cast<uint8_t>(b - static_cast<uint8_t>('0'));
  1610. break;
  1611. case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
  1612. value = static_cast<uint8_t>(b - static_cast<uint8_t>('a') +
  1613. UINT8_C(10));
  1614. break;
  1615. case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
  1616. value = static_cast<uint8_t>(b - static_cast<uint8_t>('A') +
  1617. UINT8_C(10));
  1618. break;
  1619. case '.':
  1620. {
  1621. // A dot indicates we hit a IPv4-syntax component. Backtrack, parsing
  1622. // the input from startOfComponent to the end of the input as an IPv4
  1623. // address, and then combine it with the other components.
  1624. if (currentComponentIndex > 6) {
  1625. return false; // Too many components before the IPv4 component
  1626. }
  1627. input.SkipToEnd();
  1628. Input ipv4Component;
  1629. if (input.GetInput(startOfComponent, ipv4Component) != Success) {
  1630. return false;
  1631. }
  1632. uint8_t (*ipv4)[4] =
  1633. reinterpret_cast<uint8_t(*)[4]>(&out[2 * currentComponentIndex]);
  1634. if (!ParseIPv4Address(ipv4Component, *ipv4)) {
  1635. return false;
  1636. }
  1637. assert(input.AtEnd());
  1638. currentComponentIndex += 2;
  1639. return FinishIPv6Address(out, currentComponentIndex,
  1640. contractionIndex);
  1641. }
  1642. default:
  1643. return false;
  1644. }
  1645. if (componentLength >= 4) {
  1646. // component too long
  1647. return false;
  1648. }
  1649. ++componentLength;
  1650. componentValue = (componentValue * 0x10u) + value;
  1651. }
  1652. if (currentComponentIndex >= 8) {
  1653. return false; // too many components
  1654. }
  1655. if (componentLength == 0) {
  1656. if (input.AtEnd() && currentComponentIndex == contractionIndex) {
  1657. if (contractionIndex == 0) {
  1658. // don't accept "::"
  1659. return false;
  1660. }
  1661. return FinishIPv6Address(out, currentComponentIndex,
  1662. contractionIndex);
  1663. }
  1664. return false;
  1665. }
  1666. out[2 * currentComponentIndex] =
  1667. static_cast<uint8_t>(componentValue / 0x100);
  1668. out[(2 * currentComponentIndex) + 1] =
  1669. static_cast<uint8_t>(componentValue % 0x100);
  1670. ++currentComponentIndex;
  1671. if (input.AtEnd()) {
  1672. return FinishIPv6Address(out, currentComponentIndex,
  1673. contractionIndex);
  1674. }
  1675. uint8_t b;
  1676. if (input.Read(b) != Success || b != ':') {
  1677. assert(false);
  1678. return false;
  1679. }
  1680. if (input.Peek(':')) {
  1681. // Contraction
  1682. if (contractionIndex != -1) {
  1683. return false; // multiple contractions are not allowed.
  1684. }
  1685. if (input.Read(b) != Success || b != ':') {
  1686. assert(false);
  1687. return false;
  1688. }
  1689. contractionIndex = currentComponentIndex;
  1690. if (input.AtEnd()) {
  1691. // "::" at the end of the input.
  1692. return FinishIPv6Address(out, currentComponentIndex,
  1693. contractionIndex);
  1694. }
  1695. }
  1696. }
  1697. }
  1698. bool
  1699. IsValidReferenceDNSID(Input hostname)
  1700. {
  1701. return IsValidDNSID(hostname, IDRole::ReferenceID, AllowWildcards::No);
  1702. }
  1703. bool
  1704. IsValidPresentedDNSID(Input hostname)
  1705. {
  1706. return IsValidDNSID(hostname, IDRole::PresentedID, AllowWildcards::Yes);
  1707. }
  1708. namespace {
  1709. // RFC 5280 Section 4.2.1.6 says that a dNSName "MUST be in the 'preferred name
  1710. // syntax', as specified by Section 3.5 of [RFC1034] and as modified by Section
  1711. // 2.1 of [RFC1123]" except "a dNSName of ' ' MUST NOT be used." Additionally,
  1712. // we allow underscores for compatibility with existing practice.
  1713. bool
  1714. IsValidDNSID(Input hostname, IDRole idRole, AllowWildcards allowWildcards)
  1715. {
  1716. if (hostname.GetLength() > 253) {
  1717. return false;
  1718. }
  1719. Reader input(hostname);
  1720. if (idRole == IDRole::NameConstraint && input.AtEnd()) {
  1721. return true;
  1722. }
  1723. size_t dotCount = 0;
  1724. size_t labelLength = 0;
  1725. bool labelIsAllNumeric = false;
  1726. bool labelEndsWithHyphen = false;
  1727. // Only presented IDs are allowed to have wildcard labels. And, like
  1728. // Chromium, be stricter than RFC 6125 requires by insisting that a
  1729. // wildcard label consist only of '*'.
  1730. bool isWildcard = allowWildcards == AllowWildcards::Yes && input.Peek('*');
  1731. bool isFirstByte = !isWildcard;
  1732. if (isWildcard) {
  1733. Result rv = input.Skip(1);
  1734. if (rv != Success) {
  1735. assert(false);
  1736. return false;
  1737. }
  1738. uint8_t b;
  1739. rv = input.Read(b);
  1740. if (rv != Success) {
  1741. return false;
  1742. }
  1743. if (b != '.') {
  1744. return false;
  1745. }
  1746. ++dotCount;
  1747. }
  1748. do {
  1749. static const size_t MAX_LABEL_LENGTH = 63;
  1750. uint8_t b;
  1751. if (input.Read(b) != Success) {
  1752. return false;
  1753. }
  1754. switch (b) {
  1755. case '-':
  1756. if (labelLength == 0) {
  1757. return false; // Labels must not start with a hyphen.
  1758. }
  1759. labelIsAllNumeric = false;
  1760. labelEndsWithHyphen = true;
  1761. ++labelLength;
  1762. if (labelLength > MAX_LABEL_LENGTH) {
  1763. return false;
  1764. }
  1765. break;
  1766. // We avoid isdigit because it is locale-sensitive. See
  1767. // http://pubs.opengroup.org/onlinepubs/009695399/functions/isdigit.html
  1768. case '0': case '5':
  1769. case '1': case '6':
  1770. case '2': case '7':
  1771. case '3': case '8':
  1772. case '4': case '9':
  1773. if (labelLength == 0) {
  1774. labelIsAllNumeric = true;
  1775. }
  1776. labelEndsWithHyphen = false;
  1777. ++labelLength;
  1778. if (labelLength > MAX_LABEL_LENGTH) {
  1779. return false;
  1780. }
  1781. break;
  1782. // We avoid using islower/isupper/tolower/toupper or similar things, to
  1783. // avoid any possibility of this code being locale-sensitive. See
  1784. // http://pubs.opengroup.org/onlinepubs/009695399/functions/isupper.html
  1785. case 'a': case 'A': case 'n': case 'N':
  1786. case 'b': case 'B': case 'o': case 'O':
  1787. case 'c': case 'C': case 'p': case 'P':
  1788. case 'd': case 'D': case 'q': case 'Q':
  1789. case 'e': case 'E': case 'r': case 'R':
  1790. case 'f': case 'F': case 's': case 'S':
  1791. case 'g': case 'G': case 't': case 'T':
  1792. case 'h': case 'H': case 'u': case 'U':
  1793. case 'i': case 'I': case 'v': case 'V':
  1794. case 'j': case 'J': case 'w': case 'W':
  1795. case 'k': case 'K': case 'x': case 'X':
  1796. case 'l': case 'L': case 'y': case 'Y':
  1797. case 'm': case 'M': case 'z': case 'Z':
  1798. // We allow underscores for compatibility with existing practices.
  1799. // See bug 1136616.
  1800. case '_':
  1801. labelIsAllNumeric = false;
  1802. labelEndsWithHyphen = false;
  1803. ++labelLength;
  1804. if (labelLength > MAX_LABEL_LENGTH) {
  1805. return false;
  1806. }
  1807. break;
  1808. case '.':
  1809. ++dotCount;
  1810. if (labelLength == 0 &&
  1811. (idRole != IDRole::NameConstraint || !isFirstByte)) {
  1812. return false;
  1813. }
  1814. if (labelEndsWithHyphen) {
  1815. return false; // Labels must not end with a hyphen.
  1816. }
  1817. labelLength = 0;
  1818. break;
  1819. default:
  1820. return false; // Invalid character.
  1821. }
  1822. isFirstByte = false;
  1823. } while (!input.AtEnd());
  1824. // Only reference IDs, not presented IDs or name constraints, may be
  1825. // absolute.
  1826. if (labelLength == 0 && idRole != IDRole::ReferenceID) {
  1827. return false;
  1828. }
  1829. if (labelEndsWithHyphen) {
  1830. return false; // Labels must not end with a hyphen.
  1831. }
  1832. if (labelIsAllNumeric) {
  1833. return false; // Last label must not be all numeric.
  1834. }
  1835. if (isWildcard) {
  1836. // If the DNS ID ends with a dot, the last dot signifies an absolute ID.
  1837. size_t labelCount = (labelLength == 0) ? dotCount : (dotCount + 1);
  1838. // Like NSS, require at least two labels to follow the wildcard label.
  1839. //
  1840. // TODO(bug XXXXXXX): Allow the TrustDomain to control this on a
  1841. // per-eTLD+1 basis, similar to Chromium. Even then, it might be better to
  1842. // still enforce that there are at least two labels after the wildcard.
  1843. if (labelCount < 3) {
  1844. return false;
  1845. }
  1846. // XXX: RFC6125 says that we shouldn't accept wildcards within an IDN
  1847. // A-Label. The consequence of this is that we effectively discriminate
  1848. // against users of languages that cannot be encoded with ASCII.
  1849. if (StartsWithIDNALabel(hostname)) {
  1850. return false;
  1851. }
  1852. // TODO(bug XXXXXXX): Wildcards are not allowed for EV certificates.
  1853. // Provide an option to indicate whether wildcards should be matched, for
  1854. // the purpose of helping the application enforce this.
  1855. }
  1856. return true;
  1857. }
  1858. } // namespace
  1859. } } // namespace mozilla::pkix