provisioners.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. package authority
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/x509"
  6. "encoding/json"
  7. "encoding/pem"
  8. "fmt"
  9. "os"
  10. "github.com/pkg/errors"
  11. "github.com/smallstep/certificates/authority/admin"
  12. "github.com/smallstep/certificates/authority/config"
  13. "github.com/smallstep/certificates/authority/provisioner"
  14. "github.com/smallstep/certificates/errs"
  15. "go.step.sm/cli-utils/step"
  16. "go.step.sm/cli-utils/ui"
  17. "go.step.sm/crypto/jose"
  18. "go.step.sm/linkedca"
  19. "gopkg.in/square/go-jose.v2/jwt"
  20. )
  21. // Provisioners is the interface used by the provisioners collection.
  22. type Provisioners interface {
  23. Load(id string) (provisioner.Interface, bool)
  24. Store(p provisioner.Interface) error
  25. Update(p provisioner.Interface) error
  26. Remove(id string) error
  27. LoadByName(name string) (provisioner.Interface, bool)
  28. LoadByToken(token *jose.JSONWebToken, claims *jose.Claims) (provisioner.Interface, bool)
  29. LoadByTokenID(tokenProvisionerID string) (provisioner.Interface, bool)
  30. LoadByCertificate(cert *x509.Certificate) (provisioner.Interface, bool)
  31. Find(cursor string, limit int) (provisioner.List, string)
  32. LoadEncryptedKey(keyID string) (string, bool)
  33. }
  34. // GetEncryptedKey returns the JWE key corresponding to the given kid argument.
  35. func (a *Authority) GetEncryptedKey(kid string) (string, error) {
  36. a.adminMutex.RLock()
  37. defer a.adminMutex.RUnlock()
  38. key, ok := a.provisioners.LoadEncryptedKey(kid)
  39. if !ok {
  40. return "", errs.NotFound("encrypted key with kid %s was not found", kid)
  41. }
  42. return key, nil
  43. }
  44. // GetProvisioners returns a map listing each provisioner and the JWK Key Set
  45. // with their public keys.
  46. func (a *Authority) GetProvisioners(cursor string, limit int) (provisioner.List, string, error) {
  47. a.adminMutex.RLock()
  48. defer a.adminMutex.RUnlock()
  49. provisioners, nextCursor := a.provisioners.Find(cursor, limit)
  50. return provisioners, nextCursor, nil
  51. }
  52. // LoadProvisionerByCertificate returns an interface to the provisioner that
  53. // provisioned the certificate.
  54. func (a *Authority) LoadProvisionerByCertificate(crt *x509.Certificate) (provisioner.Interface, error) {
  55. a.adminMutex.RLock()
  56. defer a.adminMutex.RUnlock()
  57. p, ok := a.provisioners.LoadByCertificate(crt)
  58. if !ok {
  59. return nil, admin.NewError(admin.ErrorNotFoundType, "unable to load provisioner from certificate")
  60. }
  61. return p, nil
  62. }
  63. // LoadProvisionerByToken returns an interface to the provisioner that
  64. // provisioned the token.
  65. func (a *Authority) LoadProvisionerByToken(token *jwt.JSONWebToken, claims *jwt.Claims) (provisioner.Interface, error) {
  66. a.adminMutex.RLock()
  67. defer a.adminMutex.RUnlock()
  68. p, ok := a.provisioners.LoadByToken(token, claims)
  69. if !ok {
  70. return nil, admin.NewError(admin.ErrorNotFoundType, "unable to load provisioner from token")
  71. }
  72. return p, nil
  73. }
  74. // LoadProvisionerByID returns an interface to the provisioner with the given ID.
  75. func (a *Authority) LoadProvisionerByID(id string) (provisioner.Interface, error) {
  76. a.adminMutex.RLock()
  77. defer a.adminMutex.RUnlock()
  78. p, ok := a.provisioners.Load(id)
  79. if !ok {
  80. return nil, admin.NewError(admin.ErrorNotFoundType, "provisioner %s not found", id)
  81. }
  82. return p, nil
  83. }
  84. // LoadProvisionerByName returns an interface to the provisioner with the given Name.
  85. func (a *Authority) LoadProvisionerByName(name string) (provisioner.Interface, error) {
  86. a.adminMutex.RLock()
  87. defer a.adminMutex.RUnlock()
  88. p, ok := a.provisioners.LoadByName(name)
  89. if !ok {
  90. return nil, admin.NewError(admin.ErrorNotFoundType, "provisioner %s not found", name)
  91. }
  92. return p, nil
  93. }
  94. func (a *Authority) generateProvisionerConfig(ctx context.Context) (provisioner.Config, error) {
  95. // Merge global and configuration claims
  96. claimer, err := provisioner.NewClaimer(a.config.AuthorityConfig.Claims, config.GlobalProvisionerClaims)
  97. if err != nil {
  98. return provisioner.Config{}, err
  99. }
  100. // TODO: should we also be combining the ssh federated roots here?
  101. // If we rotate ssh roots keys, sshpop provisioner will lose ability to
  102. // validate old SSH certificates, unless they are added as federated certs.
  103. sshKeys, err := a.GetSSHRoots(ctx)
  104. if err != nil {
  105. return provisioner.Config{}, err
  106. }
  107. return provisioner.Config{
  108. Claims: claimer.Claims(),
  109. Audiences: a.config.GetAudiences(),
  110. DB: a.db,
  111. SSHKeys: &provisioner.SSHKeys{
  112. UserKeys: sshKeys.UserKeys,
  113. HostKeys: sshKeys.HostKeys,
  114. },
  115. GetIdentityFunc: a.getIdentityFunc,
  116. AuthorizeRenewFunc: a.authorizeRenewFunc,
  117. AuthorizeSSHRenewFunc: a.authorizeSSHRenewFunc,
  118. }, nil
  119. }
  120. // StoreProvisioner stores an provisioner.Interface to the authority.
  121. func (a *Authority) StoreProvisioner(ctx context.Context, prov *linkedca.Provisioner) error {
  122. a.adminMutex.Lock()
  123. defer a.adminMutex.Unlock()
  124. certProv, err := ProvisionerToCertificates(prov)
  125. if err != nil {
  126. return admin.WrapErrorISE(err,
  127. "error converting to certificates provisioner from linkedca provisioner")
  128. }
  129. if _, ok := a.provisioners.LoadByName(prov.GetName()); ok {
  130. return admin.NewError(admin.ErrorBadRequestType,
  131. "provisioner with name %s already exists", prov.GetName())
  132. }
  133. if _, ok := a.provisioners.LoadByTokenID(certProv.GetIDForToken()); ok {
  134. return admin.NewError(admin.ErrorBadRequestType,
  135. "provisioner with token ID %s already exists", certProv.GetIDForToken())
  136. }
  137. provisionerConfig, err := a.generateProvisionerConfig(ctx)
  138. if err != nil {
  139. return admin.WrapErrorISE(err, "error generating provisioner config")
  140. }
  141. if err := certProv.Init(provisionerConfig); err != nil {
  142. return admin.WrapError(admin.ErrorBadRequestType, err, "error validating configuration for provisioner %s", prov.Name)
  143. }
  144. // Store to database -- this will set the ID.
  145. if err := a.adminDB.CreateProvisioner(ctx, prov); err != nil {
  146. return admin.WrapErrorISE(err, "error creating provisioner")
  147. }
  148. // We need a new conversion that has the newly set ID.
  149. certProv, err = ProvisionerToCertificates(prov)
  150. if err != nil {
  151. return admin.WrapErrorISE(err,
  152. "error converting to certificates provisioner from linkedca provisioner")
  153. }
  154. if err := certProv.Init(provisionerConfig); err != nil {
  155. return admin.WrapErrorISE(err, "error initializing provisioner %s", prov.Name)
  156. }
  157. if err := a.provisioners.Store(certProv); err != nil {
  158. if err := a.reloadAdminResources(ctx); err != nil {
  159. return admin.WrapErrorISE(err, "error reloading admin resources on failed provisioner store")
  160. }
  161. return admin.WrapErrorISE(err, "error storing provisioner in authority cache")
  162. }
  163. return nil
  164. }
  165. // UpdateProvisioner stores an provisioner.Interface to the authority.
  166. func (a *Authority) UpdateProvisioner(ctx context.Context, nu *linkedca.Provisioner) error {
  167. a.adminMutex.Lock()
  168. defer a.adminMutex.Unlock()
  169. certProv, err := ProvisionerToCertificates(nu)
  170. if err != nil {
  171. return admin.WrapErrorISE(err,
  172. "error converting to certificates provisioner from linkedca provisioner")
  173. }
  174. provisionerConfig, err := a.generateProvisionerConfig(ctx)
  175. if err != nil {
  176. return admin.WrapErrorISE(err, "error generating provisioner config")
  177. }
  178. if err := certProv.Init(provisionerConfig); err != nil {
  179. return admin.WrapErrorISE(err, "error initializing provisioner %s", nu.Name)
  180. }
  181. if err := a.provisioners.Update(certProv); err != nil {
  182. return admin.WrapErrorISE(err, "error updating provisioner '%s' in authority cache", nu.Name)
  183. }
  184. if err := a.adminDB.UpdateProvisioner(ctx, nu); err != nil {
  185. if err := a.reloadAdminResources(ctx); err != nil {
  186. return admin.WrapErrorISE(err, "error reloading admin resources on failed provisioner update")
  187. }
  188. return admin.WrapErrorISE(err, "error updating provisioner '%s'", nu.Name)
  189. }
  190. return nil
  191. }
  192. // RemoveProvisioner removes an provisioner.Interface from the authority.
  193. func (a *Authority) RemoveProvisioner(ctx context.Context, id string) error {
  194. a.adminMutex.Lock()
  195. defer a.adminMutex.Unlock()
  196. p, ok := a.provisioners.Load(id)
  197. if !ok {
  198. return admin.NewError(admin.ErrorBadRequestType,
  199. "provisioner %s not found", id)
  200. }
  201. provName, provID := p.GetName(), p.GetID()
  202. // Validate
  203. // - Check that there will be SUPER_ADMINs that remain after we
  204. // remove this provisioner.
  205. if a.admins.SuperCount() == a.admins.SuperCountByProvisioner(provName) {
  206. return admin.NewError(admin.ErrorBadRequestType,
  207. "cannot remove provisioner %s because no super admins will remain", provName)
  208. }
  209. // Delete all admins associated with the provisioner.
  210. admins, ok := a.admins.LoadByProvisioner(provName)
  211. if ok {
  212. for _, adm := range admins {
  213. if err := a.removeAdmin(ctx, adm.Id); err != nil {
  214. return admin.WrapErrorISE(err, "error deleting admin %s, as part of provisioner %s deletion", adm.Subject, provName)
  215. }
  216. }
  217. }
  218. // Remove provisioner from authority caches.
  219. if err := a.provisioners.Remove(provID); err != nil {
  220. return admin.WrapErrorISE(err, "error removing admin from authority cache")
  221. }
  222. // Remove provisioner from database.
  223. if err := a.adminDB.DeleteProvisioner(ctx, provID); err != nil {
  224. if err := a.reloadAdminResources(ctx); err != nil {
  225. return admin.WrapErrorISE(err, "error reloading admin resources on failed provisioner remove")
  226. }
  227. return admin.WrapErrorISE(err, "error deleting provisioner %s", provName)
  228. }
  229. return nil
  230. }
  231. // CreateFirstProvisioner creates and stores the first provisioner when using
  232. // admin database provisioner storage.
  233. func CreateFirstProvisioner(ctx context.Context, db admin.DB, password string) (*linkedca.Provisioner, error) {
  234. if password == "" {
  235. pass, err := ui.PromptPasswordGenerate("Please enter the password to encrypt your first provisioner, leave empty and we'll generate one")
  236. if err != nil {
  237. return nil, err
  238. }
  239. password = string(pass)
  240. }
  241. jwk, jwe, err := jose.GenerateDefaultKeyPair([]byte(password))
  242. if err != nil {
  243. return nil, admin.WrapErrorISE(err, "error generating JWK key pair")
  244. }
  245. jwkPubBytes, err := jwk.MarshalJSON()
  246. if err != nil {
  247. return nil, admin.WrapErrorISE(err, "error marshaling JWK")
  248. }
  249. jwePrivStr, err := jwe.CompactSerialize()
  250. if err != nil {
  251. return nil, admin.WrapErrorISE(err, "error serializing JWE")
  252. }
  253. p := &linkedca.Provisioner{
  254. Name: "Admin JWK",
  255. Type: linkedca.Provisioner_JWK,
  256. Details: &linkedca.ProvisionerDetails{
  257. Data: &linkedca.ProvisionerDetails_JWK{
  258. JWK: &linkedca.JWKProvisioner{
  259. PublicKey: jwkPubBytes,
  260. EncryptedPrivateKey: []byte(jwePrivStr),
  261. },
  262. },
  263. },
  264. Claims: &linkedca.Claims{
  265. X509: &linkedca.X509Claims{
  266. Enabled: true,
  267. Durations: &linkedca.Durations{
  268. Default: "5m",
  269. },
  270. },
  271. },
  272. }
  273. if err := db.CreateProvisioner(ctx, p); err != nil {
  274. return nil, admin.WrapErrorISE(err, "error creating provisioner")
  275. }
  276. return p, nil
  277. }
  278. // ValidateClaims validates the Claims type.
  279. func ValidateClaims(c *linkedca.Claims) error {
  280. if c == nil {
  281. return nil
  282. }
  283. if c.X509 != nil {
  284. if c.X509.Durations != nil {
  285. if err := ValidateDurations(c.X509.Durations); err != nil {
  286. return err
  287. }
  288. }
  289. }
  290. if c.Ssh != nil {
  291. if c.Ssh.UserDurations != nil {
  292. if err := ValidateDurations(c.Ssh.UserDurations); err != nil {
  293. return err
  294. }
  295. }
  296. if c.Ssh.HostDurations != nil {
  297. if err := ValidateDurations(c.Ssh.HostDurations); err != nil {
  298. return err
  299. }
  300. }
  301. }
  302. return nil
  303. }
  304. // ValidateDurations validates the Durations type.
  305. func ValidateDurations(d *linkedca.Durations) error {
  306. var (
  307. err error
  308. min, max, def *provisioner.Duration
  309. )
  310. if d.Min != "" {
  311. min, err = provisioner.NewDuration(d.Min)
  312. if err != nil {
  313. return admin.WrapError(admin.ErrorBadRequestType, err, "min duration '%s' is invalid", d.Min)
  314. }
  315. if min.Value() < 0 {
  316. return admin.WrapError(admin.ErrorBadRequestType, err, "min duration '%s' cannot be less than 0", d.Min)
  317. }
  318. }
  319. if d.Max != "" {
  320. max, err = provisioner.NewDuration(d.Max)
  321. if err != nil {
  322. return admin.WrapError(admin.ErrorBadRequestType, err, "max duration '%s' is invalid", d.Max)
  323. }
  324. if max.Value() < 0 {
  325. return admin.WrapError(admin.ErrorBadRequestType, err, "max duration '%s' cannot be less than 0", d.Max)
  326. }
  327. }
  328. if d.Default != "" {
  329. def, err = provisioner.NewDuration(d.Default)
  330. if err != nil {
  331. return admin.WrapError(admin.ErrorBadRequestType, err, "default duration '%s' is invalid", d.Default)
  332. }
  333. if def.Value() < 0 {
  334. return admin.WrapError(admin.ErrorBadRequestType, err, "default duration '%s' cannot be less than 0", d.Default)
  335. }
  336. }
  337. if d.Min != "" && d.Max != "" && min.Value() > max.Value() {
  338. return admin.NewError(admin.ErrorBadRequestType,
  339. "min duration '%s' cannot be greater than max duration '%s'", d.Min, d.Max)
  340. }
  341. if d.Min != "" && d.Default != "" && min.Value() > def.Value() {
  342. return admin.NewError(admin.ErrorBadRequestType,
  343. "min duration '%s' cannot be greater than default duration '%s'", d.Min, d.Default)
  344. }
  345. if d.Default != "" && d.Max != "" && min.Value() > def.Value() {
  346. return admin.NewError(admin.ErrorBadRequestType,
  347. "default duration '%s' cannot be greater than max duration '%s'", d.Default, d.Max)
  348. }
  349. return nil
  350. }
  351. func provisionerListToCertificates(l []*linkedca.Provisioner) (provisioner.List, error) {
  352. var nu provisioner.List
  353. for _, p := range l {
  354. certProv, err := ProvisionerToCertificates(p)
  355. if err != nil {
  356. return nil, err
  357. }
  358. nu = append(nu, certProv)
  359. }
  360. return nu, nil
  361. }
  362. func optionsToCertificates(p *linkedca.Provisioner) *provisioner.Options {
  363. ops := &provisioner.Options{
  364. X509: &provisioner.X509Options{},
  365. SSH: &provisioner.SSHOptions{},
  366. }
  367. if p.X509Template != nil {
  368. ops.X509.Template = string(p.X509Template.Template)
  369. ops.X509.TemplateData = p.X509Template.Data
  370. }
  371. if p.SshTemplate != nil {
  372. ops.SSH.Template = string(p.SshTemplate.Template)
  373. ops.SSH.TemplateData = p.SshTemplate.Data
  374. }
  375. return ops
  376. }
  377. func durationsToCertificates(d *linkedca.Durations) (min, max, def *provisioner.Duration, err error) {
  378. if len(d.Min) > 0 {
  379. min, err = provisioner.NewDuration(d.Min)
  380. if err != nil {
  381. return nil, nil, nil, admin.WrapErrorISE(err, "error parsing minimum duration '%s'", d.Min)
  382. }
  383. }
  384. if len(d.Max) > 0 {
  385. max, err = provisioner.NewDuration(d.Max)
  386. if err != nil {
  387. return nil, nil, nil, admin.WrapErrorISE(err, "error parsing maximum duration '%s'", d.Max)
  388. }
  389. }
  390. if len(d.Default) > 0 {
  391. def, err = provisioner.NewDuration(d.Default)
  392. if err != nil {
  393. return nil, nil, nil, admin.WrapErrorISE(err, "error parsing default duration '%s'", d.Default)
  394. }
  395. }
  396. return
  397. }
  398. func durationsToLinkedca(d *provisioner.Duration) string {
  399. if d == nil {
  400. return ""
  401. }
  402. return d.Duration.String()
  403. }
  404. // claimsToCertificates converts the linkedca provisioner claims type to the
  405. // certifictes claims type.
  406. func claimsToCertificates(c *linkedca.Claims) (*provisioner.Claims, error) {
  407. if c == nil {
  408. return nil, nil
  409. }
  410. pc := &provisioner.Claims{
  411. DisableRenewal: &c.DisableRenewal,
  412. AllowRenewAfterExpiry: &c.AllowRenewAfterExpiry,
  413. }
  414. var err error
  415. if xc := c.X509; xc != nil {
  416. if d := xc.Durations; d != nil {
  417. pc.MinTLSDur, pc.MaxTLSDur, pc.DefaultTLSDur, err = durationsToCertificates(d)
  418. if err != nil {
  419. return nil, err
  420. }
  421. }
  422. }
  423. if sc := c.Ssh; sc != nil {
  424. pc.EnableSSHCA = &sc.Enabled
  425. if d := sc.UserDurations; d != nil {
  426. pc.MinUserSSHDur, pc.MaxUserSSHDur, pc.DefaultUserSSHDur, err = durationsToCertificates(d)
  427. if err != nil {
  428. return nil, err
  429. }
  430. }
  431. if d := sc.HostDurations; d != nil {
  432. pc.MinHostSSHDur, pc.MaxHostSSHDur, pc.DefaultHostSSHDur, err = durationsToCertificates(d)
  433. if err != nil {
  434. return nil, err
  435. }
  436. }
  437. }
  438. return pc, nil
  439. }
  440. func claimsToLinkedca(c *provisioner.Claims) *linkedca.Claims {
  441. if c == nil {
  442. return nil
  443. }
  444. disableRenewal := config.DefaultDisableRenewal
  445. allowRenewAfterExpiry := config.DefaultAllowRenewAfterExpiry
  446. if c.DisableRenewal != nil {
  447. disableRenewal = *c.DisableRenewal
  448. }
  449. if c.AllowRenewAfterExpiry != nil {
  450. allowRenewAfterExpiry = *c.AllowRenewAfterExpiry
  451. }
  452. lc := &linkedca.Claims{
  453. DisableRenewal: disableRenewal,
  454. AllowRenewAfterExpiry: allowRenewAfterExpiry,
  455. }
  456. if c.DefaultTLSDur != nil || c.MinTLSDur != nil || c.MaxTLSDur != nil {
  457. lc.X509 = &linkedca.X509Claims{
  458. Enabled: true,
  459. Durations: &linkedca.Durations{
  460. Default: durationsToLinkedca(c.DefaultTLSDur),
  461. Min: durationsToLinkedca(c.MinTLSDur),
  462. Max: durationsToLinkedca(c.MaxTLSDur),
  463. },
  464. }
  465. }
  466. if c.EnableSSHCA != nil && *c.EnableSSHCA {
  467. lc.Ssh = &linkedca.SSHClaims{
  468. Enabled: true,
  469. }
  470. if c.DefaultUserSSHDur != nil || c.MinUserSSHDur != nil || c.MaxUserSSHDur != nil {
  471. lc.Ssh.UserDurations = &linkedca.Durations{
  472. Default: durationsToLinkedca(c.DefaultUserSSHDur),
  473. Min: durationsToLinkedca(c.MinUserSSHDur),
  474. Max: durationsToLinkedca(c.MaxUserSSHDur),
  475. }
  476. }
  477. if c.DefaultHostSSHDur != nil || c.MinHostSSHDur != nil || c.MaxHostSSHDur != nil {
  478. lc.Ssh.HostDurations = &linkedca.Durations{
  479. Default: durationsToLinkedca(c.DefaultHostSSHDur),
  480. Min: durationsToLinkedca(c.MinHostSSHDur),
  481. Max: durationsToLinkedca(c.MaxHostSSHDur),
  482. }
  483. }
  484. }
  485. return lc
  486. }
  487. func provisionerOptionsToLinkedca(p *provisioner.Options) (*linkedca.Template, *linkedca.Template, error) {
  488. var err error
  489. var x509Template, sshTemplate *linkedca.Template
  490. if p == nil {
  491. return nil, nil, nil
  492. }
  493. if p.X509 != nil && p.X509.HasTemplate() {
  494. x509Template = &linkedca.Template{
  495. Template: nil,
  496. Data: nil,
  497. }
  498. if p.X509.Template != "" {
  499. x509Template.Template = []byte(p.SSH.Template)
  500. } else if p.X509.TemplateFile != "" {
  501. filename := step.Abs(p.X509.TemplateFile)
  502. if x509Template.Template, err = os.ReadFile(filename); err != nil {
  503. return nil, nil, errors.Wrap(err, "error reading x509 template")
  504. }
  505. }
  506. }
  507. if p.SSH != nil && p.SSH.HasTemplate() {
  508. sshTemplate = &linkedca.Template{
  509. Template: nil,
  510. Data: nil,
  511. }
  512. if p.SSH.Template != "" {
  513. sshTemplate.Template = []byte(p.SSH.Template)
  514. } else if p.SSH.TemplateFile != "" {
  515. filename := step.Abs(p.SSH.TemplateFile)
  516. if sshTemplate.Template, err = os.ReadFile(filename); err != nil {
  517. return nil, nil, errors.Wrap(err, "error reading ssh template")
  518. }
  519. }
  520. }
  521. return x509Template, sshTemplate, nil
  522. }
  523. func provisionerPEMToLinkedca(b []byte) [][]byte {
  524. var roots [][]byte
  525. var block *pem.Block
  526. for {
  527. if block, b = pem.Decode(b); block == nil {
  528. break
  529. }
  530. roots = append(roots, pem.EncodeToMemory(block))
  531. }
  532. return roots
  533. }
  534. // ProvisionerToCertificates converts the linkedca provisioner type to the certificates provisioner
  535. // interface.
  536. func ProvisionerToCertificates(p *linkedca.Provisioner) (provisioner.Interface, error) {
  537. claims, err := claimsToCertificates(p.Claims)
  538. if err != nil {
  539. return nil, err
  540. }
  541. details := p.Details.GetData()
  542. if details == nil {
  543. return nil, errors.New("provisioner does not have any details")
  544. }
  545. options := optionsToCertificates(p)
  546. switch d := details.(type) {
  547. case *linkedca.ProvisionerDetails_JWK:
  548. jwk := new(jose.JSONWebKey)
  549. if err := json.Unmarshal(d.JWK.PublicKey, &jwk); err != nil {
  550. return nil, errors.Wrap(err, "error unmarshaling public key")
  551. }
  552. return &provisioner.JWK{
  553. ID: p.Id,
  554. Type: p.Type.String(),
  555. Name: p.Name,
  556. Key: jwk,
  557. EncryptedKey: string(d.JWK.EncryptedPrivateKey),
  558. Claims: claims,
  559. Options: options,
  560. }, nil
  561. case *linkedca.ProvisionerDetails_X5C:
  562. var roots []byte
  563. for i, root := range d.X5C.GetRoots() {
  564. if i > 0 {
  565. roots = append(roots, '\n')
  566. }
  567. roots = append(roots, root...)
  568. }
  569. return &provisioner.X5C{
  570. ID: p.Id,
  571. Type: p.Type.String(),
  572. Name: p.Name,
  573. Roots: roots,
  574. Claims: claims,
  575. Options: options,
  576. }, nil
  577. case *linkedca.ProvisionerDetails_K8SSA:
  578. var publicKeys []byte
  579. for i, k := range d.K8SSA.GetPublicKeys() {
  580. if i > 0 {
  581. publicKeys = append(publicKeys, '\n')
  582. }
  583. publicKeys = append(publicKeys, k...)
  584. }
  585. return &provisioner.K8sSA{
  586. ID: p.Id,
  587. Type: p.Type.String(),
  588. Name: p.Name,
  589. PubKeys: publicKeys,
  590. Claims: claims,
  591. Options: options,
  592. }, nil
  593. case *linkedca.ProvisionerDetails_SSHPOP:
  594. return &provisioner.SSHPOP{
  595. ID: p.Id,
  596. Type: p.Type.String(),
  597. Name: p.Name,
  598. Claims: claims,
  599. }, nil
  600. case *linkedca.ProvisionerDetails_ACME:
  601. cfg := d.ACME
  602. return &provisioner.ACME{
  603. ID: p.Id,
  604. Type: p.Type.String(),
  605. Name: p.Name,
  606. ForceCN: cfg.ForceCn,
  607. RequireEAB: cfg.RequireEab,
  608. Claims: claims,
  609. Options: options,
  610. }, nil
  611. case *linkedca.ProvisionerDetails_OIDC:
  612. cfg := d.OIDC
  613. return &provisioner.OIDC{
  614. ID: p.Id,
  615. Type: p.Type.String(),
  616. Name: p.Name,
  617. TenantID: cfg.TenantId,
  618. ClientID: cfg.ClientId,
  619. ClientSecret: cfg.ClientSecret,
  620. ConfigurationEndpoint: cfg.ConfigurationEndpoint,
  621. Admins: cfg.Admins,
  622. Domains: cfg.Domains,
  623. Groups: cfg.Groups,
  624. ListenAddress: cfg.ListenAddress,
  625. Claims: claims,
  626. Options: options,
  627. }, nil
  628. case *linkedca.ProvisionerDetails_AWS:
  629. cfg := d.AWS
  630. instanceAge, err := parseInstanceAge(cfg.InstanceAge)
  631. if err != nil {
  632. return nil, err
  633. }
  634. return &provisioner.AWS{
  635. ID: p.Id,
  636. Type: p.Type.String(),
  637. Name: p.Name,
  638. Accounts: cfg.Accounts,
  639. DisableCustomSANs: cfg.DisableCustomSans,
  640. DisableTrustOnFirstUse: cfg.DisableTrustOnFirstUse,
  641. InstanceAge: instanceAge,
  642. Claims: claims,
  643. Options: options,
  644. }, nil
  645. case *linkedca.ProvisionerDetails_GCP:
  646. cfg := d.GCP
  647. instanceAge, err := parseInstanceAge(cfg.InstanceAge)
  648. if err != nil {
  649. return nil, err
  650. }
  651. return &provisioner.GCP{
  652. ID: p.Id,
  653. Type: p.Type.String(),
  654. Name: p.Name,
  655. ServiceAccounts: cfg.ServiceAccounts,
  656. ProjectIDs: cfg.ProjectIds,
  657. DisableCustomSANs: cfg.DisableCustomSans,
  658. DisableTrustOnFirstUse: cfg.DisableTrustOnFirstUse,
  659. InstanceAge: instanceAge,
  660. Claims: claims,
  661. Options: options,
  662. }, nil
  663. case *linkedca.ProvisionerDetails_Azure:
  664. cfg := d.Azure
  665. return &provisioner.Azure{
  666. ID: p.Id,
  667. Type: p.Type.String(),
  668. Name: p.Name,
  669. TenantID: cfg.TenantId,
  670. ResourceGroups: cfg.ResourceGroups,
  671. SubscriptionIDs: cfg.SubscriptionIds,
  672. ObjectIDs: cfg.ObjectIds,
  673. Audience: cfg.Audience,
  674. DisableCustomSANs: cfg.DisableCustomSans,
  675. DisableTrustOnFirstUse: cfg.DisableTrustOnFirstUse,
  676. Claims: claims,
  677. Options: options,
  678. }, nil
  679. case *linkedca.ProvisionerDetails_SCEP:
  680. cfg := d.SCEP
  681. return &provisioner.SCEP{
  682. ID: p.Id,
  683. Type: p.Type.String(),
  684. Name: p.Name,
  685. ForceCN: cfg.ForceCn,
  686. ChallengePassword: cfg.Challenge,
  687. Capabilities: cfg.Capabilities,
  688. IncludeRoot: cfg.IncludeRoot,
  689. MinimumPublicKeyLength: int(cfg.MinimumPublicKeyLength),
  690. EncryptionAlgorithmIdentifier: int(cfg.EncryptionAlgorithmIdentifier),
  691. Claims: claims,
  692. Options: options,
  693. }, nil
  694. case *linkedca.ProvisionerDetails_Nebula:
  695. var roots []byte
  696. for i, root := range d.Nebula.GetRoots() {
  697. if i > 0 && !bytes.HasSuffix(root, []byte{'\n'}) {
  698. roots = append(roots, '\n')
  699. }
  700. roots = append(roots, root...)
  701. }
  702. return &provisioner.Nebula{
  703. ID: p.Id,
  704. Type: p.Type.String(),
  705. Name: p.Name,
  706. Roots: roots,
  707. Claims: claims,
  708. Options: options,
  709. }, nil
  710. default:
  711. return nil, fmt.Errorf("provisioner %s not implemented", p.Type)
  712. }
  713. }
  714. // ProvisionerToLinkedca converts a provisioner.Interface to a
  715. // linkedca.Provisioner type.
  716. func ProvisionerToLinkedca(p provisioner.Interface) (*linkedca.Provisioner, error) {
  717. switch p := p.(type) {
  718. case *provisioner.JWK:
  719. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  720. if err != nil {
  721. return nil, err
  722. }
  723. publicKey, err := json.Marshal(p.Key)
  724. if err != nil {
  725. return nil, errors.Wrap(err, "error marshaling key")
  726. }
  727. return &linkedca.Provisioner{
  728. Id: p.ID,
  729. Type: linkedca.Provisioner_JWK,
  730. Name: p.GetName(),
  731. Details: &linkedca.ProvisionerDetails{
  732. Data: &linkedca.ProvisionerDetails_JWK{
  733. JWK: &linkedca.JWKProvisioner{
  734. PublicKey: publicKey,
  735. EncryptedPrivateKey: []byte(p.EncryptedKey),
  736. },
  737. },
  738. },
  739. Claims: claimsToLinkedca(p.Claims),
  740. X509Template: x509Template,
  741. SshTemplate: sshTemplate,
  742. }, nil
  743. case *provisioner.OIDC:
  744. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  745. if err != nil {
  746. return nil, err
  747. }
  748. return &linkedca.Provisioner{
  749. Id: p.ID,
  750. Type: linkedca.Provisioner_OIDC,
  751. Name: p.GetName(),
  752. Details: &linkedca.ProvisionerDetails{
  753. Data: &linkedca.ProvisionerDetails_OIDC{
  754. OIDC: &linkedca.OIDCProvisioner{
  755. ClientId: p.ClientID,
  756. ClientSecret: p.ClientSecret,
  757. ConfigurationEndpoint: p.ConfigurationEndpoint,
  758. Admins: p.Admins,
  759. Domains: p.Domains,
  760. Groups: p.Groups,
  761. ListenAddress: p.ListenAddress,
  762. TenantId: p.TenantID,
  763. },
  764. },
  765. },
  766. Claims: claimsToLinkedca(p.Claims),
  767. X509Template: x509Template,
  768. SshTemplate: sshTemplate,
  769. }, nil
  770. case *provisioner.GCP:
  771. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  772. if err != nil {
  773. return nil, err
  774. }
  775. return &linkedca.Provisioner{
  776. Id: p.ID,
  777. Type: linkedca.Provisioner_GCP,
  778. Name: p.GetName(),
  779. Details: &linkedca.ProvisionerDetails{
  780. Data: &linkedca.ProvisionerDetails_GCP{
  781. GCP: &linkedca.GCPProvisioner{
  782. ServiceAccounts: p.ServiceAccounts,
  783. ProjectIds: p.ProjectIDs,
  784. DisableCustomSans: p.DisableCustomSANs,
  785. DisableTrustOnFirstUse: p.DisableTrustOnFirstUse,
  786. InstanceAge: p.InstanceAge.String(),
  787. },
  788. },
  789. },
  790. Claims: claimsToLinkedca(p.Claims),
  791. X509Template: x509Template,
  792. SshTemplate: sshTemplate,
  793. }, nil
  794. case *provisioner.AWS:
  795. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  796. if err != nil {
  797. return nil, err
  798. }
  799. return &linkedca.Provisioner{
  800. Id: p.ID,
  801. Type: linkedca.Provisioner_AWS,
  802. Name: p.GetName(),
  803. Details: &linkedca.ProvisionerDetails{
  804. Data: &linkedca.ProvisionerDetails_AWS{
  805. AWS: &linkedca.AWSProvisioner{
  806. Accounts: p.Accounts,
  807. DisableCustomSans: p.DisableCustomSANs,
  808. DisableTrustOnFirstUse: p.DisableTrustOnFirstUse,
  809. InstanceAge: p.InstanceAge.String(),
  810. },
  811. },
  812. },
  813. Claims: claimsToLinkedca(p.Claims),
  814. X509Template: x509Template,
  815. SshTemplate: sshTemplate,
  816. }, nil
  817. case *provisioner.Azure:
  818. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  819. if err != nil {
  820. return nil, err
  821. }
  822. return &linkedca.Provisioner{
  823. Id: p.ID,
  824. Type: linkedca.Provisioner_AZURE,
  825. Name: p.GetName(),
  826. Details: &linkedca.ProvisionerDetails{
  827. Data: &linkedca.ProvisionerDetails_Azure{
  828. Azure: &linkedca.AzureProvisioner{
  829. TenantId: p.TenantID,
  830. ResourceGroups: p.ResourceGroups,
  831. SubscriptionIds: p.SubscriptionIDs,
  832. ObjectIds: p.ObjectIDs,
  833. Audience: p.Audience,
  834. DisableCustomSans: p.DisableCustomSANs,
  835. DisableTrustOnFirstUse: p.DisableTrustOnFirstUse,
  836. },
  837. },
  838. },
  839. Claims: claimsToLinkedca(p.Claims),
  840. X509Template: x509Template,
  841. SshTemplate: sshTemplate,
  842. }, nil
  843. case *provisioner.ACME:
  844. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  845. if err != nil {
  846. return nil, err
  847. }
  848. return &linkedca.Provisioner{
  849. Id: p.ID,
  850. Type: linkedca.Provisioner_ACME,
  851. Name: p.GetName(),
  852. Details: &linkedca.ProvisionerDetails{
  853. Data: &linkedca.ProvisionerDetails_ACME{
  854. ACME: &linkedca.ACMEProvisioner{
  855. ForceCn: p.ForceCN,
  856. },
  857. },
  858. },
  859. Claims: claimsToLinkedca(p.Claims),
  860. X509Template: x509Template,
  861. SshTemplate: sshTemplate,
  862. }, nil
  863. case *provisioner.X5C:
  864. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  865. if err != nil {
  866. return nil, err
  867. }
  868. return &linkedca.Provisioner{
  869. Id: p.ID,
  870. Type: linkedca.Provisioner_X5C,
  871. Name: p.GetName(),
  872. Details: &linkedca.ProvisionerDetails{
  873. Data: &linkedca.ProvisionerDetails_X5C{
  874. X5C: &linkedca.X5CProvisioner{
  875. Roots: provisionerPEMToLinkedca(p.Roots),
  876. },
  877. },
  878. },
  879. Claims: claimsToLinkedca(p.Claims),
  880. X509Template: x509Template,
  881. SshTemplate: sshTemplate,
  882. }, nil
  883. case *provisioner.K8sSA:
  884. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  885. if err != nil {
  886. return nil, err
  887. }
  888. return &linkedca.Provisioner{
  889. Id: p.ID,
  890. Type: linkedca.Provisioner_K8SSA,
  891. Name: p.GetName(),
  892. Details: &linkedca.ProvisionerDetails{
  893. Data: &linkedca.ProvisionerDetails_K8SSA{
  894. K8SSA: &linkedca.K8SSAProvisioner{
  895. PublicKeys: provisionerPEMToLinkedca(p.PubKeys),
  896. },
  897. },
  898. },
  899. Claims: claimsToLinkedca(p.Claims),
  900. X509Template: x509Template,
  901. SshTemplate: sshTemplate,
  902. }, nil
  903. case *provisioner.SSHPOP:
  904. return &linkedca.Provisioner{
  905. Id: p.ID,
  906. Type: linkedca.Provisioner_SSHPOP,
  907. Name: p.GetName(),
  908. Details: &linkedca.ProvisionerDetails{
  909. Data: &linkedca.ProvisionerDetails_SSHPOP{
  910. SSHPOP: &linkedca.SSHPOPProvisioner{},
  911. },
  912. },
  913. Claims: claimsToLinkedca(p.Claims),
  914. }, nil
  915. case *provisioner.SCEP:
  916. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  917. if err != nil {
  918. return nil, err
  919. }
  920. return &linkedca.Provisioner{
  921. Id: p.ID,
  922. Type: linkedca.Provisioner_SCEP,
  923. Name: p.GetName(),
  924. Details: &linkedca.ProvisionerDetails{
  925. Data: &linkedca.ProvisionerDetails_SCEP{
  926. SCEP: &linkedca.SCEPProvisioner{
  927. ForceCn: p.ForceCN,
  928. Challenge: p.GetChallengePassword(),
  929. Capabilities: p.Capabilities,
  930. MinimumPublicKeyLength: int32(p.MinimumPublicKeyLength),
  931. IncludeRoot: p.IncludeRoot,
  932. EncryptionAlgorithmIdentifier: int32(p.EncryptionAlgorithmIdentifier),
  933. },
  934. },
  935. },
  936. Claims: claimsToLinkedca(p.Claims),
  937. X509Template: x509Template,
  938. SshTemplate: sshTemplate,
  939. }, nil
  940. case *provisioner.Nebula:
  941. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  942. if err != nil {
  943. return nil, err
  944. }
  945. return &linkedca.Provisioner{
  946. Id: p.ID,
  947. Type: linkedca.Provisioner_NEBULA,
  948. Name: p.GetName(),
  949. Details: &linkedca.ProvisionerDetails{
  950. Data: &linkedca.ProvisionerDetails_Nebula{
  951. Nebula: &linkedca.NebulaProvisioner{
  952. Roots: provisionerPEMToLinkedca(p.Roots),
  953. },
  954. },
  955. },
  956. Claims: claimsToLinkedca(p.Claims),
  957. X509Template: x509Template,
  958. SshTemplate: sshTemplate,
  959. }, nil
  960. default:
  961. return nil, fmt.Errorf("provisioner %s not implemented", p.GetType())
  962. }
  963. }
  964. func parseInstanceAge(age string) (provisioner.Duration, error) {
  965. var instanceAge provisioner.Duration
  966. if age != "" {
  967. iap, err := provisioner.NewDuration(age)
  968. if err != nil {
  969. return instanceAge, err
  970. }
  971. instanceAge = *iap
  972. }
  973. return instanceAge, nil
  974. }