provisioners.go 28 KB

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