provisioners.go 43 KB

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