collection.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. "go.step.sm/crypto/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, SSHPOP)
  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. // Kubernetes Service Account tokens.
  81. if payload.Issuer == k8sSAIssuer {
  82. if p, ok := c.Load(K8sSAID); ok {
  83. return p, ok
  84. }
  85. // Kubernetes service account provisioner not found
  86. return nil, false
  87. }
  88. // Audience is required for non k8sSA tokens.
  89. if len(payload.Audience) == 0 {
  90. return nil, false
  91. }
  92. // Try with azp (OIDC)
  93. if len(payload.AuthorizedParty) > 0 {
  94. if p, ok := c.Load(payload.AuthorizedParty); ok {
  95. return p, ok
  96. }
  97. }
  98. // Try with tid (Azure)
  99. if payload.TenantID != "" {
  100. if p, ok := c.Load(payload.TenantID); ok {
  101. return p, ok
  102. }
  103. }
  104. // Fallback to aud
  105. return c.Load(payload.Audience[0])
  106. }
  107. // LoadByCertificate looks for the provisioner extension and extracts the
  108. // proper id to load the provisioner.
  109. func (c *Collection) LoadByCertificate(cert *x509.Certificate) (Interface, bool) {
  110. for _, e := range cert.Extensions {
  111. if e.Id.Equal(stepOIDProvisioner) {
  112. var provisioner stepProvisionerASN1
  113. if _, err := asn1.Unmarshal(e.Value, &provisioner); err != nil {
  114. return nil, false
  115. }
  116. switch Type(provisioner.Type) {
  117. case TypeJWK:
  118. return c.Load(string(provisioner.Name) + ":" + string(provisioner.CredentialID))
  119. case TypeAWS:
  120. return c.Load("aws/" + string(provisioner.Name))
  121. case TypeGCP:
  122. return c.Load("gcp/" + string(provisioner.Name))
  123. case TypeACME:
  124. return c.Load("acme/" + string(provisioner.Name))
  125. case TypeX5C:
  126. return c.Load("x5c/" + string(provisioner.Name))
  127. case TypeK8sSA:
  128. return c.Load(K8sSAID)
  129. default:
  130. return c.Load(string(provisioner.CredentialID))
  131. }
  132. }
  133. }
  134. // Default to noop provisioner if an extension is not found. This allows to
  135. // accept a renewal of a cert without the provisioner extension.
  136. return &noop{}, true
  137. }
  138. // LoadEncryptedKey returns an encrypted key by indexed by KeyID. At this moment
  139. // only JWK encrypted keys are indexed by KeyID.
  140. func (c *Collection) LoadEncryptedKey(keyID string) (string, bool) {
  141. p, ok := loadProvisioner(c.byKey, keyID)
  142. if !ok {
  143. return "", false
  144. }
  145. _, key, ok := p.GetEncryptedKey()
  146. return key, ok
  147. }
  148. // Store adds a provisioner to the collection and enforces the uniqueness of
  149. // provisioner IDs.
  150. func (c *Collection) Store(p Interface) error {
  151. // Store provisioner always in byID. ID must be unique.
  152. if _, loaded := c.byID.LoadOrStore(p.GetID(), p); loaded {
  153. return errors.New("cannot add multiple provisioners with the same id")
  154. }
  155. // Store provisioner in byKey if EncryptedKey is defined.
  156. if kid, _, ok := p.GetEncryptedKey(); ok {
  157. c.byKey.Store(kid, p)
  158. }
  159. // Store sorted provisioners.
  160. // Use the first 4 bytes (32bit) of the sum to insert the order
  161. // Using big endian format to get the strings sorted:
  162. // 0x00000000, 0x00000001, 0x00000002, ...
  163. bi := make([]byte, 4)
  164. sum := provisionerSum(p)
  165. binary.BigEndian.PutUint32(bi, uint32(c.sorted.Len()))
  166. sum[0], sum[1], sum[2], sum[3] = bi[0], bi[1], bi[2], bi[3]
  167. c.sorted = append(c.sorted, uidProvisioner{
  168. provisioner: p,
  169. uid: hex.EncodeToString(sum),
  170. })
  171. sort.Sort(c.sorted)
  172. return nil
  173. }
  174. // Find implements pagination on a list of sorted provisioners.
  175. func (c *Collection) Find(cursor string, limit int) (List, string) {
  176. switch {
  177. case limit <= 0:
  178. limit = DefaultProvisionersLimit
  179. case limit > DefaultProvisionersMax:
  180. limit = DefaultProvisionersMax
  181. }
  182. n := c.sorted.Len()
  183. cursor = fmt.Sprintf("%040s", cursor)
  184. i := sort.Search(n, func(i int) bool { return c.sorted[i].uid >= cursor })
  185. slice := List{}
  186. for ; i < n && len(slice) < limit; i++ {
  187. slice = append(slice, c.sorted[i].provisioner)
  188. }
  189. if i < n {
  190. return slice, strings.TrimLeft(c.sorted[i].uid, "0")
  191. }
  192. return slice, ""
  193. }
  194. func loadProvisioner(m *sync.Map, key string) (Interface, bool) {
  195. i, ok := m.Load(key)
  196. if !ok {
  197. return nil, false
  198. }
  199. p, ok := i.(Interface)
  200. if !ok {
  201. return nil, false
  202. }
  203. return p, true
  204. }
  205. // provisionerSum returns the SHA1 of the provisioners ID. From this we will
  206. // create the unique and sorted id.
  207. func provisionerSum(p Interface) []byte {
  208. sum := sha1.Sum([]byte(p.GetID()))
  209. return sum[:]
  210. }
  211. // matchesAudience returns true if A and B share at least one element.
  212. func matchesAudience(as, bs []string) bool {
  213. if len(bs) == 0 || len(as) == 0 {
  214. return false
  215. }
  216. for _, b := range bs {
  217. for _, a := range as {
  218. if b == a || stripPort(a) == stripPort(b) {
  219. return true
  220. }
  221. }
  222. }
  223. return false
  224. }
  225. // stripPort attempts to strip the port from the given url. If parsing the url
  226. // produces errors it will just return the passed argument.
  227. func stripPort(rawurl string) string {
  228. u, err := url.Parse(rawurl)
  229. if err != nil {
  230. return rawurl
  231. }
  232. u.Host = u.Hostname()
  233. return u.String()
  234. }
  235. // extractFragment extracts the first fragment of an audience url.
  236. func extractFragment(audience []string) string {
  237. for _, s := range audience {
  238. if u, err := url.Parse(s); err == nil && u.Fragment != "" {
  239. return u.Fragment
  240. }
  241. }
  242. return ""
  243. }