provisioners.go 45 KB

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