pem_chain.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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. */
  22. package template
  23. import (
  24. "bytes"
  25. "crypto/x509"
  26. "encoding/pem"
  27. "fmt"
  28. )
  29. const (
  30. errNilCert = "certificate is nil"
  31. errFoundDisjunctCert = "found multiple leaf or disjunct certificates"
  32. errNoLeafFound = "no leaf certificate found"
  33. errChainCycle = "constructing chain resulted in cycle"
  34. )
  35. type node struct {
  36. cert *x509.Certificate
  37. parent *node
  38. isParent bool
  39. }
  40. func fetchCertChains(data []byte) ([]byte, error) {
  41. var newCertChain []*x509.Certificate
  42. var pemData []byte
  43. nodes, err := pemToNodes(data)
  44. if err != nil {
  45. return nil, err
  46. }
  47. // at the end of this computation, the output will be a single linked list
  48. // the tail of the list will be the root node (which has no parents)
  49. // the head of the list will be the leaf node (whose parent will be intermediate certs)
  50. // (head) leaf -> intermediates -> root (tail)
  51. for i := range nodes {
  52. for j := range nodes {
  53. // ignore same node to prevent generating a cycle
  54. if i == j {
  55. continue
  56. }
  57. // if ith node AuthorityKeyId is same as jth node SubjectKeyId, jth node was used
  58. // to sign the ith certificate
  59. if bytes.Equal(nodes[i].cert.AuthorityKeyId, nodes[j].cert.SubjectKeyId) {
  60. nodes[j].isParent = true
  61. nodes[i].parent = nodes[j]
  62. break
  63. }
  64. }
  65. }
  66. var foundLeaf bool
  67. var leaf *node
  68. for i := range nodes {
  69. if !nodes[i].isParent {
  70. if foundLeaf {
  71. return nil, fmt.Errorf(errFoundDisjunctCert)
  72. }
  73. // this is the leaf node as it's not a parent for any other node
  74. leaf = nodes[i]
  75. foundLeaf = true
  76. }
  77. }
  78. if leaf == nil {
  79. return nil, fmt.Errorf(errNoLeafFound)
  80. }
  81. processedNodes := 0
  82. // iterate through the directed list and append the nodes to new cert chain
  83. for leaf != nil {
  84. processedNodes++
  85. // ensure we aren't stuck in a cyclic loop
  86. if processedNodes > len(nodes) {
  87. return pemData, fmt.Errorf(errChainCycle)
  88. }
  89. newCertChain = append(newCertChain, leaf.cert)
  90. leaf = leaf.parent
  91. }
  92. for _, cert := range newCertChain {
  93. b := &pem.Block{
  94. Type: pemTypeCertificate,
  95. Bytes: cert.Raw,
  96. }
  97. pemData = append(pemData, pem.EncodeToMemory(b)...)
  98. }
  99. return pemData, nil
  100. }
  101. func pemToNodes(data []byte) ([]*node, error) {
  102. nodes := make([]*node, 0)
  103. for {
  104. // decode pem to der first
  105. block, rest := pem.Decode(data)
  106. data = rest
  107. if block == nil {
  108. break
  109. }
  110. cert, err := x509.ParseCertificate(block.Bytes)
  111. if err != nil {
  112. return nil, err
  113. }
  114. // this should not be the case because ParseCertificate should return a non nil
  115. // certificate when there is no error.
  116. if cert == nil {
  117. return nil, fmt.Errorf(errNilCert)
  118. }
  119. nodes = append(nodes, &node{
  120. cert: cert,
  121. parent: nil,
  122. isParent: false,
  123. })
  124. }
  125. return nodes, nil
  126. }