provisioners.go 46 KB

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