collection.go 10 KB

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