collection.go 7.6 KB

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