provisioners.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  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. Claims: claims,
  685. Options: options,
  686. }, nil
  687. case *linkedca.ProvisionerDetails_OIDC:
  688. cfg := d.OIDC
  689. return &provisioner.OIDC{
  690. ID: p.Id,
  691. Type: p.Type.String(),
  692. Name: p.Name,
  693. TenantID: cfg.TenantId,
  694. ClientID: cfg.ClientId,
  695. ClientSecret: cfg.ClientSecret,
  696. ConfigurationEndpoint: cfg.ConfigurationEndpoint,
  697. Admins: cfg.Admins,
  698. Domains: cfg.Domains,
  699. Groups: cfg.Groups,
  700. ListenAddress: cfg.ListenAddress,
  701. Claims: claims,
  702. Options: options,
  703. }, nil
  704. case *linkedca.ProvisionerDetails_AWS:
  705. cfg := d.AWS
  706. instanceAge, err := parseInstanceAge(cfg.InstanceAge)
  707. if err != nil {
  708. return nil, err
  709. }
  710. return &provisioner.AWS{
  711. ID: p.Id,
  712. Type: p.Type.String(),
  713. Name: p.Name,
  714. Accounts: cfg.Accounts,
  715. DisableCustomSANs: cfg.DisableCustomSans,
  716. DisableTrustOnFirstUse: cfg.DisableTrustOnFirstUse,
  717. InstanceAge: instanceAge,
  718. Claims: claims,
  719. Options: options,
  720. }, nil
  721. case *linkedca.ProvisionerDetails_GCP:
  722. cfg := d.GCP
  723. instanceAge, err := parseInstanceAge(cfg.InstanceAge)
  724. if err != nil {
  725. return nil, err
  726. }
  727. return &provisioner.GCP{
  728. ID: p.Id,
  729. Type: p.Type.String(),
  730. Name: p.Name,
  731. ServiceAccounts: cfg.ServiceAccounts,
  732. ProjectIDs: cfg.ProjectIds,
  733. DisableCustomSANs: cfg.DisableCustomSans,
  734. DisableTrustOnFirstUse: cfg.DisableTrustOnFirstUse,
  735. InstanceAge: instanceAge,
  736. Claims: claims,
  737. Options: options,
  738. }, nil
  739. case *linkedca.ProvisionerDetails_Azure:
  740. cfg := d.Azure
  741. return &provisioner.Azure{
  742. ID: p.Id,
  743. Type: p.Type.String(),
  744. Name: p.Name,
  745. TenantID: cfg.TenantId,
  746. ResourceGroups: cfg.ResourceGroups,
  747. SubscriptionIDs: cfg.SubscriptionIds,
  748. ObjectIDs: cfg.ObjectIds,
  749. Audience: cfg.Audience,
  750. DisableCustomSANs: cfg.DisableCustomSans,
  751. DisableTrustOnFirstUse: cfg.DisableTrustOnFirstUse,
  752. Claims: claims,
  753. Options: options,
  754. }, nil
  755. case *linkedca.ProvisionerDetails_SCEP:
  756. cfg := d.SCEP
  757. return &provisioner.SCEP{
  758. ID: p.Id,
  759. Type: p.Type.String(),
  760. Name: p.Name,
  761. ForceCN: cfg.ForceCn,
  762. ChallengePassword: cfg.Challenge,
  763. Capabilities: cfg.Capabilities,
  764. IncludeRoot: cfg.IncludeRoot,
  765. MinimumPublicKeyLength: int(cfg.MinimumPublicKeyLength),
  766. EncryptionAlgorithmIdentifier: int(cfg.EncryptionAlgorithmIdentifier),
  767. Claims: claims,
  768. Options: options,
  769. }, nil
  770. case *linkedca.ProvisionerDetails_Nebula:
  771. var roots []byte
  772. for i, root := range d.Nebula.GetRoots() {
  773. if i > 0 && !bytes.HasSuffix(root, []byte{'\n'}) {
  774. roots = append(roots, '\n')
  775. }
  776. roots = append(roots, root...)
  777. }
  778. return &provisioner.Nebula{
  779. ID: p.Id,
  780. Type: p.Type.String(),
  781. Name: p.Name,
  782. Roots: roots,
  783. Claims: claims,
  784. Options: options,
  785. }, nil
  786. default:
  787. return nil, fmt.Errorf("provisioner %s not implemented", p.Type)
  788. }
  789. }
  790. // ProvisionerToLinkedca converts a provisioner.Interface to a
  791. // linkedca.Provisioner type.
  792. func ProvisionerToLinkedca(p provisioner.Interface) (*linkedca.Provisioner, error) {
  793. switch p := p.(type) {
  794. case *provisioner.JWK:
  795. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  796. if err != nil {
  797. return nil, err
  798. }
  799. publicKey, err := json.Marshal(p.Key)
  800. if err != nil {
  801. return nil, errors.Wrap(err, "error marshaling key")
  802. }
  803. return &linkedca.Provisioner{
  804. Id: p.ID,
  805. Type: linkedca.Provisioner_JWK,
  806. Name: p.GetName(),
  807. Details: &linkedca.ProvisionerDetails{
  808. Data: &linkedca.ProvisionerDetails_JWK{
  809. JWK: &linkedca.JWKProvisioner{
  810. PublicKey: publicKey,
  811. EncryptedPrivateKey: []byte(p.EncryptedKey),
  812. },
  813. },
  814. },
  815. Claims: claimsToLinkedca(p.Claims),
  816. X509Template: x509Template,
  817. SshTemplate: sshTemplate,
  818. }, nil
  819. case *provisioner.OIDC:
  820. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  821. if err != nil {
  822. return nil, err
  823. }
  824. return &linkedca.Provisioner{
  825. Id: p.ID,
  826. Type: linkedca.Provisioner_OIDC,
  827. Name: p.GetName(),
  828. Details: &linkedca.ProvisionerDetails{
  829. Data: &linkedca.ProvisionerDetails_OIDC{
  830. OIDC: &linkedca.OIDCProvisioner{
  831. ClientId: p.ClientID,
  832. ClientSecret: p.ClientSecret,
  833. ConfigurationEndpoint: p.ConfigurationEndpoint,
  834. Admins: p.Admins,
  835. Domains: p.Domains,
  836. Groups: p.Groups,
  837. ListenAddress: p.ListenAddress,
  838. TenantId: p.TenantID,
  839. },
  840. },
  841. },
  842. Claims: claimsToLinkedca(p.Claims),
  843. X509Template: x509Template,
  844. SshTemplate: sshTemplate,
  845. }, nil
  846. case *provisioner.GCP:
  847. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  848. if err != nil {
  849. return nil, err
  850. }
  851. return &linkedca.Provisioner{
  852. Id: p.ID,
  853. Type: linkedca.Provisioner_GCP,
  854. Name: p.GetName(),
  855. Details: &linkedca.ProvisionerDetails{
  856. Data: &linkedca.ProvisionerDetails_GCP{
  857. GCP: &linkedca.GCPProvisioner{
  858. ServiceAccounts: p.ServiceAccounts,
  859. ProjectIds: p.ProjectIDs,
  860. DisableCustomSans: p.DisableCustomSANs,
  861. DisableTrustOnFirstUse: p.DisableTrustOnFirstUse,
  862. InstanceAge: p.InstanceAge.String(),
  863. },
  864. },
  865. },
  866. Claims: claimsToLinkedca(p.Claims),
  867. X509Template: x509Template,
  868. SshTemplate: sshTemplate,
  869. }, nil
  870. case *provisioner.AWS:
  871. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  872. if err != nil {
  873. return nil, err
  874. }
  875. return &linkedca.Provisioner{
  876. Id: p.ID,
  877. Type: linkedca.Provisioner_AWS,
  878. Name: p.GetName(),
  879. Details: &linkedca.ProvisionerDetails{
  880. Data: &linkedca.ProvisionerDetails_AWS{
  881. AWS: &linkedca.AWSProvisioner{
  882. Accounts: p.Accounts,
  883. DisableCustomSans: p.DisableCustomSANs,
  884. DisableTrustOnFirstUse: p.DisableTrustOnFirstUse,
  885. InstanceAge: p.InstanceAge.String(),
  886. },
  887. },
  888. },
  889. Claims: claimsToLinkedca(p.Claims),
  890. X509Template: x509Template,
  891. SshTemplate: sshTemplate,
  892. }, nil
  893. case *provisioner.Azure:
  894. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  895. if err != nil {
  896. return nil, err
  897. }
  898. return &linkedca.Provisioner{
  899. Id: p.ID,
  900. Type: linkedca.Provisioner_AZURE,
  901. Name: p.GetName(),
  902. Details: &linkedca.ProvisionerDetails{
  903. Data: &linkedca.ProvisionerDetails_Azure{
  904. Azure: &linkedca.AzureProvisioner{
  905. TenantId: p.TenantID,
  906. ResourceGroups: p.ResourceGroups,
  907. SubscriptionIds: p.SubscriptionIDs,
  908. ObjectIds: p.ObjectIDs,
  909. Audience: p.Audience,
  910. DisableCustomSans: p.DisableCustomSANs,
  911. DisableTrustOnFirstUse: p.DisableTrustOnFirstUse,
  912. },
  913. },
  914. },
  915. Claims: claimsToLinkedca(p.Claims),
  916. X509Template: x509Template,
  917. SshTemplate: sshTemplate,
  918. }, nil
  919. case *provisioner.ACME:
  920. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  921. if err != nil {
  922. return nil, err
  923. }
  924. return &linkedca.Provisioner{
  925. Id: p.ID,
  926. Type: linkedca.Provisioner_ACME,
  927. Name: p.GetName(),
  928. Details: &linkedca.ProvisionerDetails{
  929. Data: &linkedca.ProvisionerDetails_ACME{
  930. ACME: &linkedca.ACMEProvisioner{
  931. ForceCn: p.ForceCN,
  932. },
  933. },
  934. },
  935. Claims: claimsToLinkedca(p.Claims),
  936. X509Template: x509Template,
  937. SshTemplate: sshTemplate,
  938. }, nil
  939. case *provisioner.X5C:
  940. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  941. if err != nil {
  942. return nil, err
  943. }
  944. return &linkedca.Provisioner{
  945. Id: p.ID,
  946. Type: linkedca.Provisioner_X5C,
  947. Name: p.GetName(),
  948. Details: &linkedca.ProvisionerDetails{
  949. Data: &linkedca.ProvisionerDetails_X5C{
  950. X5C: &linkedca.X5CProvisioner{
  951. Roots: provisionerPEMToLinkedca(p.Roots),
  952. },
  953. },
  954. },
  955. Claims: claimsToLinkedca(p.Claims),
  956. X509Template: x509Template,
  957. SshTemplate: sshTemplate,
  958. }, nil
  959. case *provisioner.K8sSA:
  960. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  961. if err != nil {
  962. return nil, err
  963. }
  964. return &linkedca.Provisioner{
  965. Id: p.ID,
  966. Type: linkedca.Provisioner_K8SSA,
  967. Name: p.GetName(),
  968. Details: &linkedca.ProvisionerDetails{
  969. Data: &linkedca.ProvisionerDetails_K8SSA{
  970. K8SSA: &linkedca.K8SSAProvisioner{
  971. PublicKeys: provisionerPEMToLinkedca(p.PubKeys),
  972. },
  973. },
  974. },
  975. Claims: claimsToLinkedca(p.Claims),
  976. X509Template: x509Template,
  977. SshTemplate: sshTemplate,
  978. }, nil
  979. case *provisioner.SSHPOP:
  980. return &linkedca.Provisioner{
  981. Id: p.ID,
  982. Type: linkedca.Provisioner_SSHPOP,
  983. Name: p.GetName(),
  984. Details: &linkedca.ProvisionerDetails{
  985. Data: &linkedca.ProvisionerDetails_SSHPOP{
  986. SSHPOP: &linkedca.SSHPOPProvisioner{},
  987. },
  988. },
  989. Claims: claimsToLinkedca(p.Claims),
  990. }, nil
  991. case *provisioner.SCEP:
  992. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  993. if err != nil {
  994. return nil, err
  995. }
  996. return &linkedca.Provisioner{
  997. Id: p.ID,
  998. Type: linkedca.Provisioner_SCEP,
  999. Name: p.GetName(),
  1000. Details: &linkedca.ProvisionerDetails{
  1001. Data: &linkedca.ProvisionerDetails_SCEP{
  1002. SCEP: &linkedca.SCEPProvisioner{
  1003. ForceCn: p.ForceCN,
  1004. Challenge: p.GetChallengePassword(),
  1005. Capabilities: p.Capabilities,
  1006. MinimumPublicKeyLength: int32(p.MinimumPublicKeyLength),
  1007. IncludeRoot: p.IncludeRoot,
  1008. EncryptionAlgorithmIdentifier: int32(p.EncryptionAlgorithmIdentifier),
  1009. },
  1010. },
  1011. },
  1012. Claims: claimsToLinkedca(p.Claims),
  1013. X509Template: x509Template,
  1014. SshTemplate: sshTemplate,
  1015. }, nil
  1016. case *provisioner.Nebula:
  1017. x509Template, sshTemplate, err := provisionerOptionsToLinkedca(p.Options)
  1018. if err != nil {
  1019. return nil, err
  1020. }
  1021. return &linkedca.Provisioner{
  1022. Id: p.ID,
  1023. Type: linkedca.Provisioner_NEBULA,
  1024. Name: p.GetName(),
  1025. Details: &linkedca.ProvisionerDetails{
  1026. Data: &linkedca.ProvisionerDetails_Nebula{
  1027. Nebula: &linkedca.NebulaProvisioner{
  1028. Roots: provisionerPEMToLinkedca(p.Roots),
  1029. },
  1030. },
  1031. },
  1032. Claims: claimsToLinkedca(p.Claims),
  1033. X509Template: x509Template,
  1034. SshTemplate: sshTemplate,
  1035. }, nil
  1036. default:
  1037. return nil, fmt.Errorf("provisioner %s not implemented", p.GetType())
  1038. }
  1039. }
  1040. func parseInstanceAge(age string) (provisioner.Duration, error) {
  1041. var instanceAge provisioner.Duration
  1042. if age != "" {
  1043. iap, err := provisioner.NewDuration(age)
  1044. if err != nil {
  1045. return instanceAge, err
  1046. }
  1047. instanceAge = *iap
  1048. }
  1049. return instanceAge, nil
  1050. }