1
0

verify.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. /*
  2. Copyright Suzhou Tongji Fintech Research Institute 2017 All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package sm2
  14. import (
  15. "bytes"
  16. "errors"
  17. "fmt"
  18. "net"
  19. "runtime"
  20. "strings"
  21. "time"
  22. "unicode/utf8"
  23. )
  24. type InvalidReason int
  25. const (
  26. // NotAuthorizedToSign results when a certificate is signed by another
  27. // which isn't marked as a CA certificate.
  28. NotAuthorizedToSign InvalidReason = iota
  29. // Expired results when a certificate has expired, based on the time
  30. // given in the VerifyOptions.
  31. Expired
  32. // CANotAuthorizedForThisName results when an intermediate or root
  33. // certificate has a name constraint which doesn't include the name
  34. // being checked.
  35. CANotAuthorizedForThisName
  36. // TooManyIntermediates results when a path length constraint is
  37. // violated.
  38. TooManyIntermediates
  39. // IncompatibleUsage results when the certificate's key usage indicates
  40. // that it may only be used for a different purpose.
  41. IncompatibleUsage
  42. // NameMismatch results when the subject name of a parent certificate
  43. // does not match the issuer name in the child.
  44. NameMismatch
  45. )
  46. // CertificateInvalidError results when an odd error occurs. Users of this
  47. // library probably want to handle all these errors uniformly.
  48. type CertificateInvalidError struct {
  49. Cert *Certificate
  50. Reason InvalidReason
  51. }
  52. func (e CertificateInvalidError) Error() string {
  53. switch e.Reason {
  54. case NotAuthorizedToSign:
  55. return "x509: certificate is not authorized to sign other certificates"
  56. case Expired:
  57. return "x509: certificate has expired or is not yet valid"
  58. case CANotAuthorizedForThisName:
  59. return "x509: a root or intermediate certificate is not authorized to sign in this domain"
  60. case TooManyIntermediates:
  61. return "x509: too many intermediates for path length constraint"
  62. case IncompatibleUsage:
  63. return "x509: certificate specifies an incompatible key usage"
  64. case NameMismatch:
  65. return "x509: issuer name does not match subject from issuing certificate"
  66. }
  67. return "x509: unknown error"
  68. }
  69. // HostnameError results when the set of authorized names doesn't match the
  70. // requested name.
  71. type HostnameError struct {
  72. Certificate *Certificate
  73. Host string
  74. }
  75. func (h HostnameError) Error() string {
  76. c := h.Certificate
  77. var valid string
  78. if ip := net.ParseIP(h.Host); ip != nil {
  79. // Trying to validate an IP
  80. if len(c.IPAddresses) == 0 {
  81. return "x509: cannot validate certificate for " + h.Host + " because it doesn't contain any IP SANs"
  82. }
  83. for _, san := range c.IPAddresses {
  84. if len(valid) > 0 {
  85. valid += ", "
  86. }
  87. valid += san.String()
  88. }
  89. } else {
  90. if len(c.DNSNames) > 0 {
  91. valid = strings.Join(c.DNSNames, ", ")
  92. } else {
  93. valid = c.Subject.CommonName
  94. }
  95. }
  96. if len(valid) == 0 {
  97. return "x509: certificate is not valid for any names, but wanted to match " + h.Host
  98. }
  99. return "x509: certificate is valid for " + valid + ", not " + h.Host
  100. }
  101. // UnknownAuthorityError results when the certificate issuer is unknown
  102. type UnknownAuthorityError struct {
  103. Cert *Certificate
  104. // hintErr contains an error that may be helpful in determining why an
  105. // authority wasn't found.
  106. hintErr error
  107. // hintCert contains a possible authority certificate that was rejected
  108. // because of the error in hintErr.
  109. hintCert *Certificate
  110. }
  111. func (e UnknownAuthorityError) Error() string {
  112. s := "x509: certificate signed by unknown authority"
  113. if e.hintErr != nil {
  114. certName := e.hintCert.Subject.CommonName
  115. if len(certName) == 0 {
  116. if len(e.hintCert.Subject.Organization) > 0 {
  117. certName = e.hintCert.Subject.Organization[0]
  118. } else {
  119. certName = "serial:" + e.hintCert.SerialNumber.String()
  120. }
  121. }
  122. s += fmt.Sprintf(" (possibly because of %q while trying to verify candidate authority certificate %q)", e.hintErr, certName)
  123. }
  124. return s
  125. }
  126. // SystemRootsError results when we fail to load the system root certificates.
  127. type SystemRootsError struct {
  128. Err error
  129. }
  130. func (se SystemRootsError) Error() string {
  131. msg := "x509: failed to load system roots and no roots provided"
  132. if se.Err != nil {
  133. return msg + "; " + se.Err.Error()
  134. }
  135. return msg
  136. }
  137. // errNotParsed is returned when a certificate without ASN.1 contents is
  138. // verified. Platform-specific verification needs the ASN.1 contents.
  139. var errNotParsed = errors.New("x509: missing ASN.1 contents; use ParseCertificate")
  140. // VerifyOptions contains parameters for Certificate.Verify. It's a structure
  141. // because other PKIX verification APIs have ended up needing many options.
  142. type VerifyOptions struct {
  143. DNSName string
  144. Intermediates *CertPool
  145. Roots *CertPool // if nil, the system roots are used
  146. CurrentTime time.Time // if zero, the current time is used
  147. // KeyUsage specifies which Extended Key Usage values are acceptable.
  148. // An empty list means ExtKeyUsageServerAuth. Key usage is considered a
  149. // constraint down the chain which mirrors Windows CryptoAPI behavior,
  150. // but not the spec. To accept any key usage, include ExtKeyUsageAny.
  151. KeyUsages []ExtKeyUsage
  152. }
  153. const (
  154. leafCertificate = iota
  155. intermediateCertificate
  156. rootCertificate
  157. )
  158. func matchNameConstraint(domain, constraint string) bool {
  159. // The meaning of zero length constraints is not specified, but this
  160. // code follows NSS and accepts them as valid for everything.
  161. if len(constraint) == 0 {
  162. return true
  163. }
  164. if len(domain) < len(constraint) {
  165. return false
  166. }
  167. prefixLen := len(domain) - len(constraint)
  168. if !strings.EqualFold(domain[prefixLen:], constraint) {
  169. return false
  170. }
  171. if prefixLen == 0 {
  172. return true
  173. }
  174. isSubdomain := domain[prefixLen-1] == '.'
  175. constraintHasLeadingDot := constraint[0] == '.'
  176. return isSubdomain != constraintHasLeadingDot
  177. }
  178. // isValid performs validity checks on the c.
  179. func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error {
  180. if len(currentChain) > 0 {
  181. child := currentChain[len(currentChain)-1]
  182. if !bytes.Equal(child.RawIssuer, c.RawSubject) {
  183. return CertificateInvalidError{c, NameMismatch}
  184. }
  185. }
  186. now := opts.CurrentTime
  187. if now.IsZero() {
  188. now = time.Now()
  189. }
  190. if now.Before(c.NotBefore) || now.After(c.NotAfter) {
  191. return CertificateInvalidError{c, Expired}
  192. }
  193. if len(c.PermittedDNSDomains) > 0 {
  194. ok := false
  195. for _, constraint := range c.PermittedDNSDomains {
  196. ok = matchNameConstraint(opts.DNSName, constraint)
  197. if ok {
  198. break
  199. }
  200. }
  201. if !ok {
  202. return CertificateInvalidError{c, CANotAuthorizedForThisName}
  203. }
  204. }
  205. // KeyUsage status flags are ignored. From Engineering Security, Peter
  206. // Gutmann: A European government CA marked its signing certificates as
  207. // being valid for encryption only, but no-one noticed. Another
  208. // European CA marked its signature keys as not being valid for
  209. // signatures. A different CA marked its own trusted root certificate
  210. // as being invalid for certificate signing. Another national CA
  211. // distributed a certificate to be used to encrypt data for the
  212. // country’s tax authority that was marked as only being usable for
  213. // digital signatures but not for encryption. Yet another CA reversed
  214. // the order of the bit flags in the keyUsage due to confusion over
  215. // encoding endianness, essentially setting a random keyUsage in
  216. // certificates that it issued. Another CA created a self-invalidating
  217. // certificate by adding a certificate policy statement stipulating
  218. // that the certificate had to be used strictly as specified in the
  219. // keyUsage, and a keyUsage containing a flag indicating that the RSA
  220. // encryption key could only be used for Diffie-Hellman key agreement.
  221. if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) {
  222. return CertificateInvalidError{c, NotAuthorizedToSign}
  223. }
  224. if c.BasicConstraintsValid && c.MaxPathLen >= 0 {
  225. numIntermediates := len(currentChain) - 1
  226. if numIntermediates > c.MaxPathLen {
  227. return CertificateInvalidError{c, TooManyIntermediates}
  228. }
  229. }
  230. return nil
  231. }
  232. // Verify attempts to verify c by building one or more chains from c to a
  233. // certificate in opts.Roots, using certificates in opts.Intermediates if
  234. // needed. If successful, it returns one or more chains where the first
  235. // element of the chain is c and the last element is from opts.Roots.
  236. //
  237. // If opts.Roots is nil and system roots are unavailable the returned error
  238. // will be of type SystemRootsError.
  239. //
  240. // WARNING: this doesn't do any revocation checking.
  241. func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error) {
  242. // Platform-specific verification needs the ASN.1 contents so
  243. // this makes the behavior consistent across platforms.
  244. if len(c.Raw) == 0 {
  245. return nil, errNotParsed
  246. }
  247. if opts.Intermediates != nil {
  248. for _, intermediate := range opts.Intermediates.certs {
  249. if len(intermediate.Raw) == 0 {
  250. return nil, errNotParsed
  251. }
  252. }
  253. }
  254. // Use Windows's own verification and chain building.
  255. if opts.Roots == nil && runtime.GOOS == "windows" {
  256. return c.systemVerify(&opts)
  257. }
  258. if len(c.UnhandledCriticalExtensions) > 0 {
  259. return nil, UnhandledCriticalExtension{}
  260. }
  261. if opts.Roots == nil {
  262. opts.Roots = systemRootsPool()
  263. if opts.Roots == nil {
  264. return nil, SystemRootsError{systemRootsErr}
  265. }
  266. }
  267. err = c.isValid(leafCertificate, nil, &opts)
  268. if err != nil {
  269. return
  270. }
  271. if len(opts.DNSName) > 0 {
  272. err = c.VerifyHostname(opts.DNSName)
  273. if err != nil {
  274. return
  275. }
  276. }
  277. var candidateChains [][]*Certificate
  278. if opts.Roots.contains(c) {
  279. candidateChains = append(candidateChains, []*Certificate{c})
  280. } else {
  281. if candidateChains, err = c.buildChains(make(map[int][][]*Certificate), []*Certificate{c}, &opts); err != nil {
  282. return nil, err
  283. }
  284. }
  285. keyUsages := opts.KeyUsages
  286. if len(keyUsages) == 0 {
  287. keyUsages = []ExtKeyUsage{ExtKeyUsageServerAuth}
  288. }
  289. // If any key usage is acceptable then we're done.
  290. for _, usage := range keyUsages {
  291. if usage == ExtKeyUsageAny {
  292. chains = candidateChains
  293. return
  294. }
  295. }
  296. for _, candidate := range candidateChains {
  297. if checkChainForKeyUsage(candidate, keyUsages) {
  298. chains = append(chains, candidate)
  299. }
  300. }
  301. if len(chains) == 0 {
  302. err = CertificateInvalidError{c, IncompatibleUsage}
  303. }
  304. return
  305. }
  306. func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate {
  307. n := make([]*Certificate, len(chain)+1)
  308. copy(n, chain)
  309. n[len(chain)] = cert
  310. return n
  311. }
  312. func (c *Certificate) buildChains(cache map[int][][]*Certificate, currentChain []*Certificate, opts *VerifyOptions) (chains [][]*Certificate, err error) {
  313. possibleRoots, failedRoot, rootErr := opts.Roots.findVerifiedParents(c)
  314. nextRoot:
  315. for _, rootNum := range possibleRoots {
  316. root := opts.Roots.certs[rootNum]
  317. for _, cert := range currentChain {
  318. if cert.Equal(root) {
  319. continue nextRoot
  320. }
  321. }
  322. err = root.isValid(rootCertificate, currentChain, opts)
  323. if err != nil {
  324. continue
  325. }
  326. chains = append(chains, appendToFreshChain(currentChain, root))
  327. }
  328. possibleIntermediates, failedIntermediate, intermediateErr := opts.Intermediates.findVerifiedParents(c)
  329. nextIntermediate:
  330. for _, intermediateNum := range possibleIntermediates {
  331. intermediate := opts.Intermediates.certs[intermediateNum]
  332. for _, cert := range currentChain {
  333. if cert.Equal(intermediate) {
  334. continue nextIntermediate
  335. }
  336. }
  337. err = intermediate.isValid(intermediateCertificate, currentChain, opts)
  338. if err != nil {
  339. continue
  340. }
  341. var childChains [][]*Certificate
  342. childChains, ok := cache[intermediateNum]
  343. if !ok {
  344. childChains, err = intermediate.buildChains(cache, appendToFreshChain(currentChain, intermediate), opts)
  345. cache[intermediateNum] = childChains
  346. }
  347. chains = append(chains, childChains...)
  348. }
  349. if len(chains) > 0 {
  350. err = nil
  351. }
  352. if len(chains) == 0 && err == nil {
  353. hintErr := rootErr
  354. hintCert := failedRoot
  355. if hintErr == nil {
  356. hintErr = intermediateErr
  357. hintCert = failedIntermediate
  358. }
  359. err = UnknownAuthorityError{c, hintErr, hintCert}
  360. }
  361. return
  362. }
  363. func matchHostnames(pattern, host string) bool {
  364. host = strings.TrimSuffix(host, ".")
  365. pattern = strings.TrimSuffix(pattern, ".")
  366. if len(pattern) == 0 || len(host) == 0 {
  367. return false
  368. }
  369. patternParts := strings.Split(pattern, ".")
  370. hostParts := strings.Split(host, ".")
  371. if len(patternParts) != len(hostParts) {
  372. return false
  373. }
  374. for i, patternPart := range patternParts {
  375. if i == 0 && patternPart == "*" {
  376. continue
  377. }
  378. if patternPart != hostParts[i] {
  379. return false
  380. }
  381. }
  382. return true
  383. }
  384. // toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use
  385. // an explicitly ASCII function to avoid any sharp corners resulting from
  386. // performing Unicode operations on DNS labels.
  387. func toLowerCaseASCII(in string) string {
  388. // If the string is already lower-case then there's nothing to do.
  389. isAlreadyLowerCase := true
  390. for _, c := range in {
  391. if c == utf8.RuneError {
  392. // If we get a UTF-8 error then there might be
  393. // upper-case ASCII bytes in the invalid sequence.
  394. isAlreadyLowerCase = false
  395. break
  396. }
  397. if 'A' <= c && c <= 'Z' {
  398. isAlreadyLowerCase = false
  399. break
  400. }
  401. }
  402. if isAlreadyLowerCase {
  403. return in
  404. }
  405. out := []byte(in)
  406. for i, c := range out {
  407. if 'A' <= c && c <= 'Z' {
  408. out[i] += 'a' - 'A'
  409. }
  410. }
  411. return string(out)
  412. }
  413. // VerifyHostname returns nil if c is a valid certificate for the named host.
  414. // Otherwise it returns an error describing the mismatch.
  415. func (c *Certificate) VerifyHostname(h string) error {
  416. // IP addresses may be written in [ ].
  417. candidateIP := h
  418. if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' {
  419. candidateIP = h[1 : len(h)-1]
  420. }
  421. if ip := net.ParseIP(candidateIP); ip != nil {
  422. // We only match IP addresses against IP SANs.
  423. // https://tools.ietf.org/html/rfc6125#appendix-B.2
  424. for _, candidate := range c.IPAddresses {
  425. if ip.Equal(candidate) {
  426. return nil
  427. }
  428. }
  429. return HostnameError{c, candidateIP}
  430. }
  431. lowered := toLowerCaseASCII(h)
  432. if len(c.DNSNames) > 0 {
  433. for _, match := range c.DNSNames {
  434. if matchHostnames(toLowerCaseASCII(match), lowered) {
  435. return nil
  436. }
  437. }
  438. // If Subject Alt Name is given, we ignore the common name.
  439. } else if matchHostnames(toLowerCaseASCII(c.Subject.CommonName), lowered) {
  440. return nil
  441. }
  442. return HostnameError{c, h}
  443. }
  444. func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool {
  445. usages := make([]ExtKeyUsage, len(keyUsages))
  446. copy(usages, keyUsages)
  447. if len(chain) == 0 {
  448. return false
  449. }
  450. usagesRemaining := len(usages)
  451. // We walk down the list and cross out any usages that aren't supported
  452. // by each certificate. If we cross out all the usages, then the chain
  453. // is unacceptable.
  454. NextCert:
  455. for i := len(chain) - 1; i >= 0; i-- {
  456. cert := chain[i]
  457. if len(cert.ExtKeyUsage) == 0 && len(cert.UnknownExtKeyUsage) == 0 {
  458. // The certificate doesn't have any extended key usage specified.
  459. continue
  460. }
  461. for _, usage := range cert.ExtKeyUsage {
  462. if usage == ExtKeyUsageAny {
  463. // The certificate is explicitly good for any usage.
  464. continue NextCert
  465. }
  466. }
  467. const invalidUsage ExtKeyUsage = -1
  468. NextRequestedUsage:
  469. for i, requestedUsage := range usages {
  470. if requestedUsage == invalidUsage {
  471. continue
  472. }
  473. for _, usage := range cert.ExtKeyUsage {
  474. if requestedUsage == usage {
  475. continue NextRequestedUsage
  476. } else if requestedUsage == ExtKeyUsageServerAuth &&
  477. (usage == ExtKeyUsageNetscapeServerGatedCrypto ||
  478. usage == ExtKeyUsageMicrosoftServerGatedCrypto) {
  479. // In order to support COMODO
  480. // certificate chains, we have to
  481. // accept Netscape or Microsoft SGC
  482. // usages as equal to ServerAuth.
  483. continue NextRequestedUsage
  484. }
  485. }
  486. usages[i] = invalidUsage
  487. usagesRemaining--
  488. if usagesRemaining == 0 {
  489. return false
  490. }
  491. }
  492. }
  493. return true
  494. }