provisioners.go 42 KB

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