collection.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. package provisioner
  2. import (
  3. "crypto/sha1"
  4. "crypto/x509"
  5. "encoding/asn1"
  6. "encoding/binary"
  7. "encoding/hex"
  8. "fmt"
  9. "net/url"
  10. "sort"
  11. "strings"
  12. "sync"
  13. "github.com/pkg/errors"
  14. "github.com/smallstep/cli/jose"
  15. )
  16. // DefaultProvisionersLimit is the default limit for listing provisioners.
  17. const DefaultProvisionersLimit = 20
  18. // DefaultProvisionersMax is the maximum limit for listing provisioners.
  19. const DefaultProvisionersMax = 100
  20. type uidProvisioner struct {
  21. provisioner Interface
  22. uid string
  23. }
  24. type provisionerSlice []uidProvisioner
  25. func (p provisionerSlice) Len() int { return len(p) }
  26. func (p provisionerSlice) Less(i, j int) bool { return p[i].uid < p[j].uid }
  27. func (p provisionerSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  28. // Collection is a memory map of provisioners.
  29. type Collection struct {
  30. byID *sync.Map
  31. byKey *sync.Map
  32. sorted provisionerSlice
  33. audiences []string
  34. }
  35. // NewCollection initializes a collection of provisioners. The given list of
  36. // audiences are the audiences used by the JWT provisioner.
  37. func NewCollection(audiences []string) *Collection {
  38. return &Collection{
  39. byID: new(sync.Map),
  40. byKey: new(sync.Map),
  41. audiences: audiences,
  42. }
  43. }
  44. // Load a provisioner by the ID.
  45. func (c *Collection) Load(id string) (Interface, bool) {
  46. return loadProvisioner(c.byID, id)
  47. }
  48. // LoadByToken parses the token claims and loads the provisioner associated.
  49. func (c *Collection) LoadByToken(token *jose.JSONWebToken, claims *jose.Claims) (Interface, bool) {
  50. // match with server audiences
  51. if matchesAudience(claims.Audience, c.audiences) {
  52. // If matches with stored audiences it will be a JWT token (default), and
  53. // the id would be <issuer>:<kid>.
  54. return c.Load(claims.Issuer + ":" + token.Headers[0].KeyID)
  55. }
  56. // The ID will be just the clientID stored in azp or aud.
  57. var payload openIDPayload
  58. if err := token.UnsafeClaimsWithoutVerification(&payload); err != nil {
  59. return nil, false
  60. }
  61. // audience is required
  62. if len(payload.Audience) == 0 {
  63. return nil, false
  64. }
  65. if len(payload.AuthorizedParty) > 0 {
  66. return c.Load(payload.AuthorizedParty)
  67. }
  68. return c.Load(payload.Audience[0])
  69. }
  70. // LoadByCertificate looks for the provisioner extension and extracts the
  71. // proper id to load the provisioner.
  72. func (c *Collection) LoadByCertificate(cert *x509.Certificate) (Interface, bool) {
  73. for _, e := range cert.Extensions {
  74. if e.Id.Equal(stepOIDProvisioner) {
  75. var provisioner stepProvisionerASN1
  76. if _, err := asn1.Unmarshal(e.Value, &provisioner); err != nil {
  77. return nil, false
  78. }
  79. if provisioner.Type == int(TypeJWK) {
  80. return c.Load(string(provisioner.Name) + ":" + string(provisioner.CredentialID))
  81. }
  82. return c.Load(string(provisioner.CredentialID))
  83. }
  84. }
  85. // Default to noop provisioner if an extension is not found. This allows to
  86. // accept a renewal of a cert without the provisioner extension.
  87. return &noop{}, true
  88. }
  89. // LoadEncryptedKey returns a the encrypted key by KeyID. At this moment only
  90. // JWK encrypted keys are indexed by KeyID.
  91. func (c *Collection) LoadEncryptedKey(keyID string) (string, bool) {
  92. p, ok := loadProvisioner(c.byKey, keyID)
  93. if !ok {
  94. return "", false
  95. }
  96. _, key, ok := p.GetEncryptedKey()
  97. return key, ok
  98. }
  99. // Store adds a provisioner to the collection, it makes sure two provisioner
  100. // does not have the same ID.
  101. func (c *Collection) Store(p Interface) error {
  102. // Store provisioner always in byID. ID must be unique.
  103. if _, loaded := c.byID.LoadOrStore(p.GetID(), p); loaded == true {
  104. return errors.New("cannot add multiple provisioners with the same id")
  105. }
  106. // Store provisioner in byKey in EncryptedKey is defined.
  107. if kid, _, ok := p.GetEncryptedKey(); ok {
  108. c.byKey.Store(kid, p)
  109. }
  110. // Store sorted provisioners.
  111. // Use the first 4 bytes (32bit) of the sum to insert the order
  112. // Using big endian format to get the strings sorted:
  113. // 0x00000000, 0x00000001, 0x00000002, ...
  114. bi := make([]byte, 4)
  115. sum := provisionerSum(p)
  116. binary.BigEndian.PutUint32(bi, uint32(c.sorted.Len()))
  117. sum[0], sum[1], sum[2], sum[3] = bi[0], bi[1], bi[2], bi[3]
  118. c.sorted = append(c.sorted, uidProvisioner{
  119. provisioner: p,
  120. uid: hex.EncodeToString(sum),
  121. })
  122. sort.Sort(c.sorted)
  123. return nil
  124. }
  125. // Find implements pagination on a list of sorted provisioners.
  126. func (c *Collection) Find(cursor string, limit int) (List, string) {
  127. switch {
  128. case limit <= 0:
  129. limit = DefaultProvisionersLimit
  130. case limit > DefaultProvisionersMax:
  131. limit = DefaultProvisionersMax
  132. }
  133. n := c.sorted.Len()
  134. cursor = fmt.Sprintf("%040s", cursor)
  135. i := sort.Search(n, func(i int) bool { return c.sorted[i].uid >= cursor })
  136. slice := List{}
  137. for ; i < n && len(slice) < limit; i++ {
  138. slice = append(slice, c.sorted[i].provisioner)
  139. }
  140. if i < n {
  141. return slice, strings.TrimLeft(c.sorted[i].uid, "0")
  142. }
  143. return slice, ""
  144. }
  145. func loadProvisioner(m *sync.Map, key string) (Interface, bool) {
  146. i, ok := m.Load(key)
  147. if !ok {
  148. return nil, false
  149. }
  150. p, ok := i.(Interface)
  151. if !ok {
  152. return nil, false
  153. }
  154. return p, true
  155. }
  156. // provisionerSum returns the SHA1 of the provisioners ID. From this we will
  157. // create the unique and sorted id.
  158. func provisionerSum(p Interface) []byte {
  159. sum := sha1.Sum([]byte(p.GetID()))
  160. return sum[:]
  161. }
  162. // matchesAudience returns true if A and B share at least one element.
  163. func matchesAudience(as, bs []string) bool {
  164. if len(bs) == 0 || len(as) == 0 {
  165. return false
  166. }
  167. for _, b := range bs {
  168. for _, a := range as {
  169. if b == a || stripPort(a) == stripPort(b) {
  170. return true
  171. }
  172. }
  173. }
  174. return false
  175. }
  176. // stripPort attempts to strip the port from the given url. If parsing the url
  177. // produces errors it will just return the passed argument.
  178. func stripPort(rawurl string) string {
  179. u, err := url.Parse(rawurl)
  180. if err != nil {
  181. return rawurl
  182. }
  183. u.Host = u.Hostname()
  184. return u.String()
  185. }