collection.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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/smallstep/certificates/authority/admin"
  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. byName *sync.Map
  40. byTokenID *sync.Map
  41. sorted provisionerSlice
  42. audiences Audiences
  43. }
  44. // NewCollection initializes a collection of provisioners. The given list of
  45. // audiences are the audiences used by the JWT provisioner.
  46. func NewCollection(audiences Audiences) *Collection {
  47. return &Collection{
  48. byID: new(sync.Map),
  49. byKey: new(sync.Map),
  50. byName: new(sync.Map),
  51. byTokenID: new(sync.Map),
  52. audiences: audiences,
  53. }
  54. }
  55. // Load a provisioner by the ID.
  56. func (c *Collection) Load(id string) (Interface, bool) {
  57. return loadProvisioner(c.byID, id)
  58. }
  59. // LoadByName a provisioner by name.
  60. func (c *Collection) LoadByName(name string) (Interface, bool) {
  61. return loadProvisioner(c.byName, name)
  62. }
  63. // LoadByTokenID a provisioner by identifier found in token.
  64. // For different provisioner types this identifier may be found in in different
  65. // attributes of the token.
  66. func (c *Collection) LoadByTokenID(tokenProvisionerID string) (Interface, bool) {
  67. return loadProvisioner(c.byTokenID, tokenProvisionerID)
  68. }
  69. // LoadByToken parses the token claims and loads the provisioner associated.
  70. func (c *Collection) LoadByToken(token *jose.JSONWebToken, claims *jose.Claims) (Interface, bool) {
  71. var audiences []string
  72. // Get all audiences with the given fragment
  73. fragment := extractFragment(claims.Audience)
  74. if fragment == "" {
  75. audiences = c.audiences.All()
  76. } else {
  77. audiences = c.audiences.WithFragment(fragment).All()
  78. }
  79. // match with server audiences
  80. if matchesAudience(claims.Audience, audiences) {
  81. // Use fragment to get provisioner name (GCP, AWS, SSHPOP)
  82. if fragment != "" {
  83. return c.LoadByTokenID(fragment)
  84. }
  85. // If matches with stored audiences it will be a JWT token (default), and
  86. // the id would be <issuer>:<kid>.
  87. // TODO: is this ok?
  88. return c.LoadByTokenID(claims.Issuer + ":" + token.Headers[0].KeyID)
  89. }
  90. // The ID will be just the clientID stored in azp, aud or tid.
  91. var payload loadByTokenPayload
  92. if err := token.UnsafeClaimsWithoutVerification(&payload); err != nil {
  93. return nil, false
  94. }
  95. // Kubernetes Service Account tokens.
  96. if payload.Issuer == k8sSAIssuer {
  97. if p, ok := c.LoadByTokenID(K8sSAID); ok {
  98. return p, ok
  99. }
  100. // Kubernetes service account provisioner not found
  101. return nil, false
  102. }
  103. // Audience is required for non k8sSA tokens.
  104. if len(payload.Audience) == 0 {
  105. return nil, false
  106. }
  107. // Try with azp (OIDC)
  108. if len(payload.AuthorizedParty) > 0 {
  109. if p, ok := c.LoadByTokenID(payload.AuthorizedParty); ok {
  110. return p, ok
  111. }
  112. }
  113. // Try with tid (Azure)
  114. if payload.TenantID != "" {
  115. if p, ok := c.LoadByTokenID(payload.TenantID); ok {
  116. return p, ok
  117. }
  118. }
  119. // Fallback to aud
  120. return c.LoadByTokenID(payload.Audience[0])
  121. }
  122. // LoadByCertificate looks for the provisioner extension and extracts the
  123. // proper id to load the provisioner.
  124. func (c *Collection) LoadByCertificate(cert *x509.Certificate) (Interface, bool) {
  125. for _, e := range cert.Extensions {
  126. if e.Id.Equal(stepOIDProvisioner) {
  127. var provisioner stepProvisionerASN1
  128. if _, err := asn1.Unmarshal(e.Value, &provisioner); err != nil {
  129. return nil, false
  130. }
  131. return c.LoadByName(string(provisioner.Name))
  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 admin.NewError(admin.ErrorBadRequestType,
  154. "cannot add multiple provisioners with the same id")
  155. }
  156. // Store provisioner always by name.
  157. if _, loaded := c.byName.LoadOrStore(p.GetName(), p); loaded {
  158. c.byID.Delete(p.GetID())
  159. return admin.NewError(admin.ErrorBadRequestType,
  160. "cannot add multiple provisioners with the same name")
  161. }
  162. // Store provisioner always by ID presented in token.
  163. if _, loaded := c.byTokenID.LoadOrStore(p.GetIDForToken(), p); loaded {
  164. c.byID.Delete(p.GetID())
  165. c.byName.Delete(p.GetName())
  166. return admin.NewError(admin.ErrorBadRequestType,
  167. "cannot add multiple provisioners with the same token identifier")
  168. }
  169. // Store provisioner in byKey if EncryptedKey is defined.
  170. if kid, _, ok := p.GetEncryptedKey(); ok {
  171. c.byKey.Store(kid, p)
  172. }
  173. // Store sorted provisioners.
  174. // Use the first 4 bytes (32bit) of the sum to insert the order
  175. // Using big endian format to get the strings sorted:
  176. // 0x00000000, 0x00000001, 0x00000002, ...
  177. bi := make([]byte, 4)
  178. sum := provisionerSum(p)
  179. binary.BigEndian.PutUint32(bi, uint32(c.sorted.Len()))
  180. sum[0], sum[1], sum[2], sum[3] = bi[0], bi[1], bi[2], bi[3]
  181. c.sorted = append(c.sorted, uidProvisioner{
  182. provisioner: p,
  183. uid: hex.EncodeToString(sum),
  184. })
  185. sort.Sort(c.sorted)
  186. return nil
  187. }
  188. // Remove deletes an provisioner from all associated collections and lists.
  189. func (c *Collection) Remove(id string) error {
  190. prov, ok := c.Load(id)
  191. if !ok {
  192. return admin.NewError(admin.ErrorNotFoundType, "provisioner %s not found", id)
  193. }
  194. var found bool
  195. for i, elem := range c.sorted {
  196. if elem.provisioner.GetID() == id {
  197. // Remove index in sorted list
  198. copy(c.sorted[i:], c.sorted[i+1:]) // Shift a[i+1:] left one index.
  199. c.sorted[len(c.sorted)-1] = uidProvisioner{} // Erase last element (write zero value).
  200. c.sorted = c.sorted[:len(c.sorted)-1] // Truncate slice.
  201. found = true
  202. break
  203. }
  204. }
  205. if !found {
  206. return admin.NewError(admin.ErrorNotFoundType, "provisioner %s not found in sorted list", prov.GetName())
  207. }
  208. c.byID.Delete(id)
  209. c.byName.Delete(prov.GetName())
  210. c.byTokenID.Delete(prov.GetIDForToken())
  211. if kid, _, ok := prov.GetEncryptedKey(); ok {
  212. c.byKey.Delete(kid)
  213. }
  214. return nil
  215. }
  216. // Update updates the given provisioner in all related lists and collections.
  217. func (c *Collection) Update(nu Interface) error {
  218. old, ok := c.Load(nu.GetID())
  219. if !ok {
  220. return admin.NewError(admin.ErrorNotFoundType, "provisioner %s not found", nu.GetID())
  221. }
  222. if old.GetName() != nu.GetName() {
  223. if _, ok := c.LoadByName(nu.GetName()); ok {
  224. return admin.NewError(admin.ErrorBadRequestType,
  225. "provisioner with name %s already exists", nu.GetName())
  226. }
  227. }
  228. if old.GetIDForToken() != nu.GetIDForToken() {
  229. if _, ok := c.LoadByTokenID(nu.GetIDForToken()); ok {
  230. return admin.NewError(admin.ErrorBadRequestType,
  231. "provisioner with Token ID %s already exists", nu.GetIDForToken())
  232. }
  233. }
  234. if err := c.Remove(old.GetID()); err != nil {
  235. return err
  236. }
  237. return c.Store(nu)
  238. }
  239. // Find implements pagination on a list of sorted provisioners.
  240. func (c *Collection) Find(cursor string, limit int) (List, string) {
  241. switch {
  242. case limit <= 0:
  243. limit = DefaultProvisionersLimit
  244. case limit > DefaultProvisionersMax:
  245. limit = DefaultProvisionersMax
  246. }
  247. n := c.sorted.Len()
  248. cursor = fmt.Sprintf("%040s", cursor)
  249. i := sort.Search(n, func(i int) bool { return c.sorted[i].uid >= cursor })
  250. slice := List{}
  251. for ; i < n && len(slice) < limit; i++ {
  252. slice = append(slice, c.sorted[i].provisioner)
  253. }
  254. if i < n {
  255. return slice, strings.TrimLeft(c.sorted[i].uid, "0")
  256. }
  257. return slice, ""
  258. }
  259. func loadProvisioner(m *sync.Map, key string) (Interface, bool) {
  260. i, ok := m.Load(key)
  261. if !ok {
  262. return nil, false
  263. }
  264. p, ok := i.(Interface)
  265. if !ok {
  266. return nil, false
  267. }
  268. return p, true
  269. }
  270. // provisionerSum returns the SHA1 of the provisioners ID. From this we will
  271. // create the unique and sorted id.
  272. func provisionerSum(p Interface) []byte {
  273. sum := sha1.Sum([]byte(p.GetID()))
  274. return sum[:]
  275. }
  276. // matchesAudience returns true if A and B share at least one element.
  277. func matchesAudience(as, bs []string) bool {
  278. if len(bs) == 0 || len(as) == 0 {
  279. return false
  280. }
  281. for _, b := range bs {
  282. for _, a := range as {
  283. if b == a || stripPort(a) == stripPort(b) {
  284. return true
  285. }
  286. }
  287. }
  288. return false
  289. }
  290. // stripPort attempts to strip the port from the given url. If parsing the url
  291. // produces errors it will just return the passed argument.
  292. func stripPort(rawurl string) string {
  293. u, err := url.Parse(rawurl)
  294. if err != nil {
  295. return rawurl
  296. }
  297. u.Host = u.Hostname()
  298. return u.String()
  299. }
  300. // extractFragment extracts the first fragment of an audience url.
  301. func extractFragment(audience []string) string {
  302. for _, s := range audience {
  303. if u, err := url.Parse(s); err == nil && u.Fragment != "" {
  304. return u.Fragment
  305. }
  306. }
  307. return ""
  308. }