collection.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. default:
  118. return c.Load(string(provisioner.CredentialID))
  119. }
  120. }
  121. }
  122. // Default to noop provisioner if an extension is not found. This allows to
  123. // accept a renewal of a cert without the provisioner extension.
  124. return &noop{}, true
  125. }
  126. // LoadEncryptedKey returns an encrypted key by indexed by KeyID. At this moment
  127. // only JWK encrypted keys are indexed by KeyID.
  128. func (c *Collection) LoadEncryptedKey(keyID string) (string, bool) {
  129. p, ok := loadProvisioner(c.byKey, keyID)
  130. if !ok {
  131. return "", false
  132. }
  133. _, key, ok := p.GetEncryptedKey()
  134. return key, ok
  135. }
  136. // Store adds a provisioner to the collection and enforces the uniqueness of
  137. // provisioner IDs.
  138. func (c *Collection) Store(p Interface) error {
  139. // Store provisioner always in byID. ID must be unique.
  140. if _, loaded := c.byID.LoadOrStore(p.GetID(), p); loaded {
  141. return errors.New("cannot add multiple provisioners with the same id")
  142. }
  143. // Store provisioner in byKey if EncryptedKey is defined.
  144. if kid, _, ok := p.GetEncryptedKey(); ok {
  145. c.byKey.Store(kid, p)
  146. }
  147. // Store sorted provisioners.
  148. // Use the first 4 bytes (32bit) of the sum to insert the order
  149. // Using big endian format to get the strings sorted:
  150. // 0x00000000, 0x00000001, 0x00000002, ...
  151. bi := make([]byte, 4)
  152. sum := provisionerSum(p)
  153. binary.BigEndian.PutUint32(bi, uint32(c.sorted.Len()))
  154. sum[0], sum[1], sum[2], sum[3] = bi[0], bi[1], bi[2], bi[3]
  155. c.sorted = append(c.sorted, uidProvisioner{
  156. provisioner: p,
  157. uid: hex.EncodeToString(sum),
  158. })
  159. sort.Sort(c.sorted)
  160. return nil
  161. }
  162. // Find implements pagination on a list of sorted provisioners.
  163. func (c *Collection) Find(cursor string, limit int) (List, string) {
  164. switch {
  165. case limit <= 0:
  166. limit = DefaultProvisionersLimit
  167. case limit > DefaultProvisionersMax:
  168. limit = DefaultProvisionersMax
  169. }
  170. n := c.sorted.Len()
  171. cursor = fmt.Sprintf("%040s", cursor)
  172. i := sort.Search(n, func(i int) bool { return c.sorted[i].uid >= cursor })
  173. slice := List{}
  174. for ; i < n && len(slice) < limit; i++ {
  175. slice = append(slice, c.sorted[i].provisioner)
  176. }
  177. if i < n {
  178. return slice, strings.TrimLeft(c.sorted[i].uid, "0")
  179. }
  180. return slice, ""
  181. }
  182. func loadProvisioner(m *sync.Map, key string) (Interface, bool) {
  183. i, ok := m.Load(key)
  184. if !ok {
  185. return nil, false
  186. }
  187. p, ok := i.(Interface)
  188. if !ok {
  189. return nil, false
  190. }
  191. return p, true
  192. }
  193. // provisionerSum returns the SHA1 of the provisioners ID. From this we will
  194. // create the unique and sorted id.
  195. func provisionerSum(p Interface) []byte {
  196. sum := sha1.Sum([]byte(p.GetID()))
  197. return sum[:]
  198. }
  199. // matchesAudience returns true if A and B share at least one element.
  200. func matchesAudience(as, bs []string) bool {
  201. if len(bs) == 0 || len(as) == 0 {
  202. return false
  203. }
  204. for _, b := range bs {
  205. for _, a := range as {
  206. if b == a || stripPort(a) == stripPort(b) {
  207. return true
  208. }
  209. }
  210. }
  211. return false
  212. }
  213. // stripPort attempts to strip the port from the given url. If parsing the url
  214. // produces errors it will just return the passed argument.
  215. func stripPort(rawurl string) string {
  216. u, err := url.Parse(rawurl)
  217. if err != nil {
  218. return rawurl
  219. }
  220. u.Host = u.Hostname()
  221. return u.String()
  222. }
  223. // extractFragment extracts the first fragment of an audience url.
  224. func extractFragment(audience []string) string {
  225. for _, s := range audience {
  226. if u, err := url.Parse(s); err == nil && u.Fragment != "" {
  227. return u.Fragment
  228. }
  229. }
  230. return ""
  231. }