verify.go 32 KB

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