pem_chain.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. /*
  2. MIT License
  3. Copyright (c) Microsoft Corporation.
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE
  19. Original Author: Anish Ramasekar https://github.com/aramase
  20. In: https://github.com/Azure/secrets-store-csi-driver-provider-azure/pull/332
  21. This file is a local fork/adaptation of the original implementation.
  22. It does not need to be kept up to date with Azure upstream due to divergences.
  23. */
  24. package template
  25. import (
  26. "bytes"
  27. "crypto/x509"
  28. "encoding/pem"
  29. "errors"
  30. )
  31. const (
  32. errNilCert = "certificate is nil"
  33. errFoundDisjunctCert = "found multiple leaf or disjunct certificates"
  34. errNoLeafFound = "no leaf certificate found"
  35. errChainCycle = "constructing chain resulted in cycle"
  36. )
  37. type node struct {
  38. cert *x509.Certificate
  39. parent *node
  40. isParent bool
  41. }
  42. // fetchX509CertChains parses PEM-encoded certificates and returns them ordered
  43. // as leaf -> intermediate(s) -> root when a single chain can be inferred from
  44. // AuthorityKeyId/SubjectKeyId relationships.
  45. //
  46. // This is a formatting/templating helper only. It does not perform certificate
  47. // trust validation: it does not verify signatures, expiry, hostnames, key usage,
  48. // CA constraints, revocation, or trusted roots. Do not use a nil error from this
  49. // function as proof that a certificate chain is valid or trusted; use
  50. // crypto/x509.Certificate.Verify with explicit VerifyOptions for that purpose.
  51. func fetchX509CertChains(data []byte) ([]*x509.Certificate, error) {
  52. var newCertChain []*x509.Certificate
  53. nodes, err := pemToNodes(data)
  54. if err != nil {
  55. return nil, err
  56. }
  57. // at the end of this computation, the output will be a single linked list
  58. // the tail of the list will be the root node (which has no parents)
  59. // the head of the list will be the leaf node (whose parent will be intermediate certs)
  60. // (head) leaf -> intermediates -> root (tail)
  61. for i := range nodes {
  62. for j := range nodes {
  63. // ignore same node to prevent generating a cycle
  64. if i == j {
  65. continue
  66. }
  67. // if ith node AuthorityKeyId is same as jth node SubjectKeyId, jth node was used
  68. // to sign the ith certificate
  69. if bytes.Equal(nodes[i].cert.AuthorityKeyId, nodes[j].cert.SubjectKeyId) {
  70. nodes[j].isParent = true
  71. nodes[i].parent = nodes[j]
  72. break
  73. }
  74. }
  75. }
  76. var foundLeaf bool
  77. var leaf *node
  78. for i := range nodes {
  79. if !nodes[i].isParent {
  80. if foundLeaf {
  81. return nil, errors.New(errFoundDisjunctCert)
  82. }
  83. // this is the leaf node as it's not a parent for any other node
  84. leaf = nodes[i]
  85. foundLeaf = true
  86. }
  87. }
  88. if leaf == nil {
  89. return nil, errors.New(errNoLeafFound)
  90. }
  91. processedNodes := 0
  92. // iterate through the directed list and append the nodes to new cert chain
  93. for leaf != nil {
  94. processedNodes++
  95. // ensure we aren't stuck in a cyclic loop
  96. if processedNodes > len(nodes) {
  97. return nil, errors.New(errChainCycle)
  98. }
  99. newCertChain = append(newCertChain, leaf.cert)
  100. leaf = leaf.parent
  101. }
  102. return newCertChain, nil
  103. }
  104. // fetchCertChains returns PEM-encoded certificates ordered by
  105. // fetchX509CertChains. It preserves the same non-validation semantics: the
  106. // returned order is not proof of trust or cryptographic validity.
  107. func fetchCertChains(data []byte) ([]byte, error) {
  108. var pemData []byte
  109. newCertChain, err := fetchX509CertChains(data)
  110. if err != nil {
  111. return nil, err
  112. }
  113. for _, cert := range newCertChain {
  114. b := &pem.Block{
  115. Type: pemTypeCertificate,
  116. Bytes: cert.Raw,
  117. }
  118. pemData = append(pemData, pem.EncodeToMemory(b)...)
  119. }
  120. return pemData, nil
  121. }
  122. // pemToNodes decodes all PEM blocks in data as X.509 certificates and wraps
  123. // them as chain-construction nodes.
  124. //
  125. // Like fetchX509CertChains, this only parses certificate syntax. A successfully
  126. // parsed certificate is not necessarily trusted, currently valid, usable for a
  127. // given purpose, or correctly signed by another certificate in the input.
  128. func pemToNodes(data []byte) ([]*node, error) {
  129. nodes := make([]*node, 0)
  130. for {
  131. // decode pem to der first
  132. block, rest := pem.Decode(data)
  133. data = rest
  134. if block == nil {
  135. break
  136. }
  137. cert, err := x509.ParseCertificate(block.Bytes)
  138. if err != nil {
  139. return nil, err
  140. }
  141. // this should not be the case because ParseCertificate should return a non nil
  142. // certificate when there is no error.
  143. if cert == nil {
  144. return nil, errors.New(errNilCert)
  145. }
  146. nodes = append(nodes, &node{
  147. cert: cert,
  148. parent: nil,
  149. isParent: false,
  150. })
  151. }
  152. return nodes, nil
  153. }