collection.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. // loadByTokenPayload is a payload used to extract the id used to load the
  29. // provisioner.
  30. type loadByTokenPayload struct {
  31. jose.Claims
  32. AuthorizedParty string `json:"azp"` // OIDC client id
  33. TenantID string `json:"tid"` // Microsoft Azure tenant id
  34. }
  35. // Collection is a memory map of provisioners.
  36. type Collection struct {
  37. byID *sync.Map
  38. byKey *sync.Map
  39. sorted provisionerSlice
  40. audiences Audiences
  41. }
  42. // NewCollection initializes a collection of provisioners. The given list of
  43. // audiences are the audiences used by the JWT provisioner.
  44. func NewCollection(audiences Audiences) *Collection {
  45. return &Collection{
  46. byID: new(sync.Map),
  47. byKey: new(sync.Map),
  48. audiences: audiences,
  49. }
  50. }
  51. // Load a provisioner by the ID.
  52. func (c *Collection) Load(id string) (Interface, bool) {
  53. return loadProvisioner(c.byID, id)
  54. }
  55. // LoadByToken parses the token claims and loads the provisioner associated.
  56. func (c *Collection) LoadByToken(token *jose.JSONWebToken, claims *jose.Claims) (Interface, bool) {
  57. var audiences []string
  58. // Get all audiences with the given fragment
  59. fragment := extractFragment(claims.Audience)
  60. if fragment == "" {
  61. audiences = c.audiences.All()
  62. } else {
  63. audiences = c.audiences.WithFragment(fragment).All()
  64. }
  65. // match with server audiences
  66. if matchesAudience(claims.Audience, audiences) {
  67. // Use fragment to get provisioner name (GCP, AWS)
  68. if fragment != "" {
  69. return c.Load(fragment)
  70. }
  71. // If matches with stored audiences it will be a JWT token (default), and
  72. // the id would be <issuer>:<kid>.
  73. return c.Load(claims.Issuer + ":" + token.Headers[0].KeyID)
  74. }
  75. // The ID will be just the clientID stored in azp, aud or tid.
  76. var payload loadByTokenPayload
  77. if err := token.UnsafeClaimsWithoutVerification(&payload); err != nil {
  78. return nil, false
  79. }
  80. // Audience is required
  81. if len(payload.Audience) == 0 {
  82. return nil, false
  83. }
  84. // Try with azp (OIDC)
  85. if len(payload.AuthorizedParty) > 0 {
  86. if p, ok := c.Load(payload.AuthorizedParty); ok {
  87. return p, ok
  88. }
  89. }
  90. // Try with tid (Azure)
  91. if payload.TenantID != "" {
  92. if p, ok := c.Load(payload.TenantID); ok {
  93. return p, ok
  94. }
  95. }
  96. // Fallback to aud
  97. return c.Load(payload.Audience[0])
  98. }
  99. // LoadByCertificate looks for the provisioner extension and extracts the
  100. // proper id to load the provisioner.
  101. func (c *Collection) LoadByCertificate(cert *x509.Certificate) (Interface, bool) {
  102. for _, e := range cert.Extensions {
  103. if e.Id.Equal(stepOIDProvisioner) {
  104. var provisioner stepProvisionerASN1
  105. if _, err := asn1.Unmarshal(e.Value, &provisioner); err != nil {
  106. return nil, false
  107. }
  108. switch Type(provisioner.Type) {
  109. case TypeJWK:
  110. return c.Load(string(provisioner.Name) + ":" + string(provisioner.CredentialID))
  111. case TypeAWS:
  112. return c.Load("aws/" + string(provisioner.Name))
  113. case TypeGCP:
  114. return c.Load("gcp/" + string(provisioner.Name))
  115. case TypeACME:
  116. return c.Load("acme/" + string(provisioner.Name))
  117. case TypeX5C:
  118. return c.Load("x5c/" + string(provisioner.Name))
  119. default:
  120. return c.Load(string(provisioner.CredentialID))
  121. }
  122. }
  123. }
  124. // Default to noop provisioner if an extension is not found. This allows to
  125. // accept a renewal of a cert without the provisioner extension.
  126. return &noop{}, true
  127. }
  128. // LoadEncryptedKey returns an encrypted key by indexed by KeyID. At this moment
  129. // only JWK encrypted keys are indexed by KeyID.
  130. func (c *Collection) LoadEncryptedKey(keyID string) (string, bool) {
  131. p, ok := loadProvisioner(c.byKey, keyID)
  132. if !ok {
  133. return "", false
  134. }
  135. _, key, ok := p.GetEncryptedKey()
  136. return key, ok
  137. }
  138. // Store adds a provisioner to the collection and enforces the uniqueness of
  139. // provisioner IDs.
  140. func (c *Collection) Store(p Interface) error {
  141. // Store provisioner always in byID. ID must be unique.
  142. if _, loaded := c.byID.LoadOrStore(p.GetID(), p); loaded {
  143. return errors.New("cannot add multiple provisioners with the same id")
  144. }
  145. // Store provisioner in byKey if EncryptedKey is defined.
  146. if kid, _, ok := p.GetEncryptedKey(); ok {
  147. c.byKey.Store(kid, p)
  148. }
  149. // Store sorted provisioners.
  150. // Use the first 4 bytes (32bit) of the sum to insert the order
  151. // Using big endian format to get the strings sorted:
  152. // 0x00000000, 0x00000001, 0x00000002, ...
  153. bi := make([]byte, 4)
  154. sum := provisionerSum(p)
  155. binary.BigEndian.PutUint32(bi, uint32(c.sorted.Len()))
  156. sum[0], sum[1], sum[2], sum[3] = bi[0], bi[1], bi[2], bi[3]
  157. c.sorted = append(c.sorted, uidProvisioner{
  158. provisioner: p,
  159. uid: hex.EncodeToString(sum),
  160. })
  161. sort.Sort(c.sorted)
  162. return nil
  163. }
  164. // Find implements pagination on a list of sorted provisioners.
  165. func (c *Collection) Find(cursor string, limit int) (List, string) {
  166. switch {
  167. case limit <= 0:
  168. limit = DefaultProvisionersLimit
  169. case limit > DefaultProvisionersMax:
  170. limit = DefaultProvisionersMax
  171. }
  172. n := c.sorted.Len()
  173. cursor = fmt.Sprintf("%040s", cursor)
  174. i := sort.Search(n, func(i int) bool { return c.sorted[i].uid >= cursor })
  175. slice := List{}
  176. for ; i < n && len(slice) < limit; i++ {
  177. slice = append(slice, c.sorted[i].provisioner)
  178. }
  179. if i < n {
  180. return slice, strings.TrimLeft(c.sorted[i].uid, "0")
  181. }
  182. return slice, ""
  183. }
  184. func loadProvisioner(m *sync.Map, key string) (Interface, bool) {
  185. i, ok := m.Load(key)
  186. if !ok {
  187. return nil, false
  188. }
  189. p, ok := i.(Interface)
  190. if !ok {
  191. return nil, false
  192. }
  193. return p, true
  194. }
  195. // provisionerSum returns the SHA1 of the provisioners ID. From this we will
  196. // create the unique and sorted id.
  197. func provisionerSum(p Interface) []byte {
  198. sum := sha1.Sum([]byte(p.GetID()))
  199. return sum[:]
  200. }
  201. // matchesAudience returns true if A and B share at least one element.
  202. func matchesAudience(as, bs []string) bool {
  203. if len(bs) == 0 || len(as) == 0 {
  204. return false
  205. }
  206. for _, b := range bs {
  207. for _, a := range as {
  208. if b == a || stripPort(a) == stripPort(b) {
  209. return true
  210. }
  211. }
  212. }
  213. return false
  214. }
  215. // stripPort attempts to strip the port from the given url. If parsing the url
  216. // produces errors it will just return the passed argument.
  217. func stripPort(rawurl string) string {
  218. u, err := url.Parse(rawurl)
  219. if err != nil {
  220. return rawurl
  221. }
  222. u.Host = u.Hostname()
  223. return u.String()
  224. }
  225. // extractFragment extracts the first fragment of an audience url.
  226. func extractFragment(audience []string) string {
  227. for _, s := range audience {
  228. if u, err := url.Parse(s); err == nil && u.Fragment != "" {
  229. return u.Fragment
  230. }
  231. }
  232. return ""
  233. }