provisioners.go 33 KB

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