provisioners.go 41 KB

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