provisioners.go 32 KB

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