collection.go 11 KB

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