verify.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package x509
  5. import (
  6. "bytes"
  7. "errors"
  8. "fmt"
  9. "net"
  10. "net/url"
  11. "os"
  12. "reflect"
  13. "runtime"
  14. "strings"
  15. "time"
  16. "unicode/utf8"
  17. )
  18. // ignoreCN disables interpreting Common Name as a hostname. See issue 24151.
  19. var ignoreCN = strings.Contains(os.Getenv("GODEBUG"), "x509ignoreCN=1")
  20. type InvalidReason int
  21. const (
  22. // NotAuthorizedToSign results when a certificate is signed by another
  23. // which isn't marked as a CA certificate.
  24. NotAuthorizedToSign InvalidReason = iota
  25. // Expired results when a certificate has expired, based on the time
  26. // given in the VerifyOptions.
  27. Expired
  28. // CANotAuthorizedForThisName results when an intermediate or root
  29. // certificate has a name constraint which doesn't permit a DNS or
  30. // other name (including IP address) in the leaf certificate.
  31. CANotAuthorizedForThisName
  32. // TooManyIntermediates results when a path length constraint is
  33. // violated.
  34. TooManyIntermediates
  35. // IncompatibleUsage results when the certificate's key usage indicates
  36. // that it may only be used for a different purpose.
  37. IncompatibleUsage
  38. // NameMismatch results when the subject name of a parent certificate
  39. // does not match the issuer name in the child.
  40. NameMismatch
  41. // NameConstraintsWithoutSANs results when a leaf certificate doesn't
  42. // contain a Subject Alternative Name extension, but a CA certificate
  43. // contains name constraints, and the Common Name can be interpreted as
  44. // a hostname.
  45. //
  46. // You can avoid this error by setting the experimental GODEBUG environment
  47. // variable to "x509ignoreCN=1", disabling Common Name matching entirely.
  48. // This behavior might become the default in the future.
  49. NameConstraintsWithoutSANs
  50. // UnconstrainedName results when a CA certificate contains permitted
  51. // name constraints, but leaf certificate contains a name of an
  52. // unsupported or unconstrained type.
  53. UnconstrainedName
  54. // TooManyConstraints results when the number of comparison operations
  55. // needed to check a certificate exceeds the limit set by
  56. // VerifyOptions.MaxConstraintComparisions. This limit exists to
  57. // prevent pathological certificates can consuming excessive amounts of
  58. // CPU time to verify.
  59. TooManyConstraints
  60. // CANotAuthorizedForExtKeyUsage results when an intermediate or root
  61. // certificate does not permit a requested extended key usage.
  62. CANotAuthorizedForExtKeyUsage
  63. )
  64. // CertificateInvalidError results when an odd error occurs. Users of this
  65. // library probably want to handle all these errors uniformly.
  66. type CertificateInvalidError struct {
  67. Cert *Certificate
  68. Reason InvalidReason
  69. Detail string
  70. }
  71. func (e CertificateInvalidError) Error() string {
  72. switch e.Reason {
  73. case NotAuthorizedToSign:
  74. return "x509: certificate is not authorized to sign other certificates"
  75. case Expired:
  76. return "x509: certificate has expired or is not yet valid: " + e.Detail
  77. case CANotAuthorizedForThisName:
  78. return "x509: a root or intermediate certificate is not authorized to sign for this name: " + e.Detail
  79. case CANotAuthorizedForExtKeyUsage:
  80. return "x509: a root or intermediate certificate is not authorized for an extended key usage: " + e.Detail
  81. case TooManyIntermediates:
  82. return "x509: too many intermediates for path length constraint"
  83. case IncompatibleUsage:
  84. return "x509: certificate specifies an incompatible key usage"
  85. case NameMismatch:
  86. return "x509: issuer name does not match subject from issuing certificate"
  87. case NameConstraintsWithoutSANs:
  88. return "x509: issuer has name constraints but leaf doesn't have a SAN extension"
  89. case UnconstrainedName:
  90. return "x509: issuer has name constraints but leaf contains unknown or unconstrained name: " + e.Detail
  91. }
  92. return "x509: unknown error"
  93. }
  94. // HostnameError results when the set of authorized names doesn't match the
  95. // requested name.
  96. type HostnameError struct {
  97. Certificate *Certificate
  98. Host string
  99. }
  100. func (h HostnameError) Error() string {
  101. c := h.Certificate
  102. if !c.hasSANExtension() && !validHostname(c.Subject.CommonName) &&
  103. matchHostnames(toLowerCaseASCII(c.Subject.CommonName), toLowerCaseASCII(h.Host)) {
  104. // This would have validated, if it weren't for the validHostname check on Common Name.
  105. return "x509: Common Name is not a valid hostname: " + c.Subject.CommonName
  106. }
  107. var valid string
  108. if ip := net.ParseIP(h.Host); ip != nil {
  109. // Trying to validate an IP
  110. if len(c.IPAddresses) == 0 {
  111. return "x509: cannot validate certificate for " + h.Host + " because it doesn't contain any IP SANs"
  112. }
  113. for _, san := range c.IPAddresses {
  114. if len(valid) > 0 {
  115. valid += ", "
  116. }
  117. valid += san.String()
  118. }
  119. } else {
  120. if c.commonNameAsHostname() {
  121. valid = c.Subject.CommonName
  122. } else {
  123. valid = strings.Join(c.DNSNames, ", ")
  124. }
  125. }
  126. if len(valid) == 0 {
  127. return "x509: certificate is not valid for any names, but wanted to match " + h.Host
  128. }
  129. return "x509: certificate is valid for " + valid + ", not " + h.Host
  130. }
  131. // UnknownAuthorityError results when the certificate issuer is unknown
  132. type UnknownAuthorityError struct {
  133. Cert *Certificate
  134. // hintErr contains an error that may be helpful in determining why an
  135. // authority wasn't found.
  136. hintErr error
  137. // hintCert contains a possible authority certificate that was rejected
  138. // because of the error in hintErr.
  139. hintCert *Certificate
  140. }
  141. func (e UnknownAuthorityError) Error() string {
  142. s := "x509: certificate signed by unknown authority"
  143. if e.hintErr != nil {
  144. certName := e.hintCert.Subject.CommonName
  145. if len(certName) == 0 {
  146. if len(e.hintCert.Subject.Organization) > 0 {
  147. certName = e.hintCert.Subject.Organization[0]
  148. } else {
  149. certName = "serial:" + e.hintCert.SerialNumber.String()
  150. }
  151. }
  152. s += fmt.Sprintf(" (possibly because of %q while trying to verify candidate authority certificate %q)", e.hintErr, certName)
  153. }
  154. return s
  155. }
  156. // SystemRootsError results when we fail to load the system root certificates.
  157. type SystemRootsError struct {
  158. Err error
  159. }
  160. func (se SystemRootsError) Error() string {
  161. msg := "x509: failed to load system roots and no roots provided"
  162. if se.Err != nil {
  163. return msg + "; " + se.Err.Error()
  164. }
  165. return msg
  166. }
  167. // errNotParsed is returned when a certificate without ASN.1 contents is
  168. // verified. Platform-specific verification needs the ASN.1 contents.
  169. var errNotParsed = errors.New("x509: missing ASN.1 contents; use ParseCertificate")
  170. // VerifyOptions contains parameters for Certificate.Verify. It's a structure
  171. // because other PKIX verification APIs have ended up needing many options.
  172. type VerifyOptions struct {
  173. DNSName string
  174. Intermediates *CertPool
  175. Roots *CertPool // if nil, the system roots are used
  176. CurrentTime time.Time // if zero, the current time is used
  177. // Options to disable various verification checks.
  178. DisableTimeChecks bool
  179. DisableCriticalExtensionChecks bool
  180. DisableNameChecks bool
  181. DisableEKUChecks bool
  182. DisablePathLenChecks bool
  183. DisableNameConstraintChecks bool
  184. // KeyUsage specifies which Extended Key Usage values are acceptable. A leaf
  185. // certificate is accepted if it contains any of the listed values. An empty
  186. // list means ExtKeyUsageServerAuth. To accept any key usage, include
  187. // ExtKeyUsageAny.
  188. //
  189. // Certificate chains are required to nest these extended key usage values.
  190. // (This matches the Windows CryptoAPI behavior, but not the spec.)
  191. KeyUsages []ExtKeyUsage
  192. // MaxConstraintComparisions is the maximum number of comparisons to
  193. // perform when checking a given certificate's name constraints. If
  194. // zero, a sensible default is used. This limit prevents pathological
  195. // certificates from consuming excessive amounts of CPU time when
  196. // validating.
  197. MaxConstraintComparisions int
  198. }
  199. const (
  200. leafCertificate = iota
  201. intermediateCertificate
  202. rootCertificate
  203. )
  204. // rfc2821Mailbox represents a “mailbox” (which is an email address to most
  205. // people) by breaking it into the “local” (i.e. before the '@') and “domain”
  206. // parts.
  207. type rfc2821Mailbox struct {
  208. local, domain string
  209. }
  210. // parseRFC2821Mailbox parses an email address into local and domain parts,
  211. // based on the ABNF for a “Mailbox” from RFC 2821. According to RFC 5280,
  212. // Section 4.2.1.6 that's correct for an rfc822Name from a certificate: “The
  213. // format of an rfc822Name is a "Mailbox" as defined in RFC 2821, Section 4.1.2”.
  214. func parseRFC2821Mailbox(in string) (mailbox rfc2821Mailbox, ok bool) {
  215. if len(in) == 0 {
  216. return mailbox, false
  217. }
  218. localPartBytes := make([]byte, 0, len(in)/2)
  219. if in[0] == '"' {
  220. // Quoted-string = DQUOTE *qcontent DQUOTE
  221. // non-whitespace-control = %d1-8 / %d11 / %d12 / %d14-31 / %d127
  222. // qcontent = qtext / quoted-pair
  223. // qtext = non-whitespace-control /
  224. // %d33 / %d35-91 / %d93-126
  225. // quoted-pair = ("\" text) / obs-qp
  226. // text = %d1-9 / %d11 / %d12 / %d14-127 / obs-text
  227. //
  228. // (Names beginning with “obs-” are the obsolete syntax from RFC 2822,
  229. // Section 4. Since it has been 16 years, we no longer accept that.)
  230. in = in[1:]
  231. QuotedString:
  232. for {
  233. if len(in) == 0 {
  234. return mailbox, false
  235. }
  236. c := in[0]
  237. in = in[1:]
  238. switch {
  239. case c == '"':
  240. break QuotedString
  241. case c == '\\':
  242. // quoted-pair
  243. if len(in) == 0 {
  244. return mailbox, false
  245. }
  246. if in[0] == 11 ||
  247. in[0] == 12 ||
  248. (1 <= in[0] && in[0] <= 9) ||
  249. (14 <= in[0] && in[0] <= 127) {
  250. localPartBytes = append(localPartBytes, in[0])
  251. in = in[1:]
  252. } else {
  253. return mailbox, false
  254. }
  255. case c == 11 ||
  256. c == 12 ||
  257. // Space (char 32) is not allowed based on the
  258. // BNF, but RFC 3696 gives an example that
  259. // assumes that it is. Several “verified”
  260. // errata continue to argue about this point.
  261. // We choose to accept it.
  262. c == 32 ||
  263. c == 33 ||
  264. c == 127 ||
  265. (1 <= c && c <= 8) ||
  266. (14 <= c && c <= 31) ||
  267. (35 <= c && c <= 91) ||
  268. (93 <= c && c <= 126):
  269. // qtext
  270. localPartBytes = append(localPartBytes, c)
  271. default:
  272. return mailbox, false
  273. }
  274. }
  275. } else {
  276. // Atom ("." Atom)*
  277. NextChar:
  278. for len(in) > 0 {
  279. // atext from RFC 2822, Section 3.2.4
  280. c := in[0]
  281. switch {
  282. case c == '\\':
  283. // Examples given in RFC 3696 suggest that
  284. // escaped characters can appear outside of a
  285. // quoted string. Several “verified” errata
  286. // continue to argue the point. We choose to
  287. // accept it.
  288. in = in[1:]
  289. if len(in) == 0 {
  290. return mailbox, false
  291. }
  292. fallthrough
  293. case ('0' <= c && c <= '9') ||
  294. ('a' <= c && c <= 'z') ||
  295. ('A' <= c && c <= 'Z') ||
  296. c == '!' || c == '#' || c == '$' || c == '%' ||
  297. c == '&' || c == '\'' || c == '*' || c == '+' ||
  298. c == '-' || c == '/' || c == '=' || c == '?' ||
  299. c == '^' || c == '_' || c == '`' || c == '{' ||
  300. c == '|' || c == '}' || c == '~' || c == '.':
  301. localPartBytes = append(localPartBytes, in[0])
  302. in = in[1:]
  303. default:
  304. break NextChar
  305. }
  306. }
  307. if len(localPartBytes) == 0 {
  308. return mailbox, false
  309. }
  310. // From RFC 3696, Section 3:
  311. // “period (".") may also appear, but may not be used to start
  312. // or end the local part, nor may two or more consecutive
  313. // periods appear.”
  314. twoDots := []byte{'.', '.'}
  315. if localPartBytes[0] == '.' ||
  316. localPartBytes[len(localPartBytes)-1] == '.' ||
  317. bytes.Contains(localPartBytes, twoDots) {
  318. return mailbox, false
  319. }
  320. }
  321. if len(in) == 0 || in[0] != '@' {
  322. return mailbox, false
  323. }
  324. in = in[1:]
  325. // The RFC species a format for domains, but that's known to be
  326. // violated in practice so we accept that anything after an '@' is the
  327. // domain part.
  328. if _, ok := domainToReverseLabels(in); !ok {
  329. return mailbox, false
  330. }
  331. mailbox.local = string(localPartBytes)
  332. mailbox.domain = in
  333. return mailbox, true
  334. }
  335. // domainToReverseLabels converts a textual domain name like foo.example.com to
  336. // the list of labels in reverse order, e.g. ["com", "example", "foo"].
  337. func domainToReverseLabels(domain string) (reverseLabels []string, ok bool) {
  338. for len(domain) > 0 {
  339. if i := strings.LastIndexByte(domain, '.'); i == -1 {
  340. reverseLabels = append(reverseLabels, domain)
  341. domain = ""
  342. } else {
  343. reverseLabels = append(reverseLabels, domain[i+1:])
  344. domain = domain[:i]
  345. }
  346. }
  347. if len(reverseLabels) > 0 && len(reverseLabels[0]) == 0 {
  348. // An empty label at the end indicates an absolute value.
  349. return nil, false
  350. }
  351. for _, label := range reverseLabels {
  352. if len(label) == 0 {
  353. // Empty labels are otherwise invalid.
  354. return nil, false
  355. }
  356. for _, c := range label {
  357. if c < 33 || c > 126 {
  358. // Invalid character.
  359. return nil, false
  360. }
  361. }
  362. }
  363. return reverseLabels, true
  364. }
  365. func matchEmailConstraint(mailbox rfc2821Mailbox, constraint string) (bool, error) {
  366. // If the constraint contains an @, then it specifies an exact mailbox
  367. // name.
  368. if strings.Contains(constraint, "@") {
  369. constraintMailbox, ok := parseRFC2821Mailbox(constraint)
  370. if !ok {
  371. return false, fmt.Errorf("x509: internal error: cannot parse constraint %q", constraint)
  372. }
  373. return mailbox.local == constraintMailbox.local && strings.EqualFold(mailbox.domain, constraintMailbox.domain), nil
  374. }
  375. // Otherwise the constraint is like a DNS constraint of the domain part
  376. // of the mailbox.
  377. return matchDomainConstraint(mailbox.domain, constraint)
  378. }
  379. func matchURIConstraint(uri *url.URL, constraint string) (bool, error) {
  380. // From RFC 5280, Section 4.2.1.10:
  381. // “a uniformResourceIdentifier that does not include an authority
  382. // component with a host name specified as a fully qualified domain
  383. // name (e.g., if the URI either does not include an authority
  384. // component or includes an authority component in which the host name
  385. // is specified as an IP address), then the application MUST reject the
  386. // certificate.”
  387. host := uri.Host
  388. if len(host) == 0 {
  389. return false, fmt.Errorf("URI with empty host (%q) cannot be matched against constraints", uri.String())
  390. }
  391. if strings.Contains(host, ":") && !strings.HasSuffix(host, "]") {
  392. var err error
  393. host, _, err = net.SplitHostPort(uri.Host)
  394. if err != nil {
  395. return false, err
  396. }
  397. }
  398. if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") ||
  399. net.ParseIP(host) != nil {
  400. return false, fmt.Errorf("URI with IP (%q) cannot be matched against constraints", uri.String())
  401. }
  402. return matchDomainConstraint(host, constraint)
  403. }
  404. func matchIPConstraint(ip net.IP, constraint *net.IPNet) (bool, error) {
  405. if len(ip) != len(constraint.IP) {
  406. return false, nil
  407. }
  408. for i := range ip {
  409. if mask := constraint.Mask[i]; ip[i]&mask != constraint.IP[i]&mask {
  410. return false, nil
  411. }
  412. }
  413. return true, nil
  414. }
  415. func matchDomainConstraint(domain, constraint string) (bool, error) {
  416. // The meaning of zero length constraints is not specified, but this
  417. // code follows NSS and accepts them as matching everything.
  418. if len(constraint) == 0 {
  419. return true, nil
  420. }
  421. domainLabels, ok := domainToReverseLabels(domain)
  422. if !ok {
  423. return false, fmt.Errorf("x509: internal error: cannot parse domain %q", domain)
  424. }
  425. // RFC 5280 says that a leading period in a domain name means that at
  426. // least one label must be prepended, but only for URI and email
  427. // constraints, not DNS constraints. The code also supports that
  428. // behaviour for DNS constraints.
  429. mustHaveSubdomains := false
  430. if constraint[0] == '.' {
  431. mustHaveSubdomains = true
  432. constraint = constraint[1:]
  433. }
  434. constraintLabels, ok := domainToReverseLabels(constraint)
  435. if !ok {
  436. return false, fmt.Errorf("x509: internal error: cannot parse domain %q", constraint)
  437. }
  438. if len(domainLabels) < len(constraintLabels) ||
  439. (mustHaveSubdomains && len(domainLabels) == len(constraintLabels)) {
  440. return false, nil
  441. }
  442. for i, constraintLabel := range constraintLabels {
  443. if !strings.EqualFold(constraintLabel, domainLabels[i]) {
  444. return false, nil
  445. }
  446. }
  447. return true, nil
  448. }
  449. // checkNameConstraints checks that c permits a child certificate to claim the
  450. // given name, of type nameType. The argument parsedName contains the parsed
  451. // form of name, suitable for passing to the match function. The total number
  452. // of comparisons is tracked in the given count and should not exceed the given
  453. // limit.
  454. func (c *Certificate) checkNameConstraints(count *int,
  455. maxConstraintComparisons int,
  456. nameType string,
  457. name string,
  458. parsedName interface{},
  459. match func(parsedName, constraint interface{}) (match bool, err error),
  460. permitted, excluded interface{}) error {
  461. excludedValue := reflect.ValueOf(excluded)
  462. *count += excludedValue.Len()
  463. if *count > maxConstraintComparisons {
  464. return CertificateInvalidError{c, TooManyConstraints, ""}
  465. }
  466. for i := 0; i < excludedValue.Len(); i++ {
  467. constraint := excludedValue.Index(i).Interface()
  468. match, err := match(parsedName, constraint)
  469. if err != nil {
  470. return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
  471. }
  472. if match {
  473. return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is excluded by constraint %q", nameType, name, constraint)}
  474. }
  475. }
  476. permittedValue := reflect.ValueOf(permitted)
  477. *count += permittedValue.Len()
  478. if *count > maxConstraintComparisons {
  479. return CertificateInvalidError{c, TooManyConstraints, ""}
  480. }
  481. ok := true
  482. for i := 0; i < permittedValue.Len(); i++ {
  483. constraint := permittedValue.Index(i).Interface()
  484. var err error
  485. if ok, err = match(parsedName, constraint); err != nil {
  486. return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
  487. }
  488. if ok {
  489. break
  490. }
  491. }
  492. if !ok {
  493. return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is not permitted by any constraint", nameType, name)}
  494. }
  495. return nil
  496. }
  497. // isValid performs validity checks on c given that it is a candidate to append
  498. // to the chain in currentChain.
  499. func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error {
  500. if !opts.DisableCriticalExtensionChecks && len(c.UnhandledCriticalExtensions) > 0 {
  501. return UnhandledCriticalExtension{ID: c.UnhandledCriticalExtensions[0]}
  502. }
  503. if !opts.DisableNameChecks && len(currentChain) > 0 {
  504. child := currentChain[len(currentChain)-1]
  505. if !bytes.Equal(child.RawIssuer, c.RawSubject) {
  506. return CertificateInvalidError{c, NameMismatch, ""}
  507. }
  508. }
  509. if !opts.DisableTimeChecks {
  510. now := opts.CurrentTime
  511. if now.IsZero() {
  512. now = time.Now()
  513. }
  514. if now.Before(c.NotBefore) {
  515. return CertificateInvalidError{
  516. Cert: c,
  517. Reason: Expired,
  518. Detail: fmt.Sprintf("current time %s is before %s", now.Format(time.RFC3339), c.NotBefore.Format(time.RFC3339)),
  519. }
  520. } else if now.After(c.NotAfter) {
  521. return CertificateInvalidError{
  522. Cert: c,
  523. Reason: Expired,
  524. Detail: fmt.Sprintf("current time %s is after %s", now.Format(time.RFC3339), c.NotAfter.Format(time.RFC3339)),
  525. }
  526. }
  527. }
  528. maxConstraintComparisons := opts.MaxConstraintComparisions
  529. if maxConstraintComparisons == 0 {
  530. maxConstraintComparisons = 250000
  531. }
  532. comparisonCount := 0
  533. var leaf *Certificate
  534. if certType == intermediateCertificate || certType == rootCertificate {
  535. if len(currentChain) == 0 {
  536. return errors.New("x509: internal error: empty chain when appending CA cert")
  537. }
  538. leaf = currentChain[0]
  539. }
  540. checkNameConstraints := !opts.DisableNameConstraintChecks && (certType == intermediateCertificate || certType == rootCertificate) && c.hasNameConstraints()
  541. if checkNameConstraints && leaf.commonNameAsHostname() {
  542. // This is the deprecated, legacy case of depending on the commonName as
  543. // a hostname. We don't enforce name constraints against the CN, but
  544. // VerifyHostname will look for hostnames in there if there are no SANs.
  545. // In order to ensure VerifyHostname will not accept an unchecked name,
  546. // return an error here.
  547. return CertificateInvalidError{c, NameConstraintsWithoutSANs, ""}
  548. } else if checkNameConstraints && leaf.hasSANExtension() {
  549. err := forEachSAN(leaf.getSANExtension(), func(tag int, data []byte) error {
  550. switch tag {
  551. case nameTypeEmail:
  552. name := string(data)
  553. mailbox, ok := parseRFC2821Mailbox(name)
  554. if !ok {
  555. return fmt.Errorf("x509: cannot parse rfc822Name %q", mailbox)
  556. }
  557. if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "email address", name, mailbox,
  558. func(parsedName, constraint interface{}) (bool, error) {
  559. return matchEmailConstraint(parsedName.(rfc2821Mailbox), constraint.(string))
  560. }, c.PermittedEmailAddresses, c.ExcludedEmailAddresses); err != nil {
  561. return err
  562. }
  563. case nameTypeDNS:
  564. name := string(data)
  565. if _, ok := domainToReverseLabels(name); !ok {
  566. return fmt.Errorf("x509: cannot parse dnsName %q", name)
  567. }
  568. if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "DNS name", name, name,
  569. func(parsedName, constraint interface{}) (bool, error) {
  570. return matchDomainConstraint(parsedName.(string), constraint.(string))
  571. }, c.PermittedDNSDomains, c.ExcludedDNSDomains); err != nil {
  572. return err
  573. }
  574. case nameTypeURI:
  575. name := string(data)
  576. uri, err := url.Parse(name)
  577. if err != nil {
  578. return fmt.Errorf("x509: internal error: URI SAN %q failed to parse", name)
  579. }
  580. if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "URI", name, uri,
  581. func(parsedName, constraint interface{}) (bool, error) {
  582. return matchURIConstraint(parsedName.(*url.URL), constraint.(string))
  583. }, c.PermittedURIDomains, c.ExcludedURIDomains); err != nil {
  584. return err
  585. }
  586. case nameTypeIP:
  587. ip := net.IP(data)
  588. if l := len(ip); l != net.IPv4len && l != net.IPv6len {
  589. return fmt.Errorf("x509: internal error: IP SAN %x failed to parse", data)
  590. }
  591. if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "IP address", ip.String(), ip,
  592. func(parsedName, constraint interface{}) (bool, error) {
  593. return matchIPConstraint(parsedName.(net.IP), constraint.(*net.IPNet))
  594. }, c.PermittedIPRanges, c.ExcludedIPRanges); err != nil {
  595. return err
  596. }
  597. default:
  598. // Unknown SAN types are ignored.
  599. }
  600. return nil
  601. })
  602. if err != nil {
  603. return err
  604. }
  605. }
  606. // KeyUsage status flags are ignored. From Engineering Security, Peter
  607. // Gutmann: A European government CA marked its signing certificates as
  608. // being valid for encryption only, but no-one noticed. Another
  609. // European CA marked its signature keys as not being valid for
  610. // signatures. A different CA marked its own trusted root certificate
  611. // as being invalid for certificate signing. Another national CA
  612. // distributed a certificate to be used to encrypt data for the
  613. // country’s tax authority that was marked as only being usable for
  614. // digital signatures but not for encryption. Yet another CA reversed
  615. // the order of the bit flags in the keyUsage due to confusion over
  616. // encoding endianness, essentially setting a random keyUsage in
  617. // certificates that it issued. Another CA created a self-invalidating
  618. // certificate by adding a certificate policy statement stipulating
  619. // that the certificate had to be used strictly as specified in the
  620. // keyUsage, and a keyUsage containing a flag indicating that the RSA
  621. // encryption key could only be used for Diffie-Hellman key agreement.
  622. if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) {
  623. return CertificateInvalidError{c, NotAuthorizedToSign, ""}
  624. }
  625. if !opts.DisablePathLenChecks && c.BasicConstraintsValid && c.MaxPathLen >= 0 {
  626. numIntermediates := len(currentChain) - 1
  627. if numIntermediates > c.MaxPathLen {
  628. return CertificateInvalidError{c, TooManyIntermediates, ""}
  629. }
  630. }
  631. return nil
  632. }
  633. // Verify attempts to verify c by building one or more chains from c to a
  634. // certificate in opts.Roots, using certificates in opts.Intermediates if
  635. // needed. If successful, it returns one or more chains where the first
  636. // element of the chain is c and the last element is from opts.Roots.
  637. //
  638. // If opts.Roots is nil and system roots are unavailable the returned error
  639. // will be of type SystemRootsError.
  640. //
  641. // Name constraints in the intermediates will be applied to all names claimed
  642. // in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim
  643. // example.com if an intermediate doesn't permit it, even if example.com is not
  644. // the name being validated. Note that DirectoryName constraints are not
  645. // supported.
  646. //
  647. // Extended Key Usage values are enforced down a chain, so an intermediate or
  648. // root that enumerates EKUs prevents a leaf from asserting an EKU not in that
  649. // list.
  650. //
  651. // WARNING: this function doesn't do any revocation checking.
  652. func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error) {
  653. // Platform-specific verification needs the ASN.1 contents so
  654. // this makes the behavior consistent across platforms.
  655. if len(c.Raw) == 0 {
  656. return nil, errNotParsed
  657. }
  658. if opts.Intermediates != nil {
  659. for _, intermediate := range opts.Intermediates.certs {
  660. if len(intermediate.Raw) == 0 {
  661. return nil, errNotParsed
  662. }
  663. }
  664. }
  665. // Use Windows's own verification and chain building.
  666. if opts.Roots == nil && runtime.GOOS == "windows" {
  667. return c.systemVerify(&opts)
  668. }
  669. if opts.Roots == nil {
  670. opts.Roots = systemRootsPool()
  671. if opts.Roots == nil {
  672. return nil, SystemRootsError{systemRootsErr}
  673. }
  674. }
  675. err = c.isValid(leafCertificate, nil, &opts)
  676. if err != nil {
  677. return
  678. }
  679. if len(opts.DNSName) > 0 {
  680. err = c.VerifyHostname(opts.DNSName)
  681. if err != nil {
  682. return
  683. }
  684. }
  685. var candidateChains [][]*Certificate
  686. if opts.Roots.contains(c) {
  687. candidateChains = append(candidateChains, []*Certificate{c})
  688. } else {
  689. if candidateChains, err = c.buildChains(nil, []*Certificate{c}, nil, &opts); err != nil {
  690. return nil, err
  691. }
  692. }
  693. keyUsages := opts.KeyUsages
  694. if len(keyUsages) == 0 {
  695. keyUsages = []ExtKeyUsage{ExtKeyUsageServerAuth}
  696. }
  697. // If any key usage is acceptable then we're done.
  698. for _, usage := range keyUsages {
  699. if usage == ExtKeyUsageAny {
  700. return candidateChains, nil
  701. }
  702. }
  703. for _, candidate := range candidateChains {
  704. if opts.DisableEKUChecks || checkChainForKeyUsage(candidate, keyUsages) {
  705. chains = append(chains, candidate)
  706. }
  707. }
  708. if len(chains) == 0 {
  709. return nil, CertificateInvalidError{c, IncompatibleUsage, ""}
  710. }
  711. return chains, nil
  712. }
  713. func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate {
  714. n := make([]*Certificate, len(chain)+1)
  715. copy(n, chain)
  716. n[len(chain)] = cert
  717. return n
  718. }
  719. // maxChainSignatureChecks is the maximum number of CheckSignatureFrom calls
  720. // that an invocation of buildChains will (tranistively) make. Most chains are
  721. // less than 15 certificates long, so this leaves space for multiple chains and
  722. // for failed checks due to different intermediates having the same Subject.
  723. const maxChainSignatureChecks = 100
  724. func (c *Certificate) buildChains(cache map[*Certificate][][]*Certificate, currentChain []*Certificate, sigChecks *int, opts *VerifyOptions) (chains [][]*Certificate, err error) {
  725. var (
  726. hintErr error
  727. hintCert *Certificate
  728. )
  729. considerCandidate := func(certType int, candidate *Certificate) {
  730. for _, cert := range currentChain {
  731. if cert.Equal(candidate) {
  732. return
  733. }
  734. }
  735. if sigChecks == nil {
  736. sigChecks = new(int)
  737. }
  738. *sigChecks++
  739. if *sigChecks > maxChainSignatureChecks {
  740. err = errors.New("x509: signature check attempts limit reached while verifying certificate chain")
  741. return
  742. }
  743. if err := c.CheckSignatureFrom(candidate); err != nil {
  744. if hintErr == nil {
  745. hintErr = err
  746. hintCert = candidate
  747. }
  748. return
  749. }
  750. err = candidate.isValid(certType, currentChain, opts)
  751. if err != nil {
  752. return
  753. }
  754. switch certType {
  755. case rootCertificate:
  756. chains = append(chains, appendToFreshChain(currentChain, candidate))
  757. case intermediateCertificate:
  758. if cache == nil {
  759. cache = make(map[*Certificate][][]*Certificate)
  760. }
  761. childChains, ok := cache[candidate]
  762. if !ok {
  763. childChains, err = candidate.buildChains(cache, appendToFreshChain(currentChain, candidate), sigChecks, opts)
  764. cache[candidate] = childChains
  765. }
  766. chains = append(chains, childChains...)
  767. }
  768. }
  769. for _, rootNum := range opts.Roots.findPotentialParents(c) {
  770. considerCandidate(rootCertificate, opts.Roots.certs[rootNum])
  771. }
  772. for _, intermediateNum := range opts.Intermediates.findPotentialParents(c) {
  773. considerCandidate(intermediateCertificate, opts.Intermediates.certs[intermediateNum])
  774. }
  775. if len(chains) > 0 {
  776. err = nil
  777. }
  778. if len(chains) == 0 && err == nil {
  779. err = UnknownAuthorityError{c, hintErr, hintCert}
  780. }
  781. return
  782. }
  783. // validHostname reports whether host is a valid hostname that can be matched or
  784. // matched against according to RFC 6125 2.2, with some leniency to accommodate
  785. // legacy values.
  786. func validHostname(host string) bool {
  787. host = strings.TrimSuffix(host, ".")
  788. if len(host) == 0 {
  789. return false
  790. }
  791. for i, part := range strings.Split(host, ".") {
  792. if part == "" {
  793. // Empty label.
  794. return false
  795. }
  796. if i == 0 && part == "*" {
  797. // Only allow full left-most wildcards, as those are the only ones
  798. // we match, and matching literal '*' characters is probably never
  799. // the expected behavior.
  800. continue
  801. }
  802. for j, c := range part {
  803. if 'a' <= c && c <= 'z' {
  804. continue
  805. }
  806. if '0' <= c && c <= '9' {
  807. continue
  808. }
  809. if 'A' <= c && c <= 'Z' {
  810. continue
  811. }
  812. if c == '-' && j != 0 {
  813. continue
  814. }
  815. if c == '_' || c == ':' {
  816. // Not valid characters in hostnames, but commonly
  817. // found in deployments outside the WebPKI.
  818. continue
  819. }
  820. return false
  821. }
  822. }
  823. return true
  824. }
  825. // commonNameAsHostname reports whether the Common Name field should be
  826. // considered the hostname that the certificate is valid for. This is a legacy
  827. // behavior, disabled if the Subject Alt Name extension is present.
  828. //
  829. // It applies the strict validHostname check to the Common Name field, so that
  830. // certificates without SANs can still be validated against CAs with name
  831. // constraints if there is no risk the CN would be matched as a hostname.
  832. // See NameConstraintsWithoutSANs and issue 24151.
  833. func (c *Certificate) commonNameAsHostname() bool {
  834. return !ignoreCN && !c.hasSANExtension() && validHostname(c.Subject.CommonName)
  835. }
  836. func matchHostnames(pattern, host string) bool {
  837. host = strings.TrimSuffix(host, ".")
  838. pattern = strings.TrimSuffix(pattern, ".")
  839. if len(pattern) == 0 || len(host) == 0 {
  840. return false
  841. }
  842. patternParts := strings.Split(pattern, ".")
  843. hostParts := strings.Split(host, ".")
  844. if len(patternParts) != len(hostParts) {
  845. return false
  846. }
  847. for i, patternPart := range patternParts {
  848. if i == 0 && patternPart == "*" {
  849. continue
  850. }
  851. if patternPart != hostParts[i] {
  852. return false
  853. }
  854. }
  855. return true
  856. }
  857. // toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use
  858. // an explicitly ASCII function to avoid any sharp corners resulting from
  859. // performing Unicode operations on DNS labels.
  860. func toLowerCaseASCII(in string) string {
  861. // If the string is already lower-case then there's nothing to do.
  862. isAlreadyLowerCase := true
  863. for _, c := range in {
  864. if c == utf8.RuneError {
  865. // If we get a UTF-8 error then there might be
  866. // upper-case ASCII bytes in the invalid sequence.
  867. isAlreadyLowerCase = false
  868. break
  869. }
  870. if 'A' <= c && c <= 'Z' {
  871. isAlreadyLowerCase = false
  872. break
  873. }
  874. }
  875. if isAlreadyLowerCase {
  876. return in
  877. }
  878. out := []byte(in)
  879. for i, c := range out {
  880. if 'A' <= c && c <= 'Z' {
  881. out[i] += 'a' - 'A'
  882. }
  883. }
  884. return string(out)
  885. }
  886. // VerifyHostname returns nil if c is a valid certificate for the named host.
  887. // Otherwise it returns an error describing the mismatch.
  888. func (c *Certificate) VerifyHostname(h string) error {
  889. // IP addresses may be written in [ ].
  890. candidateIP := h
  891. if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' {
  892. candidateIP = h[1 : len(h)-1]
  893. }
  894. if ip := net.ParseIP(candidateIP); ip != nil {
  895. // We only match IP addresses against IP SANs.
  896. // See RFC 6125, Appendix B.2.
  897. for _, candidate := range c.IPAddresses {
  898. if ip.Equal(candidate) {
  899. return nil
  900. }
  901. }
  902. return HostnameError{c, candidateIP}
  903. }
  904. lowered := toLowerCaseASCII(h)
  905. if c.commonNameAsHostname() {
  906. if matchHostnames(toLowerCaseASCII(c.Subject.CommonName), lowered) {
  907. return nil
  908. }
  909. } else {
  910. for _, match := range c.DNSNames {
  911. if matchHostnames(toLowerCaseASCII(match), lowered) {
  912. return nil
  913. }
  914. }
  915. }
  916. return HostnameError{c, h}
  917. }
  918. func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool {
  919. usages := make([]ExtKeyUsage, len(keyUsages))
  920. copy(usages, keyUsages)
  921. if len(chain) == 0 {
  922. return false
  923. }
  924. usagesRemaining := len(usages)
  925. // We walk down the list and cross out any usages that aren't supported
  926. // by each certificate. If we cross out all the usages, then the chain
  927. // is unacceptable.
  928. NextCert:
  929. for i := len(chain) - 1; i >= 0; i-- {
  930. cert := chain[i]
  931. if len(cert.ExtKeyUsage) == 0 && len(cert.UnknownExtKeyUsage) == 0 {
  932. // The certificate doesn't have any extended key usage specified.
  933. continue
  934. }
  935. for _, usage := range cert.ExtKeyUsage {
  936. if usage == ExtKeyUsageAny {
  937. // The certificate is explicitly good for any usage.
  938. continue NextCert
  939. }
  940. }
  941. const invalidUsage ExtKeyUsage = -1
  942. NextRequestedUsage:
  943. for i, requestedUsage := range usages {
  944. if requestedUsage == invalidUsage {
  945. continue
  946. }
  947. for _, usage := range cert.ExtKeyUsage {
  948. if requestedUsage == usage {
  949. continue NextRequestedUsage
  950. } else if requestedUsage == ExtKeyUsageServerAuth &&
  951. (usage == ExtKeyUsageNetscapeServerGatedCrypto ||
  952. usage == ExtKeyUsageMicrosoftServerGatedCrypto) {
  953. // In order to support COMODO
  954. // certificate chains, we have to
  955. // accept Netscape or Microsoft SGC
  956. // usages as equal to ServerAuth.
  957. continue NextRequestedUsage
  958. }
  959. }
  960. usages[i] = invalidUsage
  961. usagesRemaining--
  962. if usagesRemaining == 0 {
  963. return false
  964. }
  965. }
  966. }
  967. return true
  968. }