4
0

provisioners.go 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376
  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 %q", prov.Name)
  209. }
  210. // Store to database -- this will set the ID.
  211. if err := a.adminDB.CreateProvisioner(ctx, prov); err != nil {
  212. return admin.WrapErrorISE(err, "error creating provisioner")
  213. }
  214. // We need a new conversion that has the newly set ID.
  215. certProv, err = ProvisionerToCertificates(prov)
  216. if err != nil {
  217. return admin.WrapErrorISE(err,
  218. "error converting to certificates provisioner from linkedca provisioner")
  219. }
  220. if err := certProv.Init(provisionerConfig); err != nil {
  221. return admin.WrapErrorISE(err, "error initializing provisioner %s", prov.Name)
  222. }
  223. if err := a.provisioners.Store(certProv); err != nil {
  224. if err := a.ReloadAdminResources(ctx); err != nil {
  225. return admin.WrapErrorISE(err, "error reloading admin resources on failed provisioner store")
  226. }
  227. return admin.WrapErrorISE(err, "error storing provisioner in authority cache")
  228. }
  229. return nil
  230. }
  231. // UpdateProvisioner stores an provisioner.Interface to the authority.
  232. func (a *Authority) UpdateProvisioner(ctx context.Context, nu *linkedca.Provisioner) error {
  233. a.adminMutex.Lock()
  234. defer a.adminMutex.Unlock()
  235. certProv, err := ProvisionerToCertificates(nu)
  236. if err != nil {
  237. return admin.WrapErrorISE(err,
  238. "error converting to certificates provisioner from linkedca provisioner")
  239. }
  240. provisionerConfig, err := a.generateProvisionerConfig(ctx)
  241. if err != nil {
  242. return admin.WrapErrorISE(err, "error generating provisioner config")
  243. }
  244. if err := a.checkProvisionerPolicy(ctx, nu.Name, nu.Policy); err != nil {
  245. return err
  246. }
  247. if err := certProv.Init(provisionerConfig); err != nil {
  248. return admin.WrapErrorISE(err, "error initializing provisioner %s", nu.Name)
  249. }
  250. if err := a.provisioners.Update(certProv); err != nil {
  251. return admin.WrapErrorISE(err, "error updating provisioner '%s' in authority cache", nu.Name)
  252. }
  253. if err := a.adminDB.UpdateProvisioner(ctx, nu); err != nil {
  254. if err := a.ReloadAdminResources(ctx); err != nil {
  255. return admin.WrapErrorISE(err, "error reloading admin resources on failed provisioner update")
  256. }
  257. return admin.WrapErrorISE(err, "error updating provisioner '%s'", nu.Name)
  258. }
  259. return nil
  260. }
  261. // RemoveProvisioner removes an provisioner.Interface from the authority.
  262. func (a *Authority) RemoveProvisioner(ctx context.Context, id string) error {
  263. a.adminMutex.Lock()
  264. defer a.adminMutex.Unlock()
  265. p, ok := a.provisioners.Load(id)
  266. if !ok {
  267. return admin.NewError(admin.ErrorBadRequestType,
  268. "provisioner %s not found", id)
  269. }
  270. provName, provID := p.GetName(), p.GetID()
  271. if a.IsAdminAPIEnabled() {
  272. // Validate
  273. // - Check that there will be SUPER_ADMINs that remain after we
  274. // remove this provisioner.
  275. if a.IsAdminAPIEnabled() && a.admins.SuperCount() == a.admins.SuperCountByProvisioner(provName) {
  276. return admin.NewError(admin.ErrorBadRequestType,
  277. "cannot remove provisioner %s because no super admins will remain", provName)
  278. }
  279. // Delete all admins associated with the provisioner.
  280. admins, ok := a.admins.LoadByProvisioner(provName)
  281. if ok {
  282. for _, adm := range admins {
  283. if err := a.removeAdmin(ctx, adm.Id); err != nil {
  284. return admin.WrapErrorISE(err, "error deleting admin %s, as part of provisioner %s deletion", adm.Subject, provName)
  285. }
  286. }
  287. }
  288. }
  289. // Remove provisioner from authority caches.
  290. if err := a.provisioners.Remove(provID); err != nil {
  291. return admin.WrapErrorISE(err, "error removing provisioner from authority cache")
  292. }
  293. // Remove provisioner from database.
  294. if err := a.adminDB.DeleteProvisioner(ctx, provID); err != nil {
  295. if err := a.ReloadAdminResources(ctx); err != nil {
  296. return admin.WrapErrorISE(err, "error reloading admin resources on failed provisioner remove")
  297. }
  298. return admin.WrapErrorISE(err, "error deleting provisioner %s", provName)
  299. }
  300. return nil
  301. }
  302. // CreateFirstProvisioner creates and stores the first provisioner when using
  303. // admin database provisioner storage.
  304. func CreateFirstProvisioner(ctx context.Context, adminDB admin.DB, password string) (*linkedca.Provisioner, error) {
  305. if password == "" {
  306. pass, err := ui.PromptPasswordGenerate("Please enter the password to encrypt your first provisioner, leave empty and we'll generate one")
  307. if err != nil {
  308. return nil, err
  309. }
  310. password = string(pass)
  311. }
  312. jwk, jwe, err := jose.GenerateDefaultKeyPair([]byte(password))
  313. if err != nil {
  314. return nil, admin.WrapErrorISE(err, "error generating JWK key pair")
  315. }
  316. jwkPubBytes, err := jwk.MarshalJSON()
  317. if err != nil {
  318. return nil, admin.WrapErrorISE(err, "error marshaling JWK")
  319. }
  320. jwePrivStr, err := jwe.CompactSerialize()
  321. if err != nil {
  322. return nil, admin.WrapErrorISE(err, "error serializing JWE")
  323. }
  324. p := &linkedca.Provisioner{
  325. Name: "Admin JWK",
  326. Type: linkedca.Provisioner_JWK,
  327. Details: &linkedca.ProvisionerDetails{
  328. Data: &linkedca.ProvisionerDetails_JWK{
  329. JWK: &linkedca.JWKProvisioner{
  330. PublicKey: jwkPubBytes,
  331. EncryptedPrivateKey: []byte(jwePrivStr),
  332. },
  333. },
  334. },
  335. Claims: &linkedca.Claims{
  336. X509: &linkedca.X509Claims{
  337. Enabled: true,
  338. Durations: &linkedca.Durations{
  339. Default: "5m",
  340. },
  341. },
  342. },
  343. }
  344. if err := adminDB.CreateProvisioner(ctx, p); err != nil {
  345. return nil, admin.WrapErrorISE(err, "error creating provisioner")
  346. }
  347. return p, nil
  348. }
  349. // ValidateClaims validates the Claims type.
  350. func ValidateClaims(c *linkedca.Claims) error {
  351. if c == nil {
  352. return nil
  353. }
  354. if c.X509 != nil {
  355. if c.X509.Durations != nil {
  356. if err := ValidateDurations(c.X509.Durations); err != nil {
  357. return err
  358. }
  359. }
  360. }
  361. if c.Ssh != nil {
  362. if c.Ssh.UserDurations != nil {
  363. if err := ValidateDurations(c.Ssh.UserDurations); err != nil {
  364. return err
  365. }
  366. }
  367. if c.Ssh.HostDurations != nil {
  368. if err := ValidateDurations(c.Ssh.HostDurations); err != nil {
  369. return err
  370. }
  371. }
  372. }
  373. return nil
  374. }
  375. // ValidateDurations validates the Durations type.
  376. func ValidateDurations(d *linkedca.Durations) error {
  377. var (
  378. err error
  379. 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.X509.Template)
  681. } else if p.X509.TemplateFile != "" {
  682. filename := step.Abs(p.X509.TemplateFile)
  683. if x509Template.Template, err = os.ReadFile(filename); err != nil {
  684. return nil, nil, nil, errors.Wrap(err, "error reading x509 template")
  685. }
  686. }
  687. if p.X509.TemplateData != nil {
  688. x509Template.Data = p.X509.TemplateData
  689. }
  690. }
  691. if p.SSH != nil && p.SSH.HasTemplate() {
  692. sshTemplate = &linkedca.Template{
  693. Template: nil,
  694. Data: nil,
  695. }
  696. if p.SSH.Template != "" {
  697. sshTemplate.Template = []byte(p.SSH.Template)
  698. } else if p.SSH.TemplateFile != "" {
  699. filename := step.Abs(p.SSH.TemplateFile)
  700. if sshTemplate.Template, err = os.ReadFile(filename); err != nil {
  701. return nil, nil, nil, errors.Wrap(err, "error reading ssh template")
  702. }
  703. }
  704. if p.SSH.TemplateData != nil {
  705. sshTemplate.Data = p.SSH.TemplateData
  706. }
  707. }
  708. var webhooks []*linkedca.Webhook
  709. for _, pwh := range p.Webhooks {
  710. webhooks = append(webhooks, provisionerWebhookToLinkedca(pwh))
  711. }
  712. return x509Template, sshTemplate, webhooks, nil
  713. }
  714. func provisionerPEMToLinkedca(b []byte) [][]byte {
  715. var roots [][]byte
  716. var block *pem.Block
  717. for {
  718. if block, b = pem.Decode(b); block == nil {
  719. break
  720. }
  721. roots = append(roots, pem.EncodeToMemory(block))
  722. }
  723. return roots
  724. }
  725. func provisionerPEMToCertificates(bs [][]byte) []byte {
  726. var roots []byte
  727. for i, root := range bs {
  728. if i > 0 && !bytes.HasSuffix(root, []byte{'\n'}) {
  729. roots = append(roots, '\n')
  730. }
  731. roots = append(roots, root...)
  732. }
  733. return roots
  734. }
  735. // ProvisionerToCertificates converts the linkedca provisioner type to the certificates provisioner
  736. // interface.
  737. func ProvisionerToCertificates(p *linkedca.Provisioner) (provisioner.Interface, error) {
  738. claims, err := claimsToCertificates(p.Claims)
  739. if err != nil {
  740. return nil, err
  741. }
  742. details := p.Details.GetData()
  743. if details == nil {
  744. return nil, errors.New("provisioner does not have any details")
  745. }
  746. options := optionsToCertificates(p)
  747. switch d := details.(type) {
  748. case *linkedca.ProvisionerDetails_JWK:
  749. jwk := new(jose.JSONWebKey)
  750. if err := json.Unmarshal(d.JWK.PublicKey, &jwk); err != nil {
  751. return nil, errors.Wrap(err, "error unmarshaling public key")
  752. }
  753. return &provisioner.JWK{
  754. ID: p.Id,
  755. Type: p.Type.String(),
  756. Name: p.Name,
  757. Key: jwk,
  758. EncryptedKey: string(d.JWK.EncryptedPrivateKey),
  759. Claims: claims,
  760. Options: options,
  761. }, nil
  762. case *linkedca.ProvisionerDetails_X5C:
  763. var roots []byte
  764. for i, root := range d.X5C.GetRoots() {
  765. if i > 0 {
  766. roots = append(roots, '\n')
  767. }
  768. roots = append(roots, root...)
  769. }
  770. return &provisioner.X5C{
  771. ID: p.Id,
  772. Type: p.Type.String(),
  773. Name: p.Name,
  774. Roots: roots,
  775. Claims: claims,
  776. Options: options,
  777. }, nil
  778. case *linkedca.ProvisionerDetails_K8SSA:
  779. var publicKeys []byte
  780. for i, k := range d.K8SSA.GetPublicKeys() {
  781. if i > 0 {
  782. publicKeys = append(publicKeys, '\n')
  783. }
  784. publicKeys = append(publicKeys, k...)
  785. }
  786. return &provisioner.K8sSA{
  787. ID: p.Id,
  788. Type: p.Type.String(),
  789. Name: p.Name,
  790. PubKeys: publicKeys,
  791. Claims: claims,
  792. Options: options,
  793. }, nil
  794. case *linkedca.ProvisionerDetails_SSHPOP:
  795. return &provisioner.SSHPOP{
  796. ID: p.Id,
  797. Type: p.Type.String(),
  798. Name: p.Name,
  799. Claims: claims,
  800. }, nil
  801. case *linkedca.ProvisionerDetails_ACME:
  802. cfg := d.ACME
  803. return &provisioner.ACME{
  804. ID: p.Id,
  805. Type: p.Type.String(),
  806. Name: p.Name,
  807. ForceCN: cfg.ForceCn,
  808. TermsOfService: cfg.TermsOfService,
  809. Website: cfg.Website,
  810. CaaIdentities: cfg.CaaIdentities,
  811. RequireEAB: cfg.RequireEab,
  812. Challenges: challengesToCertificates(cfg.Challenges),
  813. AttestationFormats: attestationFormatsToCertificates(cfg.AttestationFormats),
  814. AttestationRoots: provisionerPEMToCertificates(cfg.AttestationRoots),
  815. Claims: claims,
  816. Options: options,
  817. }, nil
  818. case *linkedca.ProvisionerDetails_OIDC:
  819. cfg := d.OIDC
  820. return &provisioner.OIDC{
  821. ID: p.Id,
  822. Type: p.Type.String(),
  823. Name: p.Name,
  824. TenantID: cfg.TenantId,
  825. ClientID: cfg.ClientId,
  826. ClientSecret: cfg.ClientSecret,
  827. ConfigurationEndpoint: cfg.ConfigurationEndpoint,
  828. Admins: cfg.Admins,
  829. Domains: cfg.Domains,
  830. Groups: cfg.Groups,
  831. ListenAddress: cfg.ListenAddress,
  832. Claims: claims,
  833. Options: options,
  834. }, nil
  835. case *linkedca.ProvisionerDetails_AWS:
  836. cfg := d.AWS
  837. instanceAge, err := parseInstanceAge(cfg.InstanceAge)
  838. if err != nil {
  839. return nil, err
  840. }
  841. return &provisioner.AWS{
  842. ID: p.Id,
  843. Type: p.Type.String(),
  844. Name: p.Name,
  845. Accounts: cfg.Accounts,
  846. DisableCustomSANs: cfg.DisableCustomSans,
  847. DisableTrustOnFirstUse: cfg.DisableTrustOnFirstUse,
  848. InstanceAge: instanceAge,
  849. Claims: claims,
  850. Options: options,
  851. }, nil
  852. case *linkedca.ProvisionerDetails_GCP:
  853. cfg := d.GCP
  854. instanceAge, err := parseInstanceAge(cfg.InstanceAge)
  855. if err != nil {
  856. return nil, err
  857. }
  858. return &provisioner.GCP{
  859. ID: p.Id,
  860. Type: p.Type.String(),
  861. Name: p.Name,
  862. ServiceAccounts: cfg.ServiceAccounts,
  863. ProjectIDs: cfg.ProjectIds,
  864. DisableCustomSANs: cfg.DisableCustomSans,
  865. DisableTrustOnFirstUse: cfg.DisableTrustOnFirstUse,
  866. InstanceAge: instanceAge,
  867. Claims: claims,
  868. Options: options,
  869. }, nil
  870. case *linkedca.ProvisionerDetails_Azure:
  871. cfg := d.Azure
  872. return &provisioner.Azure{
  873. ID: p.Id,
  874. Type: p.Type.String(),
  875. Name: p.Name,
  876. TenantID: cfg.TenantId,
  877. ResourceGroups: cfg.ResourceGroups,
  878. SubscriptionIDs: cfg.SubscriptionIds,
  879. ObjectIDs: cfg.ObjectIds,
  880. Audience: cfg.Audience,
  881. DisableCustomSANs: cfg.DisableCustomSans,
  882. DisableTrustOnFirstUse: cfg.DisableTrustOnFirstUse,
  883. Claims: claims,
  884. Options: options,
  885. }, nil
  886. case *linkedca.ProvisionerDetails_SCEP:
  887. cfg := d.SCEP
  888. s := &provisioner.SCEP{
  889. ID: p.Id,
  890. Type: p.Type.String(),
  891. Name: p.Name,
  892. ForceCN: cfg.ForceCn,
  893. ChallengePassword: cfg.Challenge,
  894. Capabilities: cfg.Capabilities,
  895. IncludeRoot: cfg.IncludeRoot,
  896. ExcludeIntermediate: cfg.ExcludeIntermediate,
  897. MinimumPublicKeyLength: int(cfg.MinimumPublicKeyLength),
  898. EncryptionAlgorithmIdentifier: int(cfg.EncryptionAlgorithmIdentifier),
  899. Claims: claims,
  900. Options: options,
  901. }
  902. if decrypter := cfg.GetDecrypter(); decrypter != nil {
  903. s.DecrypterCertificate = decrypter.Certificate
  904. s.DecrypterKeyPEM = decrypter.Key
  905. s.DecrypterKeyURI = decrypter.KeyUri
  906. s.DecrypterKeyPassword = string(decrypter.KeyPassword)
  907. }
  908. return s, nil
  909. case *linkedca.ProvisionerDetails_Nebula:
  910. var roots []byte
  911. for i, root := range d.Nebula.GetRoots() {
  912. if i > 0 && !bytes.HasSuffix(root, []byte{'\n'}) {
  913. roots = append(roots, '\n')
  914. }
  915. roots = append(roots, root...)
  916. }
  917. return &provisioner.Nebula{
  918. ID: p.Id,
  919. Type: p.Type.String(),
  920. Name: p.Name,
  921. Roots: roots,
  922. Claims: claims,
  923. Options: options,
  924. }, nil
  925. default:
  926. return nil, fmt.Errorf("provisioner %s not implemented", p.Type)
  927. }
  928. }
  929. // ProvisionerToLinkedca converts a provisioner.Interface to a
  930. // linkedca.Provisioner type.
  931. func ProvisionerToLinkedca(p provisioner.Interface) (*linkedca.Provisioner, error) {
  932. switch p := p.(type) {
  933. case *provisioner.JWK:
  934. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  935. if err != nil {
  936. return nil, err
  937. }
  938. publicKey, err := json.Marshal(p.Key)
  939. if err != nil {
  940. return nil, errors.Wrap(err, "error marshaling key")
  941. }
  942. return &linkedca.Provisioner{
  943. Id: p.ID,
  944. Type: linkedca.Provisioner_JWK,
  945. Name: p.GetName(),
  946. Details: &linkedca.ProvisionerDetails{
  947. Data: &linkedca.ProvisionerDetails_JWK{
  948. JWK: &linkedca.JWKProvisioner{
  949. PublicKey: publicKey,
  950. EncryptedPrivateKey: []byte(p.EncryptedKey),
  951. },
  952. },
  953. },
  954. Claims: claimsToLinkedca(p.Claims),
  955. X509Template: x509Template,
  956. SshTemplate: sshTemplate,
  957. Webhooks: webhooks,
  958. }, nil
  959. case *provisioner.OIDC:
  960. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  961. if err != nil {
  962. return nil, err
  963. }
  964. return &linkedca.Provisioner{
  965. Id: p.ID,
  966. Type: linkedca.Provisioner_OIDC,
  967. Name: p.GetName(),
  968. Details: &linkedca.ProvisionerDetails{
  969. Data: &linkedca.ProvisionerDetails_OIDC{
  970. OIDC: &linkedca.OIDCProvisioner{
  971. ClientId: p.ClientID,
  972. ClientSecret: p.ClientSecret,
  973. ConfigurationEndpoint: p.ConfigurationEndpoint,
  974. Admins: p.Admins,
  975. Domains: p.Domains,
  976. Groups: p.Groups,
  977. ListenAddress: p.ListenAddress,
  978. TenantId: p.TenantID,
  979. },
  980. },
  981. },
  982. Claims: claimsToLinkedca(p.Claims),
  983. X509Template: x509Template,
  984. SshTemplate: sshTemplate,
  985. Webhooks: webhooks,
  986. }, nil
  987. case *provisioner.GCP:
  988. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  989. if err != nil {
  990. return nil, err
  991. }
  992. return &linkedca.Provisioner{
  993. Id: p.ID,
  994. Type: linkedca.Provisioner_GCP,
  995. Name: p.GetName(),
  996. Details: &linkedca.ProvisionerDetails{
  997. Data: &linkedca.ProvisionerDetails_GCP{
  998. GCP: &linkedca.GCPProvisioner{
  999. ServiceAccounts: p.ServiceAccounts,
  1000. ProjectIds: p.ProjectIDs,
  1001. DisableCustomSans: p.DisableCustomSANs,
  1002. DisableTrustOnFirstUse: p.DisableTrustOnFirstUse,
  1003. InstanceAge: p.InstanceAge.String(),
  1004. },
  1005. },
  1006. },
  1007. Claims: claimsToLinkedca(p.Claims),
  1008. X509Template: x509Template,
  1009. SshTemplate: sshTemplate,
  1010. Webhooks: webhooks,
  1011. }, nil
  1012. case *provisioner.AWS:
  1013. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1014. if err != nil {
  1015. return nil, err
  1016. }
  1017. return &linkedca.Provisioner{
  1018. Id: p.ID,
  1019. Type: linkedca.Provisioner_AWS,
  1020. Name: p.GetName(),
  1021. Details: &linkedca.ProvisionerDetails{
  1022. Data: &linkedca.ProvisionerDetails_AWS{
  1023. AWS: &linkedca.AWSProvisioner{
  1024. Accounts: p.Accounts,
  1025. DisableCustomSans: p.DisableCustomSANs,
  1026. DisableTrustOnFirstUse: p.DisableTrustOnFirstUse,
  1027. InstanceAge: p.InstanceAge.String(),
  1028. },
  1029. },
  1030. },
  1031. Claims: claimsToLinkedca(p.Claims),
  1032. X509Template: x509Template,
  1033. SshTemplate: sshTemplate,
  1034. Webhooks: webhooks,
  1035. }, nil
  1036. case *provisioner.Azure:
  1037. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1038. if err != nil {
  1039. return nil, err
  1040. }
  1041. return &linkedca.Provisioner{
  1042. Id: p.ID,
  1043. Type: linkedca.Provisioner_AZURE,
  1044. Name: p.GetName(),
  1045. Details: &linkedca.ProvisionerDetails{
  1046. Data: &linkedca.ProvisionerDetails_Azure{
  1047. Azure: &linkedca.AzureProvisioner{
  1048. TenantId: p.TenantID,
  1049. ResourceGroups: p.ResourceGroups,
  1050. SubscriptionIds: p.SubscriptionIDs,
  1051. ObjectIds: p.ObjectIDs,
  1052. Audience: p.Audience,
  1053. DisableCustomSans: p.DisableCustomSANs,
  1054. DisableTrustOnFirstUse: p.DisableTrustOnFirstUse,
  1055. },
  1056. },
  1057. },
  1058. Claims: claimsToLinkedca(p.Claims),
  1059. X509Template: x509Template,
  1060. SshTemplate: sshTemplate,
  1061. Webhooks: webhooks,
  1062. }, nil
  1063. case *provisioner.ACME:
  1064. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1065. if err != nil {
  1066. return nil, err
  1067. }
  1068. return &linkedca.Provisioner{
  1069. Id: p.ID,
  1070. Type: linkedca.Provisioner_ACME,
  1071. Name: p.GetName(),
  1072. Details: &linkedca.ProvisionerDetails{
  1073. Data: &linkedca.ProvisionerDetails_ACME{
  1074. ACME: &linkedca.ACMEProvisioner{
  1075. ForceCn: p.ForceCN,
  1076. TermsOfService: p.TermsOfService,
  1077. Website: p.Website,
  1078. CaaIdentities: p.CaaIdentities,
  1079. RequireEab: p.RequireEAB,
  1080. Challenges: challengesToLinkedca(p.Challenges),
  1081. AttestationFormats: attestationFormatsToLinkedca(p.AttestationFormats),
  1082. AttestationRoots: provisionerPEMToLinkedca(p.AttestationRoots),
  1083. },
  1084. },
  1085. },
  1086. Claims: claimsToLinkedca(p.Claims),
  1087. X509Template: x509Template,
  1088. SshTemplate: sshTemplate,
  1089. Webhooks: webhooks,
  1090. }, nil
  1091. case *provisioner.X5C:
  1092. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1093. if err != nil {
  1094. return nil, err
  1095. }
  1096. return &linkedca.Provisioner{
  1097. Id: p.ID,
  1098. Type: linkedca.Provisioner_X5C,
  1099. Name: p.GetName(),
  1100. Details: &linkedca.ProvisionerDetails{
  1101. Data: &linkedca.ProvisionerDetails_X5C{
  1102. X5C: &linkedca.X5CProvisioner{
  1103. Roots: provisionerPEMToLinkedca(p.Roots),
  1104. },
  1105. },
  1106. },
  1107. Claims: claimsToLinkedca(p.Claims),
  1108. X509Template: x509Template,
  1109. SshTemplate: sshTemplate,
  1110. Webhooks: webhooks,
  1111. }, nil
  1112. case *provisioner.K8sSA:
  1113. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1114. if err != nil {
  1115. return nil, err
  1116. }
  1117. return &linkedca.Provisioner{
  1118. Id: p.ID,
  1119. Type: linkedca.Provisioner_K8SSA,
  1120. Name: p.GetName(),
  1121. Details: &linkedca.ProvisionerDetails{
  1122. Data: &linkedca.ProvisionerDetails_K8SSA{
  1123. K8SSA: &linkedca.K8SSAProvisioner{
  1124. PublicKeys: provisionerPEMToLinkedca(p.PubKeys),
  1125. },
  1126. },
  1127. },
  1128. Claims: claimsToLinkedca(p.Claims),
  1129. X509Template: x509Template,
  1130. SshTemplate: sshTemplate,
  1131. Webhooks: webhooks,
  1132. }, nil
  1133. case *provisioner.SSHPOP:
  1134. return &linkedca.Provisioner{
  1135. Id: p.ID,
  1136. Type: linkedca.Provisioner_SSHPOP,
  1137. Name: p.GetName(),
  1138. Details: &linkedca.ProvisionerDetails{
  1139. Data: &linkedca.ProvisionerDetails_SSHPOP{
  1140. SSHPOP: &linkedca.SSHPOPProvisioner{},
  1141. },
  1142. },
  1143. Claims: claimsToLinkedca(p.Claims),
  1144. }, nil
  1145. case *provisioner.SCEP:
  1146. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1147. if err != nil {
  1148. return nil, err
  1149. }
  1150. return &linkedca.Provisioner{
  1151. Id: p.ID,
  1152. Type: linkedca.Provisioner_SCEP,
  1153. Name: p.GetName(),
  1154. Details: &linkedca.ProvisionerDetails{
  1155. Data: &linkedca.ProvisionerDetails_SCEP{
  1156. SCEP: &linkedca.SCEPProvisioner{
  1157. ForceCn: p.ForceCN,
  1158. Challenge: p.ChallengePassword,
  1159. Capabilities: p.Capabilities,
  1160. MinimumPublicKeyLength: int32(p.MinimumPublicKeyLength),
  1161. IncludeRoot: p.IncludeRoot,
  1162. ExcludeIntermediate: p.ExcludeIntermediate,
  1163. EncryptionAlgorithmIdentifier: int32(p.EncryptionAlgorithmIdentifier),
  1164. Decrypter: &linkedca.SCEPDecrypter{
  1165. Certificate: p.DecrypterCertificate,
  1166. Key: p.DecrypterKeyPEM,
  1167. KeyUri: p.DecrypterKeyURI,
  1168. KeyPassword: []byte(p.DecrypterKeyPassword),
  1169. },
  1170. },
  1171. },
  1172. },
  1173. Claims: claimsToLinkedca(p.Claims),
  1174. X509Template: x509Template,
  1175. SshTemplate: sshTemplate,
  1176. Webhooks: webhooks,
  1177. }, nil
  1178. case *provisioner.Nebula:
  1179. x509Template, sshTemplate, webhooks, err := provisionerOptionsToLinkedca(p.Options)
  1180. if err != nil {
  1181. return nil, err
  1182. }
  1183. return &linkedca.Provisioner{
  1184. Id: p.ID,
  1185. Type: linkedca.Provisioner_NEBULA,
  1186. Name: p.GetName(),
  1187. Details: &linkedca.ProvisionerDetails{
  1188. Data: &linkedca.ProvisionerDetails_Nebula{
  1189. Nebula: &linkedca.NebulaProvisioner{
  1190. Roots: provisionerPEMToLinkedca(p.Roots),
  1191. },
  1192. },
  1193. },
  1194. Claims: claimsToLinkedca(p.Claims),
  1195. X509Template: x509Template,
  1196. SshTemplate: sshTemplate,
  1197. Webhooks: webhooks,
  1198. }, nil
  1199. default:
  1200. return nil, fmt.Errorf("provisioner %s not implemented", p.GetType())
  1201. }
  1202. }
  1203. func parseInstanceAge(age string) (provisioner.Duration, error) {
  1204. var instanceAge provisioner.Duration
  1205. if age != "" {
  1206. iap, err := provisioner.NewDuration(age)
  1207. if err != nil {
  1208. return instanceAge, err
  1209. }
  1210. instanceAge = *iap
  1211. }
  1212. return instanceAge, nil
  1213. }
  1214. // challengesToCertificates converts linkedca challenges to provisioner ones
  1215. // skipping the unknown ones.
  1216. func challengesToCertificates(challenges []linkedca.ACMEProvisioner_ChallengeType) []provisioner.ACMEChallenge {
  1217. ret := make([]provisioner.ACMEChallenge, 0, len(challenges))
  1218. for _, ch := range challenges {
  1219. switch ch {
  1220. case linkedca.ACMEProvisioner_HTTP_01:
  1221. ret = append(ret, provisioner.HTTP_01)
  1222. case linkedca.ACMEProvisioner_DNS_01:
  1223. ret = append(ret, provisioner.DNS_01)
  1224. case linkedca.ACMEProvisioner_TLS_ALPN_01:
  1225. ret = append(ret, provisioner.TLS_ALPN_01)
  1226. case linkedca.ACMEProvisioner_DEVICE_ATTEST_01:
  1227. ret = append(ret, provisioner.DEVICE_ATTEST_01)
  1228. }
  1229. }
  1230. return ret
  1231. }
  1232. // challengesToLinkedca converts provisioner challenges to linkedca ones
  1233. // skipping the unknown ones.
  1234. func challengesToLinkedca(challenges []provisioner.ACMEChallenge) []linkedca.ACMEProvisioner_ChallengeType {
  1235. ret := make([]linkedca.ACMEProvisioner_ChallengeType, 0, len(challenges))
  1236. for _, ch := range challenges {
  1237. switch provisioner.ACMEChallenge(ch.String()) {
  1238. case provisioner.HTTP_01:
  1239. ret = append(ret, linkedca.ACMEProvisioner_HTTP_01)
  1240. case provisioner.DNS_01:
  1241. ret = append(ret, linkedca.ACMEProvisioner_DNS_01)
  1242. case provisioner.TLS_ALPN_01:
  1243. ret = append(ret, linkedca.ACMEProvisioner_TLS_ALPN_01)
  1244. case provisioner.DEVICE_ATTEST_01:
  1245. ret = append(ret, linkedca.ACMEProvisioner_DEVICE_ATTEST_01)
  1246. }
  1247. }
  1248. return ret
  1249. }
  1250. // attestationFormatsToCertificates converts linkedca attestation formats to
  1251. // provisioner ones skipping the unknown ones.
  1252. func attestationFormatsToCertificates(formats []linkedca.ACMEProvisioner_AttestationFormatType) []provisioner.ACMEAttestationFormat {
  1253. ret := make([]provisioner.ACMEAttestationFormat, 0, len(formats))
  1254. for _, f := range formats {
  1255. switch f {
  1256. case linkedca.ACMEProvisioner_APPLE:
  1257. ret = append(ret, provisioner.APPLE)
  1258. case linkedca.ACMEProvisioner_STEP:
  1259. ret = append(ret, provisioner.STEP)
  1260. case linkedca.ACMEProvisioner_TPM:
  1261. ret = append(ret, provisioner.TPM)
  1262. }
  1263. }
  1264. return ret
  1265. }
  1266. // attestationFormatsToLinkedca converts provisioner attestation formats to
  1267. // linkedca ones skipping the unknown ones.
  1268. func attestationFormatsToLinkedca(formats []provisioner.ACMEAttestationFormat) []linkedca.ACMEProvisioner_AttestationFormatType {
  1269. ret := make([]linkedca.ACMEProvisioner_AttestationFormatType, 0, len(formats))
  1270. for _, f := range formats {
  1271. switch provisioner.ACMEAttestationFormat(f.String()) {
  1272. case provisioner.APPLE:
  1273. ret = append(ret, linkedca.ACMEProvisioner_APPLE)
  1274. case provisioner.STEP:
  1275. ret = append(ret, linkedca.ACMEProvisioner_STEP)
  1276. case provisioner.TPM:
  1277. ret = append(ret, linkedca.ACMEProvisioner_TPM)
  1278. }
  1279. }
  1280. return ret
  1281. }