provisioners.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  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 a provisioner 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. if a.IsAdminAPIEnabled() {
  223. // Validate
  224. // - Check that there will be SUPER_ADMINs that remain after we
  225. // remove this provisioner.
  226. if a.IsAdminAPIEnabled() && a.admins.SuperCount() == a.admins.SuperCountByProvisioner(provName) {
  227. return admin.NewError(admin.ErrorBadRequestType,
  228. "cannot remove provisioner %s because no super admins will remain", provName)
  229. }
  230. // Delete all admins associated with the provisioner.
  231. admins, ok := a.admins.LoadByProvisioner(provName)
  232. if ok {
  233. for _, adm := range admins {
  234. if err := a.removeAdmin(ctx, adm.Id); err != nil {
  235. return admin.WrapErrorISE(err, "error deleting admin %s, as part of provisioner %s deletion", adm.Subject, provName)
  236. }
  237. }
  238. }
  239. }
  240. // Remove provisioner from authority caches.
  241. if err := a.provisioners.Remove(provID); err != nil {
  242. return admin.WrapErrorISE(err, "error removing provisioner from authority cache")
  243. }
  244. // Remove provisioner from database.
  245. if err := a.adminDB.DeleteProvisioner(ctx, provID); err != nil {
  246. if err := a.ReloadAdminResources(ctx); err != nil {
  247. return admin.WrapErrorISE(err, "error reloading admin resources on failed provisioner remove")
  248. }
  249. return admin.WrapErrorISE(err, "error deleting provisioner %s", provName)
  250. }
  251. return nil
  252. }
  253. // CreateFirstProvisioner creates and stores the first provisioner when using
  254. // admin database provisioner storage.
  255. func CreateFirstProvisioner(ctx context.Context, adminDB admin.DB, password string) (*linkedca.Provisioner, error) {
  256. if password == "" {
  257. pass, err := ui.PromptPasswordGenerate("Please enter the password to encrypt your first provisioner, leave empty and we'll generate one")
  258. if err != nil {
  259. return nil, err
  260. }
  261. password = string(pass)
  262. }
  263. jwk, jwe, err := jose.GenerateDefaultKeyPair([]byte(password))
  264. if err != nil {
  265. return nil, admin.WrapErrorISE(err, "error generating JWK key pair")
  266. }
  267. jwkPubBytes, err := jwk.MarshalJSON()
  268. if err != nil {
  269. return nil, admin.WrapErrorISE(err, "error marshaling JWK")
  270. }
  271. jwePrivStr, err := jwe.CompactSerialize()
  272. if err != nil {
  273. return nil, admin.WrapErrorISE(err, "error serializing JWE")
  274. }
  275. p := &linkedca.Provisioner{
  276. Name: "Admin JWK",
  277. Type: linkedca.Provisioner_JWK,
  278. Details: &linkedca.ProvisionerDetails{
  279. Data: &linkedca.ProvisionerDetails_JWK{
  280. JWK: &linkedca.JWKProvisioner{
  281. PublicKey: jwkPubBytes,
  282. EncryptedPrivateKey: []byte(jwePrivStr),
  283. },
  284. },
  285. },
  286. Claims: &linkedca.Claims{
  287. X509: &linkedca.X509Claims{
  288. Enabled: true,
  289. Durations: &linkedca.Durations{
  290. Default: "5m",
  291. },
  292. },
  293. },
  294. }
  295. if err := adminDB.CreateProvisioner(ctx, p); err != nil {
  296. return nil, admin.WrapErrorISE(err, "error creating provisioner")
  297. }
  298. return p, nil
  299. }
  300. // ValidateClaims validates the Claims type.
  301. func ValidateClaims(c *linkedca.Claims) error {
  302. if c == nil {
  303. return nil
  304. }
  305. if c.X509 != nil {
  306. if c.X509.Durations != nil {
  307. if err := ValidateDurations(c.X509.Durations); err != nil {
  308. return err
  309. }
  310. }
  311. }
  312. if c.Ssh != nil {
  313. if c.Ssh.UserDurations != nil {
  314. if err := ValidateDurations(c.Ssh.UserDurations); err != nil {
  315. return err
  316. }
  317. }
  318. if c.Ssh.HostDurations != nil {
  319. if err := ValidateDurations(c.Ssh.HostDurations); err != nil {
  320. return err
  321. }
  322. }
  323. }
  324. return nil
  325. }
  326. // ValidateDurations validates the Durations type.
  327. func ValidateDurations(d *linkedca.Durations) error {
  328. var (
  329. err error
  330. min, max, def *provisioner.Duration
  331. )
  332. if d.Min != "" {
  333. min, err = provisioner.NewDuration(d.Min)
  334. if err != nil {
  335. return admin.WrapError(admin.ErrorBadRequestType, err, "min duration '%s' is invalid", d.Min)
  336. }
  337. if min.Value() < 0 {
  338. return admin.WrapError(admin.ErrorBadRequestType, err, "min duration '%s' cannot be less than 0", d.Min)
  339. }
  340. }
  341. if d.Max != "" {
  342. max, err = provisioner.NewDuration(d.Max)
  343. if err != nil {
  344. return admin.WrapError(admin.ErrorBadRequestType, err, "max duration '%s' is invalid", d.Max)
  345. }
  346. if max.Value() < 0 {
  347. return admin.WrapError(admin.ErrorBadRequestType, err, "max duration '%s' cannot be less than 0", d.Max)
  348. }
  349. }
  350. if d.Default != "" {
  351. def, err = provisioner.NewDuration(d.Default)
  352. if err != nil {
  353. return admin.WrapError(admin.ErrorBadRequestType, err, "default duration '%s' is invalid", d.Default)
  354. }
  355. if def.Value() < 0 {
  356. return admin.WrapError(admin.ErrorBadRequestType, err, "default duration '%s' cannot be less than 0", d.Default)
  357. }
  358. }
  359. if d.Min != "" && d.Max != "" && min.Value() > max.Value() {
  360. return admin.NewError(admin.ErrorBadRequestType,
  361. "min duration '%s' cannot be greater than max duration '%s'", d.Min, d.Max)
  362. }
  363. if d.Min != "" && d.Default != "" && min.Value() > def.Value() {
  364. return admin.NewError(admin.ErrorBadRequestType,
  365. "min duration '%s' cannot be greater than default duration '%s'", d.Min, d.Default)
  366. }
  367. if d.Default != "" && d.Max != "" && min.Value() > def.Value() {
  368. return admin.NewError(admin.ErrorBadRequestType,
  369. "default duration '%s' cannot be greater than max duration '%s'", d.Default, d.Max)
  370. }
  371. return nil
  372. }
  373. func provisionerListToCertificates(l []*linkedca.Provisioner) (provisioner.List, error) {
  374. var nu provisioner.List
  375. for _, p := range l {
  376. certProv, err := ProvisionerToCertificates(p)
  377. if err != nil {
  378. return nil, err
  379. }
  380. nu = append(nu, certProv)
  381. }
  382. return nu, nil
  383. }
  384. func optionsToCertificates(p *linkedca.Provisioner) *provisioner.Options {
  385. ops := &provisioner.Options{
  386. X509: &provisioner.X509Options{},
  387. SSH: &provisioner.SSHOptions{},
  388. }
  389. if p.X509Template != nil {
  390. ops.X509.Template = string(p.X509Template.Template)
  391. ops.X509.TemplateData = p.X509Template.Data
  392. }
  393. if p.SshTemplate != nil {
  394. ops.SSH.Template = string(p.SshTemplate.Template)
  395. ops.SSH.TemplateData = p.SshTemplate.Data
  396. }
  397. if pol := p.GetPolicy(); pol != nil {
  398. if x := pol.GetX509(); x != nil {
  399. if allow := x.GetAllow(); allow != nil {
  400. ops.X509.AllowedNames = &policy.X509NameOptions{
  401. DNSDomains: allow.Dns,
  402. IPRanges: allow.Ips,
  403. EmailAddresses: allow.Emails,
  404. URIDomains: allow.Uris,
  405. }
  406. }
  407. if deny := x.GetDeny(); deny != nil {
  408. ops.X509.DeniedNames = &policy.X509NameOptions{
  409. DNSDomains: deny.Dns,
  410. IPRanges: deny.Ips,
  411. EmailAddresses: deny.Emails,
  412. URIDomains: deny.Uris,
  413. }
  414. }
  415. }
  416. if ssh := pol.GetSsh(); ssh != nil {
  417. if host := ssh.GetHost(); host != nil {
  418. ops.SSH.Host = &policy.SSHHostCertificateOptions{}
  419. if allow := host.GetAllow(); allow != nil {
  420. ops.SSH.Host.AllowedNames = &policy.SSHNameOptions{
  421. DNSDomains: allow.Dns,
  422. IPRanges: allow.Ips,
  423. Principals: allow.Principals,
  424. }
  425. }
  426. if deny := host.GetDeny(); deny != nil {
  427. ops.SSH.Host.DeniedNames = &policy.SSHNameOptions{
  428. DNSDomains: deny.Dns,
  429. IPRanges: deny.Ips,
  430. Principals: deny.Principals,
  431. }
  432. }
  433. }
  434. if user := ssh.GetUser(); user != nil {
  435. ops.SSH.User = &policy.SSHUserCertificateOptions{}
  436. if allow := user.GetAllow(); allow != nil {
  437. ops.SSH.User.AllowedNames = &policy.SSHNameOptions{
  438. EmailAddresses: allow.Emails,
  439. Principals: allow.Principals,
  440. }
  441. }
  442. if deny := user.GetDeny(); deny != nil {
  443. ops.SSH.User.DeniedNames = &policy.SSHNameOptions{
  444. EmailAddresses: deny.Emails,
  445. Principals: deny.Principals,
  446. }
  447. }
  448. }
  449. }
  450. }
  451. return ops
  452. }
  453. func durationsToCertificates(d *linkedca.Durations) (min, max, def *provisioner.Duration, err error) {
  454. if len(d.Min) > 0 {
  455. min, err = provisioner.NewDuration(d.Min)
  456. if err != nil {
  457. return nil, nil, nil, admin.WrapErrorISE(err, "error parsing minimum duration '%s'", d.Min)
  458. }
  459. }
  460. if len(d.Max) > 0 {
  461. max, err = provisioner.NewDuration(d.Max)
  462. if err != nil {
  463. return nil, nil, nil, admin.WrapErrorISE(err, "error parsing maximum duration '%s'", d.Max)
  464. }
  465. }
  466. if len(d.Default) > 0 {
  467. def, err = provisioner.NewDuration(d.Default)
  468. if err != nil {
  469. return nil, nil, nil, admin.WrapErrorISE(err, "error parsing default duration '%s'", d.Default)
  470. }
  471. }
  472. return
  473. }
  474. func durationsToLinkedca(d *provisioner.Duration) string {
  475. if d == nil {
  476. return ""
  477. }
  478. return d.Duration.String()
  479. }
  480. // claimsToCertificates converts the linkedca provisioner claims type to the
  481. // certifictes claims type.
  482. func claimsToCertificates(c *linkedca.Claims) (*provisioner.Claims, error) {
  483. if c == nil {
  484. return nil, nil
  485. }
  486. pc := &provisioner.Claims{
  487. DisableRenewal: &c.DisableRenewal,
  488. AllowRenewalAfterExpiry: &c.AllowRenewalAfterExpiry,
  489. }
  490. var err error
  491. if xc := c.X509; xc != nil {
  492. if d := xc.Durations; d != nil {
  493. pc.MinTLSDur, pc.MaxTLSDur, pc.DefaultTLSDur, err = durationsToCertificates(d)
  494. if err != nil {
  495. return nil, err
  496. }
  497. }
  498. }
  499. if sc := c.Ssh; sc != nil {
  500. pc.EnableSSHCA = &sc.Enabled
  501. if d := sc.UserDurations; d != nil {
  502. pc.MinUserSSHDur, pc.MaxUserSSHDur, pc.DefaultUserSSHDur, err = durationsToCertificates(d)
  503. if err != nil {
  504. return nil, err
  505. }
  506. }
  507. if d := sc.HostDurations; d != nil {
  508. pc.MinHostSSHDur, pc.MaxHostSSHDur, pc.DefaultHostSSHDur, err = durationsToCertificates(d)
  509. if err != nil {
  510. return nil, err
  511. }
  512. }
  513. }
  514. return pc, nil
  515. }
  516. func claimsToLinkedca(c *provisioner.Claims) *linkedca.Claims {
  517. if c == nil {
  518. return nil
  519. }
  520. disableRenewal := config.DefaultDisableRenewal
  521. allowRenewalAfterExpiry := config.DefaultAllowRenewalAfterExpiry
  522. if c.DisableRenewal != nil {
  523. disableRenewal = *c.DisableRenewal
  524. }
  525. if c.AllowRenewalAfterExpiry != nil {
  526. allowRenewalAfterExpiry = *c.AllowRenewalAfterExpiry
  527. }
  528. lc := &linkedca.Claims{
  529. DisableRenewal: disableRenewal,
  530. AllowRenewalAfterExpiry: allowRenewalAfterExpiry,
  531. }
  532. if c.DefaultTLSDur != nil || c.MinTLSDur != nil || c.MaxTLSDur != nil {
  533. lc.X509 = &linkedca.X509Claims{
  534. Enabled: true,
  535. Durations: &linkedca.Durations{
  536. Default: durationsToLinkedca(c.DefaultTLSDur),
  537. Min: durationsToLinkedca(c.MinTLSDur),
  538. Max: durationsToLinkedca(c.MaxTLSDur),
  539. },
  540. }
  541. }
  542. if c.EnableSSHCA != nil && *c.EnableSSHCA {
  543. lc.Ssh = &linkedca.SSHClaims{
  544. Enabled: true,
  545. }
  546. if c.DefaultUserSSHDur != nil || c.MinUserSSHDur != nil || c.MaxUserSSHDur != nil {
  547. lc.Ssh.UserDurations = &linkedca.Durations{
  548. Default: durationsToLinkedca(c.DefaultUserSSHDur),
  549. Min: durationsToLinkedca(c.MinUserSSHDur),
  550. Max: durationsToLinkedca(c.MaxUserSSHDur),
  551. }
  552. }
  553. if c.DefaultHostSSHDur != nil || c.MinHostSSHDur != nil || c.MaxHostSSHDur != nil {
  554. lc.Ssh.HostDurations = &linkedca.Durations{
  555. Default: durationsToLinkedca(c.DefaultHostSSHDur),
  556. Min: durationsToLinkedca(c.MinHostSSHDur),
  557. Max: durationsToLinkedca(c.MaxHostSSHDur),
  558. }
  559. }
  560. }
  561. return lc
  562. }
  563. func provisionerOptionsToLinkedca(p *provisioner.Options) (*linkedca.Template, *linkedca.Template, error) {
  564. var err error
  565. var x509Template, sshTemplate *linkedca.Template
  566. if p == nil {
  567. return nil, nil, nil
  568. }
  569. if p.X509 != nil && p.X509.HasTemplate() {
  570. x509Template = &linkedca.Template{
  571. Template: nil,
  572. Data: nil,
  573. }
  574. if p.X509.Template != "" {
  575. x509Template.Template = []byte(p.SSH.Template)
  576. } else if p.X509.TemplateFile != "" {
  577. filename := step.Abs(p.X509.TemplateFile)
  578. if x509Template.Template, err = os.ReadFile(filename); err != nil {
  579. return nil, nil, errors.Wrap(err, "error reading x509 template")
  580. }
  581. }
  582. }
  583. if p.SSH != nil && p.SSH.HasTemplate() {
  584. sshTemplate = &linkedca.Template{
  585. Template: nil,
  586. Data: nil,
  587. }
  588. if p.SSH.Template != "" {
  589. sshTemplate.Template = []byte(p.SSH.Template)
  590. } else if p.SSH.TemplateFile != "" {
  591. filename := step.Abs(p.SSH.TemplateFile)
  592. if sshTemplate.Template, err = os.ReadFile(filename); err != nil {
  593. return nil, nil, errors.Wrap(err, "error reading ssh template")
  594. }
  595. }
  596. }
  597. return x509Template, sshTemplate, nil
  598. }
  599. func provisionerPEMToLinkedca(b []byte) [][]byte {
  600. var roots [][]byte
  601. var block *pem.Block
  602. for {
  603. if block, b = pem.Decode(b); block == nil {
  604. break
  605. }
  606. roots = append(roots, pem.EncodeToMemory(block))
  607. }
  608. return roots
  609. }
  610. // ProvisionerToCertificates converts the linkedca provisioner type to the certificates provisioner
  611. // interface.
  612. func ProvisionerToCertificates(p *linkedca.Provisioner) (provisioner.Interface, error) {
  613. claims, err := claimsToCertificates(p.Claims)
  614. if err != nil {
  615. return nil, err
  616. }
  617. details := p.Details.GetData()
  618. if details == nil {
  619. return nil, errors.New("provisioner does not have any details")
  620. }
  621. options := optionsToCertificates(p)
  622. switch d := details.(type) {
  623. case *linkedca.ProvisionerDetails_JWK:
  624. jwk := new(jose.JSONWebKey)
  625. if err := json.Unmarshal(d.JWK.PublicKey, &jwk); err != nil {
  626. return nil, errors.Wrap(err, "error unmarshaling public key")
  627. }
  628. return &provisioner.JWK{
  629. ID: p.Id,
  630. Type: p.Type.String(),
  631. Name: p.Name,
  632. Key: jwk,
  633. EncryptedKey: string(d.JWK.EncryptedPrivateKey),
  634. Claims: claims,
  635. Options: options,
  636. }, nil
  637. case *linkedca.ProvisionerDetails_X5C:
  638. var roots []byte
  639. for i, root := range d.X5C.GetRoots() {
  640. if i > 0 {
  641. roots = append(roots, '\n')
  642. }
  643. roots = append(roots, root...)
  644. }
  645. return &provisioner.X5C{
  646. ID: p.Id,
  647. Type: p.Type.String(),
  648. Name: p.Name,
  649. Roots: roots,
  650. Claims: claims,
  651. Options: options,
  652. }, nil
  653. case *linkedca.ProvisionerDetails_K8SSA:
  654. var publicKeys []byte
  655. for i, k := range d.K8SSA.GetPublicKeys() {
  656. if i > 0 {
  657. publicKeys = append(publicKeys, '\n')
  658. }
  659. publicKeys = append(publicKeys, k...)
  660. }
  661. return &provisioner.K8sSA{
  662. ID: p.Id,
  663. Type: p.Type.String(),
  664. Name: p.Name,
  665. PubKeys: publicKeys,
  666. Claims: claims,
  667. Options: options,
  668. }, nil
  669. case *linkedca.ProvisionerDetails_SSHPOP:
  670. return &provisioner.SSHPOP{
  671. ID: p.Id,
  672. Type: p.Type.String(),
  673. Name: p.Name,
  674. Claims: claims,
  675. }, nil
  676. case *linkedca.ProvisionerDetails_ACME:
  677. cfg := d.ACME
  678. return &provisioner.ACME{
  679. ID: p.Id,
  680. Type: p.Type.String(),
  681. Name: p.Name,
  682. ForceCN: cfg.ForceCn,
  683. RequireEAB: cfg.RequireEab,
  684. Challenges: challengesToCertificates(cfg.Challenges),
  685. Claims: claims,
  686. Options: options,
  687. }, nil
  688. case *linkedca.ProvisionerDetails_OIDC:
  689. cfg := d.OIDC
  690. return &provisioner.OIDC{
  691. ID: p.Id,
  692. Type: p.Type.String(),
  693. Name: p.Name,
  694. TenantID: cfg.TenantId,
  695. ClientID: cfg.ClientId,
  696. ClientSecret: cfg.ClientSecret,
  697. ConfigurationEndpoint: cfg.ConfigurationEndpoint,
  698. Admins: cfg.Admins,
  699. Domains: cfg.Domains,
  700. Groups: cfg.Groups,
  701. ListenAddress: cfg.ListenAddress,
  702. Claims: claims,
  703. Options: options,
  704. }, nil
  705. case *linkedca.ProvisionerDetails_AWS:
  706. cfg := d.AWS
  707. instanceAge, err := parseInstanceAge(cfg.InstanceAge)
  708. if err != nil {
  709. return nil, err
  710. }
  711. return &provisioner.AWS{
  712. ID: p.Id,
  713. Type: p.Type.String(),
  714. Name: p.Name,
  715. Accounts: cfg.Accounts,
  716. DisableCustomSANs: cfg.DisableCustomSans,
  717. DisableTrustOnFirstUse: cfg.DisableTrustOnFirstUse,
  718. InstanceAge: instanceAge,
  719. Claims: claims,
  720. Options: options,
  721. }, nil
  722. case *linkedca.ProvisionerDetails_GCP:
  723. cfg := d.GCP
  724. instanceAge, err := parseInstanceAge(cfg.InstanceAge)
  725. if err != nil {
  726. return nil, err
  727. }
  728. return &provisioner.GCP{
  729. ID: p.Id,
  730. Type: p.Type.String(),
  731. Name: p.Name,
  732. ServiceAccounts: cfg.ServiceAccounts,
  733. ProjectIDs: cfg.ProjectIds,
  734. DisableCustomSANs: cfg.DisableCustomSans,
  735. DisableTrustOnFirstUse: cfg.DisableTrustOnFirstUse,
  736. InstanceAge: instanceAge,
  737. Claims: claims,
  738. Options: options,
  739. }, nil
  740. case *linkedca.ProvisionerDetails_Azure:
  741. cfg := d.Azure
  742. return &provisioner.Azure{
  743. ID: p.Id,
  744. Type: p.Type.String(),
  745. Name: p.Name,
  746. TenantID: cfg.TenantId,
  747. ResourceGroups: cfg.ResourceGroups,
  748. SubscriptionIDs: cfg.SubscriptionIds,
  749. ObjectIDs: cfg.ObjectIds,
  750. Audience: cfg.Audience,
  751. DisableCustomSANs: cfg.DisableCustomSans,
  752. DisableTrustOnFirstUse: cfg.DisableTrustOnFirstUse,
  753. Claims: claims,
  754. Options: options,
  755. }, nil
  756. case *linkedca.ProvisionerDetails_SCEP:
  757. cfg := d.SCEP
  758. return &provisioner.SCEP{
  759. ID: p.Id,
  760. Type: p.Type.String(),
  761. Name: p.Name,
  762. ForceCN: cfg.ForceCn,
  763. ChallengePassword: cfg.Challenge,
  764. Capabilities: cfg.Capabilities,
  765. IncludeRoot: cfg.IncludeRoot,
  766. MinimumPublicKeyLength: int(cfg.MinimumPublicKeyLength),
  767. EncryptionAlgorithmIdentifier: int(cfg.EncryptionAlgorithmIdentifier),
  768. Claims: claims,
  769. Options: options,
  770. }, nil
  771. case *linkedca.ProvisionerDetails_Nebula:
  772. var roots []byte
  773. for i, root := range d.Nebula.GetRoots() {
  774. if i > 0 && !bytes.HasSuffix(root, []byte{'\n'}) {
  775. roots = append(roots, '\n')
  776. }
  777. roots = append(roots, root...)
  778. }
  779. return &provisioner.Nebula{
  780. ID: p.Id,
  781. Type: p.Type.String(),
  782. Name: p.Name,
  783. Roots: roots,
  784. Claims: claims,
  785. Options: options,
  786. }, nil
  787. default:
  788. return nil, fmt.Errorf("provisioner %s not implemented", p.Type)
  789. }
  790. }
  791. // ProvisionerToLinkedca converts a provisioner.Interface to a
  792. // linkedca.Provisioner type.
  793. func ProvisionerToLinkedca(p provisioner.Interface) (*linkedca.Provisioner, error) {
  794. switch p := p.(type) {
  795. case *provisioner.JWK:
  796. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  797. if err != nil {
  798. return nil, err
  799. }
  800. publicKey, err := json.Marshal(p.Key)
  801. if err != nil {
  802. return nil, errors.Wrap(err, "error marshaling key")
  803. }
  804. return &linkedca.Provisioner{
  805. Id: p.ID,
  806. Type: linkedca.Provisioner_JWK,
  807. Name: p.GetName(),
  808. Details: &linkedca.ProvisionerDetails{
  809. Data: &linkedca.ProvisionerDetails_JWK{
  810. JWK: &linkedca.JWKProvisioner{
  811. PublicKey: publicKey,
  812. EncryptedPrivateKey: []byte(p.EncryptedKey),
  813. },
  814. },
  815. },
  816. Claims: claimsToLinkedca(p.Claims),
  817. X509Template: x509Template,
  818. SshTemplate: sshTemplate,
  819. }, nil
  820. case *provisioner.OIDC:
  821. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  822. if err != nil {
  823. return nil, err
  824. }
  825. return &linkedca.Provisioner{
  826. Id: p.ID,
  827. Type: linkedca.Provisioner_OIDC,
  828. Name: p.GetName(),
  829. Details: &linkedca.ProvisionerDetails{
  830. Data: &linkedca.ProvisionerDetails_OIDC{
  831. OIDC: &linkedca.OIDCProvisioner{
  832. ClientId: p.ClientID,
  833. ClientSecret: p.ClientSecret,
  834. ConfigurationEndpoint: p.ConfigurationEndpoint,
  835. Admins: p.Admins,
  836. Domains: p.Domains,
  837. Groups: p.Groups,
  838. ListenAddress: p.ListenAddress,
  839. TenantId: p.TenantID,
  840. },
  841. },
  842. },
  843. Claims: claimsToLinkedca(p.Claims),
  844. X509Template: x509Template,
  845. SshTemplate: sshTemplate,
  846. }, nil
  847. case *provisioner.GCP:
  848. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  849. if err != nil {
  850. return nil, err
  851. }
  852. return &linkedca.Provisioner{
  853. Id: p.ID,
  854. Type: linkedca.Provisioner_GCP,
  855. Name: p.GetName(),
  856. Details: &linkedca.ProvisionerDetails{
  857. Data: &linkedca.ProvisionerDetails_GCP{
  858. GCP: &linkedca.GCPProvisioner{
  859. ServiceAccounts: p.ServiceAccounts,
  860. ProjectIds: p.ProjectIDs,
  861. DisableCustomSans: p.DisableCustomSANs,
  862. DisableTrustOnFirstUse: p.DisableTrustOnFirstUse,
  863. InstanceAge: p.InstanceAge.String(),
  864. },
  865. },
  866. },
  867. Claims: claimsToLinkedca(p.Claims),
  868. X509Template: x509Template,
  869. SshTemplate: sshTemplate,
  870. }, nil
  871. case *provisioner.AWS:
  872. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  873. if err != nil {
  874. return nil, err
  875. }
  876. return &linkedca.Provisioner{
  877. Id: p.ID,
  878. Type: linkedca.Provisioner_AWS,
  879. Name: p.GetName(),
  880. Details: &linkedca.ProvisionerDetails{
  881. Data: &linkedca.ProvisionerDetails_AWS{
  882. AWS: &linkedca.AWSProvisioner{
  883. Accounts: p.Accounts,
  884. DisableCustomSans: p.DisableCustomSANs,
  885. DisableTrustOnFirstUse: p.DisableTrustOnFirstUse,
  886. InstanceAge: p.InstanceAge.String(),
  887. },
  888. },
  889. },
  890. Claims: claimsToLinkedca(p.Claims),
  891. X509Template: x509Template,
  892. SshTemplate: sshTemplate,
  893. }, nil
  894. case *provisioner.Azure:
  895. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  896. if err != nil {
  897. return nil, err
  898. }
  899. return &linkedca.Provisioner{
  900. Id: p.ID,
  901. Type: linkedca.Provisioner_AZURE,
  902. Name: p.GetName(),
  903. Details: &linkedca.ProvisionerDetails{
  904. Data: &linkedca.ProvisionerDetails_Azure{
  905. Azure: &linkedca.AzureProvisioner{
  906. TenantId: p.TenantID,
  907. ResourceGroups: p.ResourceGroups,
  908. SubscriptionIds: p.SubscriptionIDs,
  909. ObjectIds: p.ObjectIDs,
  910. Audience: p.Audience,
  911. DisableCustomSans: p.DisableCustomSANs,
  912. DisableTrustOnFirstUse: p.DisableTrustOnFirstUse,
  913. },
  914. },
  915. },
  916. Claims: claimsToLinkedca(p.Claims),
  917. X509Template: x509Template,
  918. SshTemplate: sshTemplate,
  919. }, nil
  920. case *provisioner.ACME:
  921. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  922. if err != nil {
  923. return nil, err
  924. }
  925. return &linkedca.Provisioner{
  926. Id: p.ID,
  927. Type: linkedca.Provisioner_ACME,
  928. Name: p.GetName(),
  929. Details: &linkedca.ProvisionerDetails{
  930. Data: &linkedca.ProvisionerDetails_ACME{
  931. ACME: &linkedca.ACMEProvisioner{
  932. ForceCn: p.ForceCN,
  933. Challenges: challengesToLinkedca(p.Challenges),
  934. },
  935. },
  936. },
  937. Claims: claimsToLinkedca(p.Claims),
  938. X509Template: x509Template,
  939. SshTemplate: sshTemplate,
  940. }, nil
  941. case *provisioner.X5C:
  942. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  943. if err != nil {
  944. return nil, err
  945. }
  946. return &linkedca.Provisioner{
  947. Id: p.ID,
  948. Type: linkedca.Provisioner_X5C,
  949. Name: p.GetName(),
  950. Details: &linkedca.ProvisionerDetails{
  951. Data: &linkedca.ProvisionerDetails_X5C{
  952. X5C: &linkedca.X5CProvisioner{
  953. Roots: provisionerPEMToLinkedca(p.Roots),
  954. },
  955. },
  956. },
  957. Claims: claimsToLinkedca(p.Claims),
  958. X509Template: x509Template,
  959. SshTemplate: sshTemplate,
  960. }, nil
  961. case *provisioner.K8sSA:
  962. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  963. if err != nil {
  964. return nil, err
  965. }
  966. return &linkedca.Provisioner{
  967. Id: p.ID,
  968. Type: linkedca.Provisioner_K8SSA,
  969. Name: p.GetName(),
  970. Details: &linkedca.ProvisionerDetails{
  971. Data: &linkedca.ProvisionerDetails_K8SSA{
  972. K8SSA: &linkedca.K8SSAProvisioner{
  973. PublicKeys: provisionerPEMToLinkedca(p.PubKeys),
  974. },
  975. },
  976. },
  977. Claims: claimsToLinkedca(p.Claims),
  978. X509Template: x509Template,
  979. SshTemplate: sshTemplate,
  980. }, nil
  981. case *provisioner.SSHPOP:
  982. return &linkedca.Provisioner{
  983. Id: p.ID,
  984. Type: linkedca.Provisioner_SSHPOP,
  985. Name: p.GetName(),
  986. Details: &linkedca.ProvisionerDetails{
  987. Data: &linkedca.ProvisionerDetails_SSHPOP{
  988. SSHPOP: &linkedca.SSHPOPProvisioner{},
  989. },
  990. },
  991. Claims: claimsToLinkedca(p.Claims),
  992. }, nil
  993. case *provisioner.SCEP:
  994. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  995. if err != nil {
  996. return nil, err
  997. }
  998. return &linkedca.Provisioner{
  999. Id: p.ID,
  1000. Type: linkedca.Provisioner_SCEP,
  1001. Name: p.GetName(),
  1002. Details: &linkedca.ProvisionerDetails{
  1003. Data: &linkedca.ProvisionerDetails_SCEP{
  1004. SCEP: &linkedca.SCEPProvisioner{
  1005. ForceCn: p.ForceCN,
  1006. Challenge: p.GetChallengePassword(),
  1007. Capabilities: p.Capabilities,
  1008. MinimumPublicKeyLength: int32(p.MinimumPublicKeyLength),
  1009. IncludeRoot: p.IncludeRoot,
  1010. EncryptionAlgorithmIdentifier: int32(p.EncryptionAlgorithmIdentifier),
  1011. },
  1012. },
  1013. },
  1014. Claims: claimsToLinkedca(p.Claims),
  1015. X509Template: x509Template,
  1016. SshTemplate: sshTemplate,
  1017. }, nil
  1018. case *provisioner.Nebula:
  1019. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  1020. if err != nil {
  1021. return nil, err
  1022. }
  1023. return &linkedca.Provisioner{
  1024. Id: p.ID,
  1025. Type: linkedca.Provisioner_NEBULA,
  1026. Name: p.GetName(),
  1027. Details: &linkedca.ProvisionerDetails{
  1028. Data: &linkedca.ProvisionerDetails_Nebula{
  1029. Nebula: &linkedca.NebulaProvisioner{
  1030. Roots: provisionerPEMToLinkedca(p.Roots),
  1031. },
  1032. },
  1033. },
  1034. Claims: claimsToLinkedca(p.Claims),
  1035. X509Template: x509Template,
  1036. SshTemplate: sshTemplate,
  1037. }, nil
  1038. default:
  1039. return nil, fmt.Errorf("provisioner %s not implemented", p.GetType())
  1040. }
  1041. }
  1042. func parseInstanceAge(age string) (provisioner.Duration, error) {
  1043. var instanceAge provisioner.Duration
  1044. if age != "" {
  1045. iap, err := provisioner.NewDuration(age)
  1046. if err != nil {
  1047. return instanceAge, err
  1048. }
  1049. instanceAge = *iap
  1050. }
  1051. return instanceAge, nil
  1052. }
  1053. func challengesToCertificates(challenges []linkedca.ACMEProvisioner_ChallengeType) []string {
  1054. ret := make([]string, len(challenges))
  1055. for i, ch := range challenges {
  1056. switch ch {
  1057. case linkedca.ACMEProvisioner_HTTP_01:
  1058. ret[i] = "http-01"
  1059. case linkedca.ACMEProvisioner_DNS_01:
  1060. ret[i] = "dns-01"
  1061. case linkedca.ACMEProvisioner_TLS_ALPN_O1:
  1062. ret[i] = "tls-alpn-01"
  1063. case linkedca.ACMEProvisioner_DEVICE_ATTEST_01:
  1064. ret[i] = "device-attest-01"
  1065. default:
  1066. ret[i] = "unknown"
  1067. }
  1068. }
  1069. return ret
  1070. }
  1071. func challengesToLinkedca(challenges []string) []linkedca.ACMEProvisioner_ChallengeType {
  1072. ret := make([]linkedca.ACMEProvisioner_ChallengeType, len(challenges))
  1073. for i, ch := range challenges {
  1074. switch ch {
  1075. case "http-01":
  1076. ret[i] = linkedca.ACMEProvisioner_HTTP_01
  1077. case "dns-01":
  1078. ret[i] = linkedca.ACMEProvisioner_DNS_01
  1079. case "tls-alpn-01":
  1080. ret[i] = linkedca.ACMEProvisioner_TLS_ALPN_O1
  1081. case "device-attest-01":
  1082. ret[i] = linkedca.ACMEProvisioner_DEVICE_ATTEST_01
  1083. default:
  1084. ret[i] = linkedca.ACMEProvisioner_UNKNOWN
  1085. }
  1086. }
  1087. return ret
  1088. }