provisioners.go 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380
  1. package authority
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/x509"
  6. "encoding/json"
  7. "encoding/pem"
  8. "fmt"
  9. "os"
  10. "github.com/pkg/errors"
  11. "go.step.sm/cli-utils/step"
  12. "go.step.sm/cli-utils/ui"
  13. "go.step.sm/crypto/jose"
  14. "go.step.sm/linkedca"
  15. "github.com/smallstep/certificates/authority/admin"
  16. "github.com/smallstep/certificates/authority/config"
  17. "github.com/smallstep/certificates/authority/policy"
  18. "github.com/smallstep/certificates/authority/provisioner"
  19. "github.com/smallstep/certificates/db"
  20. "github.com/smallstep/certificates/errs"
  21. )
  22. type raProvisioner interface {
  23. RAInfo() *provisioner.RAInfo
  24. }
  25. type attProvisioner interface {
  26. AttestationData() *provisioner.AttestationData
  27. }
  28. // wrapProvisioner wraps the given provisioner with RA information and
  29. // attestation data.
  30. func wrapProvisioner(p provisioner.Interface, attData *provisioner.AttestationData) *wrappedProvisioner {
  31. var raInfo *provisioner.RAInfo
  32. if rap, ok := p.(raProvisioner); ok {
  33. raInfo = rap.RAInfo()
  34. }
  35. return &wrappedProvisioner{
  36. Interface: p,
  37. attestationData: attData,
  38. raInfo: raInfo,
  39. }
  40. }
  41. // wrapRAProvisioner wraps the given provisioner with RA information.
  42. func wrapRAProvisioner(p provisioner.Interface, raInfo *provisioner.RAInfo) *wrappedProvisioner {
  43. return &wrappedProvisioner{
  44. Interface: p,
  45. raInfo: raInfo,
  46. }
  47. }
  48. // isRAProvisioner returns if the given provisioner is an RA provisioner.
  49. func isRAProvisioner(p provisioner.Interface) bool {
  50. if rap, ok := p.(raProvisioner); ok {
  51. return rap.RAInfo() != nil
  52. }
  53. return false
  54. }
  55. // wrappedProvisioner implements raProvisioner and attProvisioner.
  56. type wrappedProvisioner struct {
  57. provisioner.Interface
  58. attestationData *provisioner.AttestationData
  59. raInfo *provisioner.RAInfo
  60. }
  61. func (p *wrappedProvisioner) AttestationData() *provisioner.AttestationData {
  62. return p.attestationData
  63. }
  64. func (p *wrappedProvisioner) RAInfo() *provisioner.RAInfo {
  65. return p.raInfo
  66. }
  67. // GetEncryptedKey returns the JWE key corresponding to the given kid argument.
  68. func (a *Authority) GetEncryptedKey(kid string) (string, error) {
  69. a.adminMutex.RLock()
  70. defer a.adminMutex.RUnlock()
  71. key, ok := a.provisioners.LoadEncryptedKey(kid)
  72. if !ok {
  73. return "", errs.NotFound("encrypted key with kid %s was not found", kid)
  74. }
  75. return key, nil
  76. }
  77. // GetProvisioners returns a map listing each provisioner and the JWK Key Set
  78. // with their public keys.
  79. func (a *Authority) GetProvisioners(cursor string, limit int) (provisioner.List, string, error) {
  80. a.adminMutex.RLock()
  81. defer a.adminMutex.RUnlock()
  82. provisioners, nextCursor := a.provisioners.Find(cursor, limit)
  83. return provisioners, nextCursor, nil
  84. }
  85. // LoadProvisionerByCertificate returns an interface to the provisioner that
  86. // provisioned the certificate.
  87. func (a *Authority) LoadProvisionerByCertificate(crt *x509.Certificate) (provisioner.Interface, error) {
  88. a.adminMutex.RLock()
  89. defer a.adminMutex.RUnlock()
  90. if p, err := a.unsafeLoadProvisionerFromDatabase(crt); err == nil {
  91. return p, nil
  92. }
  93. return a.unsafeLoadProvisionerFromExtension(crt)
  94. }
  95. func (a *Authority) unsafeLoadProvisionerFromExtension(crt *x509.Certificate) (provisioner.Interface, error) {
  96. p, ok := a.provisioners.LoadByCertificate(crt)
  97. if !ok || p.GetType() == 0 {
  98. return nil, admin.NewError(admin.ErrorNotFoundType, "unable to load provisioner from certificate")
  99. }
  100. return p, nil
  101. }
  102. func (a *Authority) unsafeLoadProvisionerFromDatabase(crt *x509.Certificate) (provisioner.Interface, error) {
  103. // certificateDataGetter is an interface that can be used to retrieve the
  104. // provisioner from a db or a linked ca.
  105. type certificateDataGetter interface {
  106. GetCertificateData(string) (*db.CertificateData, error)
  107. }
  108. var err error
  109. var data *db.CertificateData
  110. if cdg, ok := a.adminDB.(certificateDataGetter); ok {
  111. data, err = cdg.GetCertificateData(crt.SerialNumber.String())
  112. } else if cdg, ok := a.db.(certificateDataGetter); ok {
  113. data, err = cdg.GetCertificateData(crt.SerialNumber.String())
  114. }
  115. if err == nil && data != nil && data.Provisioner != nil {
  116. if p, ok := a.provisioners.Load(data.Provisioner.ID); ok {
  117. if data.RaInfo != nil {
  118. return wrapRAProvisioner(p, data.RaInfo), nil
  119. }
  120. return p, nil
  121. }
  122. }
  123. return nil, admin.NewError(admin.ErrorNotFoundType, "unable to load provisioner from certificate")
  124. }
  125. // LoadProvisionerByToken returns an interface to the provisioner that
  126. // provisioned the token.
  127. func (a *Authority) LoadProvisionerByToken(token *jose.JSONWebToken, claims *jose.Claims) (provisioner.Interface, error) {
  128. a.adminMutex.RLock()
  129. defer a.adminMutex.RUnlock()
  130. p, ok := a.provisioners.LoadByToken(token, claims)
  131. if !ok {
  132. return nil, admin.NewError(admin.ErrorNotFoundType, "unable to load provisioner from token")
  133. }
  134. return p, nil
  135. }
  136. // LoadProvisionerByID returns an interface to the provisioner with the given ID.
  137. func (a *Authority) LoadProvisionerByID(id string) (provisioner.Interface, error) {
  138. a.adminMutex.RLock()
  139. defer a.adminMutex.RUnlock()
  140. p, ok := a.provisioners.Load(id)
  141. if !ok {
  142. return nil, admin.NewError(admin.ErrorNotFoundType, "provisioner %s not found", id)
  143. }
  144. return p, nil
  145. }
  146. // LoadProvisionerByName returns an interface to the provisioner with the given Name.
  147. func (a *Authority) LoadProvisionerByName(name string) (provisioner.Interface, error) {
  148. a.adminMutex.RLock()
  149. defer a.adminMutex.RUnlock()
  150. p, ok := a.provisioners.LoadByName(name)
  151. if !ok {
  152. return nil, admin.NewError(admin.ErrorNotFoundType, "provisioner %s not found", name)
  153. }
  154. return p, nil
  155. }
  156. func (a *Authority) generateProvisionerConfig(ctx context.Context) (provisioner.Config, error) {
  157. // Merge global and configuration claims
  158. claimer, err := provisioner.NewClaimer(a.config.AuthorityConfig.Claims, config.GlobalProvisionerClaims)
  159. if err != nil {
  160. return provisioner.Config{}, err
  161. }
  162. // TODO: should we also be combining the ssh federated roots here?
  163. // If we rotate ssh roots keys, sshpop provisioner will lose ability to
  164. // validate old SSH certificates, unless they are added as federated certs.
  165. sshKeys, err := a.GetSSHRoots(ctx)
  166. if err != nil {
  167. return provisioner.Config{}, err
  168. }
  169. return provisioner.Config{
  170. Claims: claimer.Claims(),
  171. Audiences: a.config.GetAudiences(),
  172. SSHKeys: &provisioner.SSHKeys{
  173. UserKeys: sshKeys.UserKeys,
  174. HostKeys: sshKeys.HostKeys,
  175. },
  176. GetIdentityFunc: a.getIdentityFunc,
  177. AuthorizeRenewFunc: a.authorizeRenewFunc,
  178. AuthorizeSSHRenewFunc: a.authorizeSSHRenewFunc,
  179. WebhookClient: a.webhookClient,
  180. SCEPKeyManager: a.scepKeyManager,
  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 %q", 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. minDur, maxDur, def *provisioner.Duration
  380. )
  381. if d.Min != "" {
  382. minDur, 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 minDur.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. maxDur, 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 maxDur.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 != "" && minDur.Value() > maxDur.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 != "" && minDur.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 != "" && minDur.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) (minDur, maxDur, def *provisioner.Duration, err error) {
  552. if d.Min != "" {
  553. minDur, 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 d.Max != "" {
  559. maxDur, 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 d.Default != "" {
  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. DisableSmallstepExtensions: &c.DisableSmallstepExtensions,
  589. }
  590. var err error
  591. if xc := c.X509; xc != nil {
  592. if d := xc.Durations; d != nil {
  593. pc.MinTLSDur, pc.MaxTLSDur, pc.DefaultTLSDur, err = durationsToCertificates(d)
  594. if err != nil {
  595. return nil, err
  596. }
  597. }
  598. }
  599. if sc := c.Ssh; sc != nil {
  600. pc.EnableSSHCA = &sc.Enabled
  601. if d := sc.UserDurations; d != nil {
  602. pc.MinUserSSHDur, pc.MaxUserSSHDur, pc.DefaultUserSSHDur, err = durationsToCertificates(d)
  603. if err != nil {
  604. return nil, err
  605. }
  606. }
  607. if d := sc.HostDurations; d != nil {
  608. pc.MinHostSSHDur, pc.MaxHostSSHDur, pc.DefaultHostSSHDur, err = durationsToCertificates(d)
  609. if err != nil {
  610. return nil, err
  611. }
  612. }
  613. }
  614. return pc, nil
  615. }
  616. func claimsToLinkedca(c *provisioner.Claims) *linkedca.Claims {
  617. if c == nil {
  618. return nil
  619. }
  620. disableRenewal := config.DefaultDisableRenewal
  621. allowRenewalAfterExpiry := config.DefaultAllowRenewalAfterExpiry
  622. disableSmallstepExtensions := config.DefaultDisableSmallstepExtensions
  623. if c.DisableRenewal != nil {
  624. disableRenewal = *c.DisableRenewal
  625. }
  626. if c.AllowRenewalAfterExpiry != nil {
  627. allowRenewalAfterExpiry = *c.AllowRenewalAfterExpiry
  628. }
  629. if c.DisableSmallstepExtensions != nil {
  630. disableSmallstepExtensions = *c.DisableSmallstepExtensions
  631. }
  632. lc := &linkedca.Claims{
  633. DisableRenewal: disableRenewal,
  634. AllowRenewalAfterExpiry: allowRenewalAfterExpiry,
  635. DisableSmallstepExtensions: disableSmallstepExtensions,
  636. }
  637. if c.DefaultTLSDur != nil || c.MinTLSDur != nil || c.MaxTLSDur != nil {
  638. lc.X509 = &linkedca.X509Claims{
  639. Enabled: true,
  640. Durations: &linkedca.Durations{
  641. Default: durationsToLinkedca(c.DefaultTLSDur),
  642. Min: durationsToLinkedca(c.MinTLSDur),
  643. Max: durationsToLinkedca(c.MaxTLSDur),
  644. },
  645. }
  646. }
  647. if c.EnableSSHCA != nil && *c.EnableSSHCA {
  648. lc.Ssh = &linkedca.SSHClaims{
  649. Enabled: true,
  650. }
  651. if c.DefaultUserSSHDur != nil || c.MinUserSSHDur != nil || c.MaxUserSSHDur != nil {
  652. lc.Ssh.UserDurations = &linkedca.Durations{
  653. Default: durationsToLinkedca(c.DefaultUserSSHDur),
  654. Min: durationsToLinkedca(c.MinUserSSHDur),
  655. Max: durationsToLinkedca(c.MaxUserSSHDur),
  656. }
  657. }
  658. if c.DefaultHostSSHDur != nil || c.MinHostSSHDur != nil || c.MaxHostSSHDur != nil {
  659. lc.Ssh.HostDurations = &linkedca.Durations{
  660. Default: durationsToLinkedca(c.DefaultHostSSHDur),
  661. Min: durationsToLinkedca(c.MinHostSSHDur),
  662. Max: durationsToLinkedca(c.MaxHostSSHDur),
  663. }
  664. }
  665. }
  666. return lc
  667. }
  668. func provisionerOptionsToLinkedca(p *provisioner.Options) (*linkedca.Template, *linkedca.Template, []*linkedca.Webhook, error) {
  669. var err error
  670. var x509Template, sshTemplate *linkedca.Template
  671. if p == nil {
  672. return nil, nil, nil, nil
  673. }
  674. if p.X509 != nil && p.X509.HasTemplate() {
  675. x509Template = &linkedca.Template{
  676. Template: nil,
  677. Data: nil,
  678. }
  679. if p.X509.Template != "" {
  680. x509Template.Template = []byte(p.X509.Template)
  681. } else if p.X509.TemplateFile != "" {
  682. filename := step.Abs(p.X509.TemplateFile)
  683. if x509Template.Template, err = os.ReadFile(filename); err != nil {
  684. return nil, nil, nil, errors.Wrap(err, "error reading x509 template")
  685. }
  686. }
  687. if p.X509.TemplateData != nil {
  688. x509Template.Data = p.X509.TemplateData
  689. }
  690. }
  691. if p.SSH != nil && p.SSH.HasTemplate() {
  692. sshTemplate = &linkedca.Template{
  693. Template: nil,
  694. Data: nil,
  695. }
  696. if p.SSH.Template != "" {
  697. sshTemplate.Template = []byte(p.SSH.Template)
  698. } else if p.SSH.TemplateFile != "" {
  699. filename := step.Abs(p.SSH.TemplateFile)
  700. if sshTemplate.Template, err = os.ReadFile(filename); err != nil {
  701. return nil, nil, nil, errors.Wrap(err, "error reading ssh template")
  702. }
  703. }
  704. if p.SSH.TemplateData != nil {
  705. sshTemplate.Data = p.SSH.TemplateData
  706. }
  707. }
  708. var webhooks []*linkedca.Webhook
  709. for _, pwh := range p.Webhooks {
  710. webhooks = append(webhooks, provisionerWebhookToLinkedca(pwh))
  711. }
  712. return x509Template, sshTemplate, webhooks, nil
  713. }
  714. func provisionerPEMToLinkedca(b []byte) [][]byte {
  715. var roots [][]byte
  716. var block *pem.Block
  717. for {
  718. if block, b = pem.Decode(b); block == nil {
  719. break
  720. }
  721. roots = append(roots, pem.EncodeToMemory(block))
  722. }
  723. return roots
  724. }
  725. func provisionerPEMToCertificates(bs [][]byte) []byte {
  726. var roots []byte
  727. for i, root := range bs {
  728. if i > 0 && !bytes.HasSuffix(root, []byte{'\n'}) {
  729. roots = append(roots, '\n')
  730. }
  731. roots = append(roots, root...)
  732. }
  733. return roots
  734. }
  735. // ProvisionerToCertificates converts the linkedca provisioner type to the certificates provisioner
  736. // interface.
  737. func ProvisionerToCertificates(p *linkedca.Provisioner) (provisioner.Interface, error) {
  738. claims, err := claimsToCertificates(p.Claims)
  739. if err != nil {
  740. return nil, err
  741. }
  742. details := p.Details.GetData()
  743. if details == nil {
  744. return nil, errors.New("provisioner does not have any details")
  745. }
  746. options := optionsToCertificates(p)
  747. switch d := details.(type) {
  748. case *linkedca.ProvisionerDetails_JWK:
  749. jwk := new(jose.JSONWebKey)
  750. if err := json.Unmarshal(d.JWK.PublicKey, &jwk); err != nil {
  751. return nil, errors.Wrap(err, "error unmarshaling public key")
  752. }
  753. return &provisioner.JWK{
  754. ID: p.Id,
  755. Type: p.Type.String(),
  756. Name: p.Name,
  757. Key: jwk,
  758. EncryptedKey: string(d.JWK.EncryptedPrivateKey),
  759. Claims: claims,
  760. Options: options,
  761. }, nil
  762. case *linkedca.ProvisionerDetails_X5C:
  763. var roots []byte
  764. for i, root := range d.X5C.GetRoots() {
  765. if i > 0 {
  766. roots = append(roots, '\n')
  767. }
  768. roots = append(roots, root...)
  769. }
  770. return &provisioner.X5C{
  771. ID: p.Id,
  772. Type: p.Type.String(),
  773. Name: p.Name,
  774. Roots: roots,
  775. Claims: claims,
  776. Options: options,
  777. }, nil
  778. case *linkedca.ProvisionerDetails_K8SSA:
  779. var publicKeys []byte
  780. for i, k := range d.K8SSA.GetPublicKeys() {
  781. if i > 0 {
  782. publicKeys = append(publicKeys, '\n')
  783. }
  784. publicKeys = append(publicKeys, k...)
  785. }
  786. return &provisioner.K8sSA{
  787. ID: p.Id,
  788. Type: p.Type.String(),
  789. Name: p.Name,
  790. PubKeys: publicKeys,
  791. Claims: claims,
  792. Options: options,
  793. }, nil
  794. case *linkedca.ProvisionerDetails_SSHPOP:
  795. return &provisioner.SSHPOP{
  796. ID: p.Id,
  797. Type: p.Type.String(),
  798. Name: p.Name,
  799. Claims: claims,
  800. }, nil
  801. case *linkedca.ProvisionerDetails_ACME:
  802. cfg := d.ACME
  803. return &provisioner.ACME{
  804. ID: p.Id,
  805. Type: p.Type.String(),
  806. Name: p.Name,
  807. ForceCN: cfg.ForceCn,
  808. TermsOfService: cfg.TermsOfService,
  809. Website: cfg.Website,
  810. CaaIdentities: cfg.CaaIdentities,
  811. RequireEAB: cfg.RequireEab,
  812. Challenges: challengesToCertificates(cfg.Challenges),
  813. AttestationFormats: attestationFormatsToCertificates(cfg.AttestationFormats),
  814. AttestationRoots: provisionerPEMToCertificates(cfg.AttestationRoots),
  815. Claims: claims,
  816. Options: options,
  817. }, nil
  818. case *linkedca.ProvisionerDetails_OIDC:
  819. cfg := d.OIDC
  820. return &provisioner.OIDC{
  821. ID: p.Id,
  822. Type: p.Type.String(),
  823. Name: p.Name,
  824. TenantID: cfg.TenantId,
  825. ClientID: cfg.ClientId,
  826. ClientSecret: cfg.ClientSecret,
  827. ConfigurationEndpoint: cfg.ConfigurationEndpoint,
  828. Admins: cfg.Admins,
  829. Domains: cfg.Domains,
  830. Groups: cfg.Groups,
  831. ListenAddress: cfg.ListenAddress,
  832. Scopes: cfg.Scopes,
  833. AuthParams: cfg.AuthParams,
  834. Claims: claims,
  835. Options: options,
  836. }, nil
  837. case *linkedca.ProvisionerDetails_AWS:
  838. cfg := d.AWS
  839. instanceAge, err := parseInstanceAge(cfg.InstanceAge)
  840. if err != nil {
  841. return nil, err
  842. }
  843. return &provisioner.AWS{
  844. ID: p.Id,
  845. Type: p.Type.String(),
  846. Name: p.Name,
  847. Accounts: cfg.Accounts,
  848. DisableCustomSANs: cfg.DisableCustomSans,
  849. DisableTrustOnFirstUse: cfg.DisableTrustOnFirstUse,
  850. InstanceAge: instanceAge,
  851. Claims: claims,
  852. Options: options,
  853. }, nil
  854. case *linkedca.ProvisionerDetails_GCP:
  855. cfg := d.GCP
  856. instanceAge, err := parseInstanceAge(cfg.InstanceAge)
  857. if err != nil {
  858. return nil, err
  859. }
  860. return &provisioner.GCP{
  861. ID: p.Id,
  862. Type: p.Type.String(),
  863. Name: p.Name,
  864. ServiceAccounts: cfg.ServiceAccounts,
  865. ProjectIDs: cfg.ProjectIds,
  866. DisableCustomSANs: cfg.DisableCustomSans,
  867. DisableTrustOnFirstUse: cfg.DisableTrustOnFirstUse,
  868. InstanceAge: instanceAge,
  869. Claims: claims,
  870. Options: options,
  871. }, nil
  872. case *linkedca.ProvisionerDetails_Azure:
  873. cfg := d.Azure
  874. return &provisioner.Azure{
  875. ID: p.Id,
  876. Type: p.Type.String(),
  877. Name: p.Name,
  878. TenantID: cfg.TenantId,
  879. ResourceGroups: cfg.ResourceGroups,
  880. SubscriptionIDs: cfg.SubscriptionIds,
  881. ObjectIDs: cfg.ObjectIds,
  882. Audience: cfg.Audience,
  883. DisableCustomSANs: cfg.DisableCustomSans,
  884. DisableTrustOnFirstUse: cfg.DisableTrustOnFirstUse,
  885. Claims: claims,
  886. Options: options,
  887. }, nil
  888. case *linkedca.ProvisionerDetails_SCEP:
  889. cfg := d.SCEP
  890. s := &provisioner.SCEP{
  891. ID: p.Id,
  892. Type: p.Type.String(),
  893. Name: p.Name,
  894. ForceCN: cfg.ForceCn,
  895. ChallengePassword: cfg.Challenge,
  896. Capabilities: cfg.Capabilities,
  897. IncludeRoot: cfg.IncludeRoot,
  898. ExcludeIntermediate: cfg.ExcludeIntermediate,
  899. MinimumPublicKeyLength: int(cfg.MinimumPublicKeyLength),
  900. EncryptionAlgorithmIdentifier: int(cfg.EncryptionAlgorithmIdentifier),
  901. Claims: claims,
  902. Options: options,
  903. }
  904. if decrypter := cfg.GetDecrypter(); decrypter != nil {
  905. s.DecrypterCertificate = decrypter.Certificate
  906. s.DecrypterKeyPEM = decrypter.Key
  907. s.DecrypterKeyURI = decrypter.KeyUri
  908. s.DecrypterKeyPassword = string(decrypter.KeyPassword)
  909. }
  910. return s, nil
  911. case *linkedca.ProvisionerDetails_Nebula:
  912. var roots []byte
  913. for i, root := range d.Nebula.GetRoots() {
  914. if i > 0 && !bytes.HasSuffix(root, []byte{'\n'}) {
  915. roots = append(roots, '\n')
  916. }
  917. roots = append(roots, root...)
  918. }
  919. return &provisioner.Nebula{
  920. ID: p.Id,
  921. Type: p.Type.String(),
  922. Name: p.Name,
  923. Roots: roots,
  924. Claims: claims,
  925. Options: options,
  926. }, nil
  927. default:
  928. return nil, fmt.Errorf("provisioner %s not implemented", p.Type)
  929. }
  930. }
  931. // ProvisionerToLinkedca converts a provisioner.Interface to a
  932. // linkedca.Provisioner type.
  933. func ProvisionerToLinkedca(p provisioner.Interface) (*linkedca.Provisioner, error) {
  934. switch p := p.(type) {
  935. case *provisioner.JWK:
  936. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  937. if err != nil {
  938. return nil, err
  939. }
  940. publicKey, err := json.Marshal(p.Key)
  941. if err != nil {
  942. return nil, errors.Wrap(err, "error marshaling key")
  943. }
  944. return &linkedca.Provisioner{
  945. Id: p.ID,
  946. Type: linkedca.Provisioner_JWK,
  947. Name: p.GetName(),
  948. Details: &linkedca.ProvisionerDetails{
  949. Data: &linkedca.ProvisionerDetails_JWK{
  950. JWK: &linkedca.JWKProvisioner{
  951. PublicKey: publicKey,
  952. EncryptedPrivateKey: []byte(p.EncryptedKey),
  953. },
  954. },
  955. },
  956. Claims: claimsToLinkedca(p.Claims),
  957. X509Template: x509Template,
  958. SshTemplate: sshTemplate,
  959. Webhooks: webhooks,
  960. }, nil
  961. case *provisioner.OIDC:
  962. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  963. if err != nil {
  964. return nil, err
  965. }
  966. return &linkedca.Provisioner{
  967. Id: p.ID,
  968. Type: linkedca.Provisioner_OIDC,
  969. Name: p.GetName(),
  970. Details: &linkedca.ProvisionerDetails{
  971. Data: &linkedca.ProvisionerDetails_OIDC{
  972. OIDC: &linkedca.OIDCProvisioner{
  973. ClientId: p.ClientID,
  974. ClientSecret: p.ClientSecret,
  975. ConfigurationEndpoint: p.ConfigurationEndpoint,
  976. Admins: p.Admins,
  977. Domains: p.Domains,
  978. Groups: p.Groups,
  979. ListenAddress: p.ListenAddress,
  980. TenantId: p.TenantID,
  981. Scopes: p.Scopes,
  982. AuthParams: p.AuthParams,
  983. },
  984. },
  985. },
  986. Claims: claimsToLinkedca(p.Claims),
  987. X509Template: x509Template,
  988. SshTemplate: sshTemplate,
  989. Webhooks: webhooks,
  990. }, nil
  991. case *provisioner.GCP:
  992. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  993. if err != nil {
  994. return nil, err
  995. }
  996. return &linkedca.Provisioner{
  997. Id: p.ID,
  998. Type: linkedca.Provisioner_GCP,
  999. Name: p.GetName(),
  1000. Details: &linkedca.ProvisionerDetails{
  1001. Data: &linkedca.ProvisionerDetails_GCP{
  1002. GCP: &linkedca.GCPProvisioner{
  1003. ServiceAccounts: p.ServiceAccounts,
  1004. ProjectIds: p.ProjectIDs,
  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.AWS:
  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_AWS,
  1024. Name: p.GetName(),
  1025. Details: &linkedca.ProvisionerDetails{
  1026. Data: &linkedca.ProvisionerDetails_AWS{
  1027. AWS: &linkedca.AWSProvisioner{
  1028. Accounts: p.Accounts,
  1029. DisableCustomSans: p.DisableCustomSANs,
  1030. DisableTrustOnFirstUse: p.DisableTrustOnFirstUse,
  1031. InstanceAge: p.InstanceAge.String(),
  1032. },
  1033. },
  1034. },
  1035. Claims: claimsToLinkedca(p.Claims),
  1036. X509Template: x509Template,
  1037. SshTemplate: sshTemplate,
  1038. Webhooks: webhooks,
  1039. }, nil
  1040. case *provisioner.Azure:
  1041. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1042. if err != nil {
  1043. return nil, err
  1044. }
  1045. return &linkedca.Provisioner{
  1046. Id: p.ID,
  1047. Type: linkedca.Provisioner_AZURE,
  1048. Name: p.GetName(),
  1049. Details: &linkedca.ProvisionerDetails{
  1050. Data: &linkedca.ProvisionerDetails_Azure{
  1051. Azure: &linkedca.AzureProvisioner{
  1052. TenantId: p.TenantID,
  1053. ResourceGroups: p.ResourceGroups,
  1054. SubscriptionIds: p.SubscriptionIDs,
  1055. ObjectIds: p.ObjectIDs,
  1056. Audience: p.Audience,
  1057. DisableCustomSans: p.DisableCustomSANs,
  1058. DisableTrustOnFirstUse: p.DisableTrustOnFirstUse,
  1059. },
  1060. },
  1061. },
  1062. Claims: claimsToLinkedca(p.Claims),
  1063. X509Template: x509Template,
  1064. SshTemplate: sshTemplate,
  1065. Webhooks: webhooks,
  1066. }, nil
  1067. case *provisioner.ACME:
  1068. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1069. if err != nil {
  1070. return nil, err
  1071. }
  1072. return &linkedca.Provisioner{
  1073. Id: p.ID,
  1074. Type: linkedca.Provisioner_ACME,
  1075. Name: p.GetName(),
  1076. Details: &linkedca.ProvisionerDetails{
  1077. Data: &linkedca.ProvisionerDetails_ACME{
  1078. ACME: &linkedca.ACMEProvisioner{
  1079. ForceCn: p.ForceCN,
  1080. TermsOfService: p.TermsOfService,
  1081. Website: p.Website,
  1082. CaaIdentities: p.CaaIdentities,
  1083. RequireEab: p.RequireEAB,
  1084. Challenges: challengesToLinkedca(p.Challenges),
  1085. AttestationFormats: attestationFormatsToLinkedca(p.AttestationFormats),
  1086. AttestationRoots: provisionerPEMToLinkedca(p.AttestationRoots),
  1087. },
  1088. },
  1089. },
  1090. Claims: claimsToLinkedca(p.Claims),
  1091. X509Template: x509Template,
  1092. SshTemplate: sshTemplate,
  1093. Webhooks: webhooks,
  1094. }, nil
  1095. case *provisioner.X5C:
  1096. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1097. if err != nil {
  1098. return nil, err
  1099. }
  1100. return &linkedca.Provisioner{
  1101. Id: p.ID,
  1102. Type: linkedca.Provisioner_X5C,
  1103. Name: p.GetName(),
  1104. Details: &linkedca.ProvisionerDetails{
  1105. Data: &linkedca.ProvisionerDetails_X5C{
  1106. X5C: &linkedca.X5CProvisioner{
  1107. Roots: provisionerPEMToLinkedca(p.Roots),
  1108. },
  1109. },
  1110. },
  1111. Claims: claimsToLinkedca(p.Claims),
  1112. X509Template: x509Template,
  1113. SshTemplate: sshTemplate,
  1114. Webhooks: webhooks,
  1115. }, nil
  1116. case *provisioner.K8sSA:
  1117. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1118. if err != nil {
  1119. return nil, err
  1120. }
  1121. return &linkedca.Provisioner{
  1122. Id: p.ID,
  1123. Type: linkedca.Provisioner_K8SSA,
  1124. Name: p.GetName(),
  1125. Details: &linkedca.ProvisionerDetails{
  1126. Data: &linkedca.ProvisionerDetails_K8SSA{
  1127. K8SSA: &linkedca.K8SSAProvisioner{
  1128. PublicKeys: provisionerPEMToLinkedca(p.PubKeys),
  1129. },
  1130. },
  1131. },
  1132. Claims: claimsToLinkedca(p.Claims),
  1133. X509Template: x509Template,
  1134. SshTemplate: sshTemplate,
  1135. Webhooks: webhooks,
  1136. }, nil
  1137. case *provisioner.SSHPOP:
  1138. return &linkedca.Provisioner{
  1139. Id: p.ID,
  1140. Type: linkedca.Provisioner_SSHPOP,
  1141. Name: p.GetName(),
  1142. Details: &linkedca.ProvisionerDetails{
  1143. Data: &linkedca.ProvisionerDetails_SSHPOP{
  1144. SSHPOP: &linkedca.SSHPOPProvisioner{},
  1145. },
  1146. },
  1147. Claims: claimsToLinkedca(p.Claims),
  1148. }, nil
  1149. case *provisioner.SCEP:
  1150. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1151. if err != nil {
  1152. return nil, err
  1153. }
  1154. return &linkedca.Provisioner{
  1155. Id: p.ID,
  1156. Type: linkedca.Provisioner_SCEP,
  1157. Name: p.GetName(),
  1158. Details: &linkedca.ProvisionerDetails{
  1159. Data: &linkedca.ProvisionerDetails_SCEP{
  1160. SCEP: &linkedca.SCEPProvisioner{
  1161. ForceCn: p.ForceCN,
  1162. Challenge: p.ChallengePassword,
  1163. Capabilities: p.Capabilities,
  1164. MinimumPublicKeyLength: int32(p.MinimumPublicKeyLength),
  1165. IncludeRoot: p.IncludeRoot,
  1166. ExcludeIntermediate: p.ExcludeIntermediate,
  1167. EncryptionAlgorithmIdentifier: int32(p.EncryptionAlgorithmIdentifier),
  1168. Decrypter: &linkedca.SCEPDecrypter{
  1169. Certificate: p.DecrypterCertificate,
  1170. Key: p.DecrypterKeyPEM,
  1171. KeyUri: p.DecrypterKeyURI,
  1172. KeyPassword: []byte(p.DecrypterKeyPassword),
  1173. },
  1174. },
  1175. },
  1176. },
  1177. Claims: claimsToLinkedca(p.Claims),
  1178. X509Template: x509Template,
  1179. SshTemplate: sshTemplate,
  1180. Webhooks: webhooks,
  1181. }, nil
  1182. case *provisioner.Nebula:
  1183. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1184. if err != nil {
  1185. return nil, err
  1186. }
  1187. return &linkedca.Provisioner{
  1188. Id: p.ID,
  1189. Type: linkedca.Provisioner_NEBULA,
  1190. Name: p.GetName(),
  1191. Details: &linkedca.ProvisionerDetails{
  1192. Data: &linkedca.ProvisionerDetails_Nebula{
  1193. Nebula: &linkedca.NebulaProvisioner{
  1194. Roots: provisionerPEMToLinkedca(p.Roots),
  1195. },
  1196. },
  1197. },
  1198. Claims: claimsToLinkedca(p.Claims),
  1199. X509Template: x509Template,
  1200. SshTemplate: sshTemplate,
  1201. Webhooks: webhooks,
  1202. }, nil
  1203. default:
  1204. return nil, fmt.Errorf("provisioner %s not implemented", p.GetType())
  1205. }
  1206. }
  1207. func parseInstanceAge(age string) (provisioner.Duration, error) {
  1208. var instanceAge provisioner.Duration
  1209. if age != "" {
  1210. iap, err := provisioner.NewDuration(age)
  1211. if err != nil {
  1212. return instanceAge, err
  1213. }
  1214. instanceAge = *iap
  1215. }
  1216. return instanceAge, nil
  1217. }
  1218. // challengesToCertificates converts linkedca challenges to provisioner ones
  1219. // skipping the unknown ones.
  1220. func challengesToCertificates(challenges []linkedca.ACMEProvisioner_ChallengeType) []provisioner.ACMEChallenge {
  1221. ret := make([]provisioner.ACMEChallenge, 0, len(challenges))
  1222. for _, ch := range challenges {
  1223. switch ch {
  1224. case linkedca.ACMEProvisioner_HTTP_01:
  1225. ret = append(ret, provisioner.HTTP_01)
  1226. case linkedca.ACMEProvisioner_DNS_01:
  1227. ret = append(ret, provisioner.DNS_01)
  1228. case linkedca.ACMEProvisioner_TLS_ALPN_01:
  1229. ret = append(ret, provisioner.TLS_ALPN_01)
  1230. case linkedca.ACMEProvisioner_DEVICE_ATTEST_01:
  1231. ret = append(ret, provisioner.DEVICE_ATTEST_01)
  1232. }
  1233. }
  1234. return ret
  1235. }
  1236. // challengesToLinkedca converts provisioner challenges to linkedca ones
  1237. // skipping the unknown ones.
  1238. func challengesToLinkedca(challenges []provisioner.ACMEChallenge) []linkedca.ACMEProvisioner_ChallengeType {
  1239. ret := make([]linkedca.ACMEProvisioner_ChallengeType, 0, len(challenges))
  1240. for _, ch := range challenges {
  1241. switch provisioner.ACMEChallenge(ch.String()) {
  1242. case provisioner.HTTP_01:
  1243. ret = append(ret, linkedca.ACMEProvisioner_HTTP_01)
  1244. case provisioner.DNS_01:
  1245. ret = append(ret, linkedca.ACMEProvisioner_DNS_01)
  1246. case provisioner.TLS_ALPN_01:
  1247. ret = append(ret, linkedca.ACMEProvisioner_TLS_ALPN_01)
  1248. case provisioner.DEVICE_ATTEST_01:
  1249. ret = append(ret, linkedca.ACMEProvisioner_DEVICE_ATTEST_01)
  1250. }
  1251. }
  1252. return ret
  1253. }
  1254. // attestationFormatsToCertificates converts linkedca attestation formats to
  1255. // provisioner ones skipping the unknown ones.
  1256. func attestationFormatsToCertificates(formats []linkedca.ACMEProvisioner_AttestationFormatType) []provisioner.ACMEAttestationFormat {
  1257. ret := make([]provisioner.ACMEAttestationFormat, 0, len(formats))
  1258. for _, f := range formats {
  1259. switch f {
  1260. case linkedca.ACMEProvisioner_APPLE:
  1261. ret = append(ret, provisioner.APPLE)
  1262. case linkedca.ACMEProvisioner_STEP:
  1263. ret = append(ret, provisioner.STEP)
  1264. case linkedca.ACMEProvisioner_TPM:
  1265. ret = append(ret, provisioner.TPM)
  1266. }
  1267. }
  1268. return ret
  1269. }
  1270. // attestationFormatsToLinkedca converts provisioner attestation formats to
  1271. // linkedca ones skipping the unknown ones.
  1272. func attestationFormatsToLinkedca(formats []provisioner.ACMEAttestationFormat) []linkedca.ACMEProvisioner_AttestationFormatType {
  1273. ret := make([]linkedca.ACMEProvisioner_AttestationFormatType, 0, len(formats))
  1274. for _, f := range formats {
  1275. switch provisioner.ACMEAttestationFormat(f.String()) {
  1276. case provisioner.APPLE:
  1277. ret = append(ret, linkedca.ACMEProvisioner_APPLE)
  1278. case provisioner.STEP:
  1279. ret = append(ret, linkedca.ACMEProvisioner_STEP)
  1280. case provisioner.TPM:
  1281. ret = append(ret, linkedca.ACMEProvisioner_TPM)
  1282. }
  1283. }
  1284. return ret
  1285. }