provisioners.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  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. 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.SSH.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. }
  688. if p.SSH != nil && p.SSH.HasTemplate() {
  689. sshTemplate = &linkedca.Template{
  690. Template: nil,
  691. Data: nil,
  692. }
  693. if p.SSH.Template != "" {
  694. sshTemplate.Template = []byte(p.SSH.Template)
  695. } else if p.SSH.TemplateFile != "" {
  696. filename := step.Abs(p.SSH.TemplateFile)
  697. if sshTemplate.Template, err = os.ReadFile(filename); err != nil {
  698. return nil, nil, nil, errors.Wrap(err, "error reading ssh template")
  699. }
  700. }
  701. }
  702. var webhooks []*linkedca.Webhook
  703. for _, pwh := range p.Webhooks {
  704. webhooks = append(webhooks, provisionerWebhookToLinkedca(pwh))
  705. }
  706. return x509Template, sshTemplate, webhooks, nil
  707. }
  708. func provisionerPEMToLinkedca(b []byte) [][]byte {
  709. var roots [][]byte
  710. var block *pem.Block
  711. for {
  712. if block, b = pem.Decode(b); block == nil {
  713. break
  714. }
  715. roots = append(roots, pem.EncodeToMemory(block))
  716. }
  717. return roots
  718. }
  719. func provisionerPEMToCertificates(bs [][]byte) []byte {
  720. var roots []byte
  721. for i, root := range bs {
  722. if i > 0 && !bytes.HasSuffix(root, []byte{'\n'}) {
  723. roots = append(roots, '\n')
  724. }
  725. roots = append(roots, root...)
  726. }
  727. return roots
  728. }
  729. // ProvisionerToCertificates converts the linkedca provisioner type to the certificates provisioner
  730. // interface.
  731. func ProvisionerToCertificates(p *linkedca.Provisioner) (provisioner.Interface, error) {
  732. claims, err := claimsToCertificates(p.Claims)
  733. if err != nil {
  734. return nil, err
  735. }
  736. details := p.Details.GetData()
  737. if details == nil {
  738. return nil, errors.New("provisioner does not have any details")
  739. }
  740. options := optionsToCertificates(p)
  741. switch d := details.(type) {
  742. case *linkedca.ProvisionerDetails_JWK:
  743. jwk := new(jose.JSONWebKey)
  744. if err := json.Unmarshal(d.JWK.PublicKey, &jwk); err != nil {
  745. return nil, errors.Wrap(err, "error unmarshaling public key")
  746. }
  747. return &provisioner.JWK{
  748. ID: p.Id,
  749. Type: p.Type.String(),
  750. Name: p.Name,
  751. Key: jwk,
  752. EncryptedKey: string(d.JWK.EncryptedPrivateKey),
  753. Claims: claims,
  754. Options: options,
  755. }, nil
  756. case *linkedca.ProvisionerDetails_X5C:
  757. var roots []byte
  758. for i, root := range d.X5C.GetRoots() {
  759. if i > 0 {
  760. roots = append(roots, '\n')
  761. }
  762. roots = append(roots, root...)
  763. }
  764. return &provisioner.X5C{
  765. ID: p.Id,
  766. Type: p.Type.String(),
  767. Name: p.Name,
  768. Roots: roots,
  769. Claims: claims,
  770. Options: options,
  771. }, nil
  772. case *linkedca.ProvisionerDetails_K8SSA:
  773. var publicKeys []byte
  774. for i, k := range d.K8SSA.GetPublicKeys() {
  775. if i > 0 {
  776. publicKeys = append(publicKeys, '\n')
  777. }
  778. publicKeys = append(publicKeys, k...)
  779. }
  780. return &provisioner.K8sSA{
  781. ID: p.Id,
  782. Type: p.Type.String(),
  783. Name: p.Name,
  784. PubKeys: publicKeys,
  785. Claims: claims,
  786. Options: options,
  787. }, nil
  788. case *linkedca.ProvisionerDetails_SSHPOP:
  789. return &provisioner.SSHPOP{
  790. ID: p.Id,
  791. Type: p.Type.String(),
  792. Name: p.Name,
  793. Claims: claims,
  794. }, nil
  795. case *linkedca.ProvisionerDetails_ACME:
  796. cfg := d.ACME
  797. return &provisioner.ACME{
  798. ID: p.Id,
  799. Type: p.Type.String(),
  800. Name: p.Name,
  801. ForceCN: cfg.ForceCn,
  802. TermsOfService: cfg.TermsOfService,
  803. Website: cfg.Website,
  804. CaaIdentities: cfg.CaaIdentities,
  805. RequireEAB: cfg.RequireEab,
  806. Challenges: challengesToCertificates(cfg.Challenges),
  807. AttestationFormats: attestationFormatsToCertificates(cfg.AttestationFormats),
  808. AttestationRoots: provisionerPEMToCertificates(cfg.AttestationRoots),
  809. Claims: claims,
  810. Options: options,
  811. }, nil
  812. case *linkedca.ProvisionerDetails_OIDC:
  813. cfg := d.OIDC
  814. return &provisioner.OIDC{
  815. ID: p.Id,
  816. Type: p.Type.String(),
  817. Name: p.Name,
  818. TenantID: cfg.TenantId,
  819. ClientID: cfg.ClientId,
  820. ClientSecret: cfg.ClientSecret,
  821. ConfigurationEndpoint: cfg.ConfigurationEndpoint,
  822. Admins: cfg.Admins,
  823. Domains: cfg.Domains,
  824. Groups: cfg.Groups,
  825. ListenAddress: cfg.ListenAddress,
  826. Claims: claims,
  827. Options: options,
  828. }, nil
  829. case *linkedca.ProvisionerDetails_AWS:
  830. cfg := d.AWS
  831. instanceAge, err := parseInstanceAge(cfg.InstanceAge)
  832. if err != nil {
  833. return nil, err
  834. }
  835. return &provisioner.AWS{
  836. ID: p.Id,
  837. Type: p.Type.String(),
  838. Name: p.Name,
  839. Accounts: cfg.Accounts,
  840. DisableCustomSANs: cfg.DisableCustomSans,
  841. DisableTrustOnFirstUse: cfg.DisableTrustOnFirstUse,
  842. InstanceAge: instanceAge,
  843. Claims: claims,
  844. Options: options,
  845. }, nil
  846. case *linkedca.ProvisionerDetails_GCP:
  847. cfg := d.GCP
  848. instanceAge, err := parseInstanceAge(cfg.InstanceAge)
  849. if err != nil {
  850. return nil, err
  851. }
  852. return &provisioner.GCP{
  853. ID: p.Id,
  854. Type: p.Type.String(),
  855. Name: p.Name,
  856. ServiceAccounts: cfg.ServiceAccounts,
  857. ProjectIDs: cfg.ProjectIds,
  858. DisableCustomSANs: cfg.DisableCustomSans,
  859. DisableTrustOnFirstUse: cfg.DisableTrustOnFirstUse,
  860. InstanceAge: instanceAge,
  861. Claims: claims,
  862. Options: options,
  863. }, nil
  864. case *linkedca.ProvisionerDetails_Azure:
  865. cfg := d.Azure
  866. return &provisioner.Azure{
  867. ID: p.Id,
  868. Type: p.Type.String(),
  869. Name: p.Name,
  870. TenantID: cfg.TenantId,
  871. ResourceGroups: cfg.ResourceGroups,
  872. SubscriptionIDs: cfg.SubscriptionIds,
  873. ObjectIDs: cfg.ObjectIds,
  874. Audience: cfg.Audience,
  875. DisableCustomSANs: cfg.DisableCustomSans,
  876. DisableTrustOnFirstUse: cfg.DisableTrustOnFirstUse,
  877. Claims: claims,
  878. Options: options,
  879. }, nil
  880. case *linkedca.ProvisionerDetails_SCEP:
  881. cfg := d.SCEP
  882. return &provisioner.SCEP{
  883. ID: p.Id,
  884. Type: p.Type.String(),
  885. Name: p.Name,
  886. ForceCN: cfg.ForceCn,
  887. ChallengePassword: cfg.Challenge,
  888. Capabilities: cfg.Capabilities,
  889. IncludeRoot: cfg.IncludeRoot,
  890. MinimumPublicKeyLength: int(cfg.MinimumPublicKeyLength),
  891. EncryptionAlgorithmIdentifier: int(cfg.EncryptionAlgorithmIdentifier),
  892. Claims: claims,
  893. Options: options,
  894. }, nil
  895. case *linkedca.ProvisionerDetails_Nebula:
  896. var roots []byte
  897. for i, root := range d.Nebula.GetRoots() {
  898. if i > 0 && !bytes.HasSuffix(root, []byte{'\n'}) {
  899. roots = append(roots, '\n')
  900. }
  901. roots = append(roots, root...)
  902. }
  903. return &provisioner.Nebula{
  904. ID: p.Id,
  905. Type: p.Type.String(),
  906. Name: p.Name,
  907. Roots: roots,
  908. Claims: claims,
  909. Options: options,
  910. }, nil
  911. default:
  912. return nil, fmt.Errorf("provisioner %s not implemented", p.Type)
  913. }
  914. }
  915. // ProvisionerToLinkedca converts a provisioner.Interface to a
  916. // linkedca.Provisioner type.
  917. func ProvisionerToLinkedca(p provisioner.Interface) (*linkedca.Provisioner, error) {
  918. switch p := p.(type) {
  919. case *provisioner.JWK:
  920. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  921. if err != nil {
  922. return nil, err
  923. }
  924. publicKey, err := json.Marshal(p.Key)
  925. if err != nil {
  926. return nil, errors.Wrap(err, "error marshaling key")
  927. }
  928. return &linkedca.Provisioner{
  929. Id: p.ID,
  930. Type: linkedca.Provisioner_JWK,
  931. Name: p.GetName(),
  932. Details: &linkedca.ProvisionerDetails{
  933. Data: &linkedca.ProvisionerDetails_JWK{
  934. JWK: &linkedca.JWKProvisioner{
  935. PublicKey: publicKey,
  936. EncryptedPrivateKey: []byte(p.EncryptedKey),
  937. },
  938. },
  939. },
  940. Claims: claimsToLinkedca(p.Claims),
  941. X509Template: x509Template,
  942. SshTemplate: sshTemplate,
  943. Webhooks: webhooks,
  944. }, nil
  945. case *provisioner.OIDC:
  946. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  947. if err != nil {
  948. return nil, err
  949. }
  950. return &linkedca.Provisioner{
  951. Id: p.ID,
  952. Type: linkedca.Provisioner_OIDC,
  953. Name: p.GetName(),
  954. Details: &linkedca.ProvisionerDetails{
  955. Data: &linkedca.ProvisionerDetails_OIDC{
  956. OIDC: &linkedca.OIDCProvisioner{
  957. ClientId: p.ClientID,
  958. ClientSecret: p.ClientSecret,
  959. ConfigurationEndpoint: p.ConfigurationEndpoint,
  960. Admins: p.Admins,
  961. Domains: p.Domains,
  962. Groups: p.Groups,
  963. ListenAddress: p.ListenAddress,
  964. TenantId: p.TenantID,
  965. },
  966. },
  967. },
  968. Claims: claimsToLinkedca(p.Claims),
  969. X509Template: x509Template,
  970. SshTemplate: sshTemplate,
  971. Webhooks: webhooks,
  972. }, nil
  973. case *provisioner.GCP:
  974. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  975. if err != nil {
  976. return nil, err
  977. }
  978. return &linkedca.Provisioner{
  979. Id: p.ID,
  980. Type: linkedca.Provisioner_GCP,
  981. Name: p.GetName(),
  982. Details: &linkedca.ProvisionerDetails{
  983. Data: &linkedca.ProvisionerDetails_GCP{
  984. GCP: &linkedca.GCPProvisioner{
  985. ServiceAccounts: p.ServiceAccounts,
  986. ProjectIds: p.ProjectIDs,
  987. DisableCustomSans: p.DisableCustomSANs,
  988. DisableTrustOnFirstUse: p.DisableTrustOnFirstUse,
  989. InstanceAge: p.InstanceAge.String(),
  990. },
  991. },
  992. },
  993. Claims: claimsToLinkedca(p.Claims),
  994. X509Template: x509Template,
  995. SshTemplate: sshTemplate,
  996. Webhooks: webhooks,
  997. }, nil
  998. case *provisioner.AWS:
  999. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1000. if err != nil {
  1001. return nil, err
  1002. }
  1003. return &linkedca.Provisioner{
  1004. Id: p.ID,
  1005. Type: linkedca.Provisioner_AWS,
  1006. Name: p.GetName(),
  1007. Details: &linkedca.ProvisionerDetails{
  1008. Data: &linkedca.ProvisionerDetails_AWS{
  1009. AWS: &linkedca.AWSProvisioner{
  1010. Accounts: p.Accounts,
  1011. DisableCustomSans: p.DisableCustomSANs,
  1012. DisableTrustOnFirstUse: p.DisableTrustOnFirstUse,
  1013. InstanceAge: p.InstanceAge.String(),
  1014. },
  1015. },
  1016. },
  1017. Claims: claimsToLinkedca(p.Claims),
  1018. X509Template: x509Template,
  1019. SshTemplate: sshTemplate,
  1020. Webhooks: webhooks,
  1021. }, nil
  1022. case *provisioner.Azure:
  1023. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1024. if err != nil {
  1025. return nil, err
  1026. }
  1027. return &linkedca.Provisioner{
  1028. Id: p.ID,
  1029. Type: linkedca.Provisioner_AZURE,
  1030. Name: p.GetName(),
  1031. Details: &linkedca.ProvisionerDetails{
  1032. Data: &linkedca.ProvisionerDetails_Azure{
  1033. Azure: &linkedca.AzureProvisioner{
  1034. TenantId: p.TenantID,
  1035. ResourceGroups: p.ResourceGroups,
  1036. SubscriptionIds: p.SubscriptionIDs,
  1037. ObjectIds: p.ObjectIDs,
  1038. Audience: p.Audience,
  1039. DisableCustomSans: p.DisableCustomSANs,
  1040. DisableTrustOnFirstUse: p.DisableTrustOnFirstUse,
  1041. },
  1042. },
  1043. },
  1044. Claims: claimsToLinkedca(p.Claims),
  1045. X509Template: x509Template,
  1046. SshTemplate: sshTemplate,
  1047. Webhooks: webhooks,
  1048. }, nil
  1049. case *provisioner.ACME:
  1050. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1051. if err != nil {
  1052. return nil, err
  1053. }
  1054. return &linkedca.Provisioner{
  1055. Id: p.ID,
  1056. Type: linkedca.Provisioner_ACME,
  1057. Name: p.GetName(),
  1058. Details: &linkedca.ProvisionerDetails{
  1059. Data: &linkedca.ProvisionerDetails_ACME{
  1060. ACME: &linkedca.ACMEProvisioner{
  1061. ForceCn: p.ForceCN,
  1062. TermsOfService: p.TermsOfService,
  1063. Website: p.Website,
  1064. CaaIdentities: p.CaaIdentities,
  1065. RequireEab: p.RequireEAB,
  1066. Challenges: challengesToLinkedca(p.Challenges),
  1067. AttestationFormats: attestationFormatsToLinkedca(p.AttestationFormats),
  1068. AttestationRoots: provisionerPEMToLinkedca(p.AttestationRoots),
  1069. },
  1070. },
  1071. },
  1072. Claims: claimsToLinkedca(p.Claims),
  1073. X509Template: x509Template,
  1074. SshTemplate: sshTemplate,
  1075. Webhooks: webhooks,
  1076. }, nil
  1077. case *provisioner.X5C:
  1078. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1079. if err != nil {
  1080. return nil, err
  1081. }
  1082. return &linkedca.Provisioner{
  1083. Id: p.ID,
  1084. Type: linkedca.Provisioner_X5C,
  1085. Name: p.GetName(),
  1086. Details: &linkedca.ProvisionerDetails{
  1087. Data: &linkedca.ProvisionerDetails_X5C{
  1088. X5C: &linkedca.X5CProvisioner{
  1089. Roots: provisionerPEMToLinkedca(p.Roots),
  1090. },
  1091. },
  1092. },
  1093. Claims: claimsToLinkedca(p.Claims),
  1094. X509Template: x509Template,
  1095. SshTemplate: sshTemplate,
  1096. Webhooks: webhooks,
  1097. }, nil
  1098. case *provisioner.K8sSA:
  1099. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1100. if err != nil {
  1101. return nil, err
  1102. }
  1103. return &linkedca.Provisioner{
  1104. Id: p.ID,
  1105. Type: linkedca.Provisioner_K8SSA,
  1106. Name: p.GetName(),
  1107. Details: &linkedca.ProvisionerDetails{
  1108. Data: &linkedca.ProvisionerDetails_K8SSA{
  1109. K8SSA: &linkedca.K8SSAProvisioner{
  1110. PublicKeys: provisionerPEMToLinkedca(p.PubKeys),
  1111. },
  1112. },
  1113. },
  1114. Claims: claimsToLinkedca(p.Claims),
  1115. X509Template: x509Template,
  1116. SshTemplate: sshTemplate,
  1117. Webhooks: webhooks,
  1118. }, nil
  1119. case *provisioner.SSHPOP:
  1120. return &linkedca.Provisioner{
  1121. Id: p.ID,
  1122. Type: linkedca.Provisioner_SSHPOP,
  1123. Name: p.GetName(),
  1124. Details: &linkedca.ProvisionerDetails{
  1125. Data: &linkedca.ProvisionerDetails_SSHPOP{
  1126. SSHPOP: &linkedca.SSHPOPProvisioner{},
  1127. },
  1128. },
  1129. Claims: claimsToLinkedca(p.Claims),
  1130. }, nil
  1131. case *provisioner.SCEP:
  1132. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1133. if err != nil {
  1134. return nil, err
  1135. }
  1136. return &linkedca.Provisioner{
  1137. Id: p.ID,
  1138. Type: linkedca.Provisioner_SCEP,
  1139. Name: p.GetName(),
  1140. Details: &linkedca.ProvisionerDetails{
  1141. Data: &linkedca.ProvisionerDetails_SCEP{
  1142. SCEP: &linkedca.SCEPProvisioner{
  1143. ForceCn: p.ForceCN,
  1144. Challenge: p.ChallengePassword,
  1145. Capabilities: p.Capabilities,
  1146. MinimumPublicKeyLength: int32(p.MinimumPublicKeyLength),
  1147. IncludeRoot: p.IncludeRoot,
  1148. EncryptionAlgorithmIdentifier: int32(p.EncryptionAlgorithmIdentifier),
  1149. },
  1150. },
  1151. },
  1152. Claims: claimsToLinkedca(p.Claims),
  1153. X509Template: x509Template,
  1154. SshTemplate: sshTemplate,
  1155. Webhooks: webhooks,
  1156. }, nil
  1157. case *provisioner.Nebula:
  1158. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1159. if err != nil {
  1160. return nil, err
  1161. }
  1162. return &linkedca.Provisioner{
  1163. Id: p.ID,
  1164. Type: linkedca.Provisioner_NEBULA,
  1165. Name: p.GetName(),
  1166. Details: &linkedca.ProvisionerDetails{
  1167. Data: &linkedca.ProvisionerDetails_Nebula{
  1168. Nebula: &linkedca.NebulaProvisioner{
  1169. Roots: provisionerPEMToLinkedca(p.Roots),
  1170. },
  1171. },
  1172. },
  1173. Claims: claimsToLinkedca(p.Claims),
  1174. X509Template: x509Template,
  1175. SshTemplate: sshTemplate,
  1176. Webhooks: webhooks,
  1177. }, nil
  1178. default:
  1179. return nil, fmt.Errorf("provisioner %s not implemented", p.GetType())
  1180. }
  1181. }
  1182. func parseInstanceAge(age string) (provisioner.Duration, error) {
  1183. var instanceAge provisioner.Duration
  1184. if age != "" {
  1185. iap, err := provisioner.NewDuration(age)
  1186. if err != nil {
  1187. return instanceAge, err
  1188. }
  1189. instanceAge = *iap
  1190. }
  1191. return instanceAge, nil
  1192. }
  1193. // challengesToCertificates converts linkedca challenges to provisioner ones
  1194. // skipping the unknown ones.
  1195. func challengesToCertificates(challenges []linkedca.ACMEProvisioner_ChallengeType) []provisioner.ACMEChallenge {
  1196. ret := make([]provisioner.ACMEChallenge, 0, len(challenges))
  1197. for _, ch := range challenges {
  1198. switch ch {
  1199. case linkedca.ACMEProvisioner_HTTP_01:
  1200. ret = append(ret, provisioner.HTTP_01)
  1201. case linkedca.ACMEProvisioner_DNS_01:
  1202. ret = append(ret, provisioner.DNS_01)
  1203. case linkedca.ACMEProvisioner_TLS_ALPN_01:
  1204. ret = append(ret, provisioner.TLS_ALPN_01)
  1205. case linkedca.ACMEProvisioner_DEVICE_ATTEST_01:
  1206. ret = append(ret, provisioner.DEVICE_ATTEST_01)
  1207. }
  1208. }
  1209. return ret
  1210. }
  1211. // challengesToLinkedca converts provisioner challenges to linkedca ones
  1212. // skipping the unknown ones.
  1213. func challengesToLinkedca(challenges []provisioner.ACMEChallenge) []linkedca.ACMEProvisioner_ChallengeType {
  1214. ret := make([]linkedca.ACMEProvisioner_ChallengeType, 0, len(challenges))
  1215. for _, ch := range challenges {
  1216. switch provisioner.ACMEChallenge(ch.String()) {
  1217. case provisioner.HTTP_01:
  1218. ret = append(ret, linkedca.ACMEProvisioner_HTTP_01)
  1219. case provisioner.DNS_01:
  1220. ret = append(ret, linkedca.ACMEProvisioner_DNS_01)
  1221. case provisioner.TLS_ALPN_01:
  1222. ret = append(ret, linkedca.ACMEProvisioner_TLS_ALPN_01)
  1223. case provisioner.DEVICE_ATTEST_01:
  1224. ret = append(ret, linkedca.ACMEProvisioner_DEVICE_ATTEST_01)
  1225. }
  1226. }
  1227. return ret
  1228. }
  1229. // attestationFormatsToCertificates converts linkedca attestation formats to
  1230. // provisioner ones skipping the unknown ones.
  1231. func attestationFormatsToCertificates(formats []linkedca.ACMEProvisioner_AttestationFormatType) []provisioner.ACMEAttestationFormat {
  1232. ret := make([]provisioner.ACMEAttestationFormat, 0, len(formats))
  1233. for _, f := range formats {
  1234. switch f {
  1235. case linkedca.ACMEProvisioner_APPLE:
  1236. ret = append(ret, provisioner.APPLE)
  1237. case linkedca.ACMEProvisioner_STEP:
  1238. ret = append(ret, provisioner.STEP)
  1239. case linkedca.ACMEProvisioner_TPM:
  1240. ret = append(ret, provisioner.TPM)
  1241. }
  1242. }
  1243. return ret
  1244. }
  1245. // attestationFormatsToLinkedca converts provisioner attestation formats to
  1246. // linkedca ones skipping the unknown ones.
  1247. func attestationFormatsToLinkedca(formats []provisioner.ACMEAttestationFormat) []linkedca.ACMEProvisioner_AttestationFormatType {
  1248. ret := make([]linkedca.ACMEProvisioner_AttestationFormatType, 0, len(formats))
  1249. for _, f := range formats {
  1250. switch provisioner.ACMEAttestationFormat(f.String()) {
  1251. case provisioner.APPLE:
  1252. ret = append(ret, linkedca.ACMEProvisioner_APPLE)
  1253. case provisioner.STEP:
  1254. ret = append(ret, linkedca.ACMEProvisioner_STEP)
  1255. case provisioner.TPM:
  1256. ret = append(ret, linkedca.ACMEProvisioner_TPM)
  1257. }
  1258. }
  1259. return ret
  1260. }