provisioners.go 30 KB

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