4
0

provisioners.go 30 KB

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