collection.go 10 KB

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