authority.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  1. package authority
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto"
  6. "crypto/rsa"
  7. "crypto/sha256"
  8. "crypto/x509"
  9. "encoding/hex"
  10. "fmt"
  11. "log"
  12. "strings"
  13. "sync"
  14. "time"
  15. "github.com/pkg/errors"
  16. "golang.org/x/crypto/ssh"
  17. "github.com/smallstep/linkedca"
  18. "go.step.sm/crypto/kms"
  19. kmsapi "go.step.sm/crypto/kms/apiv1"
  20. "go.step.sm/crypto/kms/sshagentkms"
  21. "go.step.sm/crypto/pemutil"
  22. "github.com/smallstep/certificates/authority/admin"
  23. adminDBNosql "github.com/smallstep/certificates/authority/admin/db/nosql"
  24. "github.com/smallstep/certificates/authority/administrator"
  25. "github.com/smallstep/certificates/authority/config"
  26. "github.com/smallstep/certificates/authority/internal/constraints"
  27. "github.com/smallstep/certificates/authority/policy"
  28. "github.com/smallstep/certificates/authority/provisioner"
  29. "github.com/smallstep/certificates/cas"
  30. casapi "github.com/smallstep/certificates/cas/apiv1"
  31. "github.com/smallstep/certificates/db"
  32. "github.com/smallstep/certificates/internal/httptransport"
  33. "github.com/smallstep/certificates/scep"
  34. "github.com/smallstep/certificates/templates"
  35. "github.com/smallstep/nosql"
  36. )
  37. // Authority implements the Certificate Authority internal interface.
  38. type Authority struct {
  39. config *config.Config
  40. keyManager kms.KeyManager
  41. provisioners *provisioner.Collection
  42. admins *administrator.Collection
  43. db db.AuthDB
  44. adminDB admin.DB
  45. templates *templates.Templates
  46. linkedCAToken string
  47. wrapTransport httptransport.Wrapper
  48. webhookClient provisioner.HTTPClient
  49. httpClient provisioner.HTTPClient
  50. // X509 CA
  51. password []byte
  52. issuerPassword []byte
  53. x509CAService cas.CertificateAuthorityService
  54. rootX509Certs []*x509.Certificate
  55. rootX509CertPool *x509.CertPool
  56. federatedX509Certs []*x509.Certificate
  57. intermediateX509Certs []*x509.Certificate
  58. certificates *sync.Map
  59. x509Enforcers []provisioner.CertificateEnforcer
  60. // SCEP CA
  61. scepOptions *scep.Options
  62. validateSCEP bool
  63. scepAuthority *scep.Authority
  64. scepKeyManager provisioner.SCEPKeyManager
  65. // SSH CA
  66. sshHostPassword []byte
  67. sshUserPassword []byte
  68. sshCAUserCertSignKey ssh.Signer
  69. sshCAHostCertSignKey ssh.Signer
  70. sshCAUserCerts []ssh.PublicKey
  71. sshCAHostCerts []ssh.PublicKey
  72. sshCAUserFederatedCerts []ssh.PublicKey
  73. sshCAHostFederatedCerts []ssh.PublicKey
  74. // CRL vars
  75. crlTicker *time.Ticker
  76. crlStopper chan struct{}
  77. crlMutex sync.Mutex
  78. // If true, do not re-initialize
  79. initOnce bool
  80. startTime time.Time
  81. // Custom functions
  82. sshBastionFunc func(ctx context.Context, user, hostname string) (*config.Bastion, error)
  83. sshCheckHostFunc func(ctx context.Context, principal string, tok string, roots []*x509.Certificate) (bool, error)
  84. sshGetHostsFunc func(ctx context.Context, cert *x509.Certificate) ([]config.Host, error)
  85. getIdentityFunc provisioner.GetIdentityFunc
  86. authorizeRenewFunc provisioner.AuthorizeRenewFunc
  87. authorizeSSHRenewFunc provisioner.AuthorizeSSHRenewFunc
  88. // Constraints and Policy engines
  89. constraintsEngine *constraints.Engine
  90. policyEngine *policy.Engine
  91. adminMutex sync.RWMutex
  92. // If true, do not initialize the authority
  93. skipInit bool
  94. // If true, do not output initialization logs
  95. quietInit bool
  96. // Called whenever applicable, in order to instrument the authority.
  97. meter Meter
  98. }
  99. // Info contains information about the authority.
  100. type Info struct {
  101. StartTime time.Time
  102. RootX509Certs []*x509.Certificate
  103. SSHCAUserPublicKey []byte
  104. SSHCAHostPublicKey []byte
  105. DNSNames []string
  106. }
  107. // New creates and initiates a new Authority type.
  108. func New(cfg *config.Config, opts ...Option) (*Authority, error) {
  109. err := cfg.Validate()
  110. if err != nil {
  111. return nil, err
  112. }
  113. var a = &Authority{
  114. config: cfg,
  115. certificates: new(sync.Map),
  116. validateSCEP: true,
  117. meter: noopMeter{},
  118. wrapTransport: httptransport.NoopWrapper(),
  119. }
  120. // Apply options.
  121. for _, fn := range opts {
  122. if err := fn(a); err != nil {
  123. return nil, err
  124. }
  125. }
  126. if a.keyManager != nil {
  127. a.keyManager = newInstrumentedKeyManager(a.keyManager, a.meter)
  128. }
  129. // Initialize system cert pool
  130. if err := initializeSystemCertPool(); err != nil {
  131. return nil, fmt.Errorf("failed to initialize the system cert pool: %w", err)
  132. }
  133. if !a.skipInit {
  134. // Initialize authority from options or configuration.
  135. if err := a.init(); err != nil {
  136. return nil, err
  137. }
  138. }
  139. return a, nil
  140. }
  141. // NewEmbedded initializes an authority that can be embedded in a different
  142. // project without the limitations of the config.
  143. func NewEmbedded(opts ...Option) (*Authority, error) {
  144. a := &Authority{
  145. config: &config.Config{},
  146. certificates: new(sync.Map),
  147. meter: noopMeter{},
  148. wrapTransport: httptransport.NoopWrapper(),
  149. }
  150. // Apply options.
  151. for _, fn := range opts {
  152. if err := fn(a); err != nil {
  153. return nil, err
  154. }
  155. }
  156. if a.keyManager != nil {
  157. a.keyManager = newInstrumentedKeyManager(a.keyManager, a.meter)
  158. }
  159. // Initialize system cert pool
  160. if err := initializeSystemCertPool(); err != nil {
  161. return nil, fmt.Errorf("failed to initialize the system cert pool: %w", err)
  162. }
  163. // Validate required options
  164. switch {
  165. case a.config == nil:
  166. return nil, errors.New("cannot create an authority without a configuration")
  167. case len(a.rootX509Certs) == 0 && a.config.Root.HasEmpties():
  168. return nil, errors.New("cannot create an authority without a root certificate")
  169. case a.x509CAService == nil && a.config.IntermediateCert == "":
  170. return nil, errors.New("cannot create an authority without an issuer certificate")
  171. case a.x509CAService == nil && a.config.IntermediateKey == "":
  172. return nil, errors.New("cannot create an authority without an issuer signer")
  173. }
  174. // Initialize config required fields.
  175. a.config.Init()
  176. if !a.skipInit {
  177. // Initialize authority from options or configuration.
  178. if err := a.init(); err != nil {
  179. return nil, err
  180. }
  181. }
  182. return a, nil
  183. }
  184. type authorityKey struct{}
  185. // NewContext adds the given authority to the context.
  186. func NewContext(ctx context.Context, a *Authority) context.Context {
  187. return context.WithValue(ctx, authorityKey{}, a)
  188. }
  189. // FromContext returns the current authority from the given context.
  190. func FromContext(ctx context.Context) (a *Authority, ok bool) {
  191. a, ok = ctx.Value(authorityKey{}).(*Authority)
  192. return
  193. }
  194. // MustFromContext returns the current authority from the given context. It will
  195. // panic if the authority is not in the context.
  196. func MustFromContext(ctx context.Context) *Authority {
  197. var (
  198. a *Authority
  199. ok bool
  200. )
  201. if a, ok = FromContext(ctx); !ok {
  202. panic("authority is not in the context")
  203. }
  204. return a
  205. }
  206. // ReloadAdminResources reloads admins and provisioners from the DB.
  207. func (a *Authority) ReloadAdminResources(ctx context.Context) error {
  208. var (
  209. provList provisioner.List
  210. adminList []*linkedca.Admin
  211. )
  212. if a.config.AuthorityConfig.EnableAdmin {
  213. provs, err := a.adminDB.GetProvisioners(ctx)
  214. if err != nil {
  215. return admin.WrapErrorISE(err, "error getting provisioners to initialize authority")
  216. }
  217. provList, err = provisionerListToCertificates(provs)
  218. if err != nil {
  219. return admin.WrapErrorISE(err, "error converting provisioner list to certificates")
  220. }
  221. adminList, err = a.adminDB.GetAdmins(ctx)
  222. if err != nil {
  223. return admin.WrapErrorISE(err, "error getting admins to initialize authority")
  224. }
  225. } else {
  226. provList = a.config.AuthorityConfig.Provisioners
  227. adminList = a.config.AuthorityConfig.Admins
  228. }
  229. provisionerConfig, err := a.generateProvisionerConfig(ctx)
  230. if err != nil {
  231. return admin.WrapErrorISE(err, "error generating provisioner config")
  232. }
  233. // Create provisioner collection.
  234. provClxn := provisioner.NewCollection(provisionerConfig.Audiences)
  235. for _, p := range provList {
  236. if err := p.Init(provisionerConfig); err != nil {
  237. log.Printf("failed to initialize %s provisioner %q: %v\n", p.GetType(), p.GetName(), err)
  238. p = provisioner.Uninitialized{
  239. Interface: p, Reason: err,
  240. }
  241. }
  242. if err := provClxn.Store(p); err != nil {
  243. return err
  244. }
  245. }
  246. // Create admin collection.
  247. adminClxn := administrator.NewCollection(provClxn)
  248. for _, adm := range adminList {
  249. p, ok := provClxn.Load(adm.ProvisionerId)
  250. if !ok {
  251. return admin.NewErrorISE("provisioner %s not found when loading admin %s",
  252. adm.ProvisionerId, adm.Id)
  253. }
  254. if err := adminClxn.Store(adm, p); err != nil {
  255. return err
  256. }
  257. }
  258. a.config.AuthorityConfig.Provisioners = provList
  259. a.provisioners = provClxn
  260. a.config.AuthorityConfig.Admins = adminList
  261. a.admins = adminClxn
  262. switch {
  263. case a.requiresSCEP() && a.GetSCEP() == nil:
  264. // TODO(hs): try to initialize SCEP here too? It's a bit
  265. // problematic if this method is called as part of an update
  266. // via Admin API and a password needs to be provided.
  267. case a.requiresSCEP() && a.GetSCEP() != nil:
  268. // update the SCEP Authority with the currently active SCEP
  269. // provisioner names and revalidate the configuration.
  270. a.scepAuthority.UpdateProvisioners(a.getSCEPProvisionerNames())
  271. if err := a.scepAuthority.Validate(); err != nil {
  272. log.Printf("failed validating SCEP authority: %v\n", err)
  273. }
  274. case !a.requiresSCEP() && a.GetSCEP() != nil:
  275. // TODO(hs): don't remove the authority if we can't also
  276. // reload it.
  277. //a.scepAuthority = nil
  278. }
  279. return nil
  280. }
  281. // init performs validation and initializes the fields of an Authority struct.
  282. func (a *Authority) init() error {
  283. // Check if handler has already been validated/initialized.
  284. if a.initOnce {
  285. return nil
  286. }
  287. var err error
  288. ctx := NewContext(context.Background(), a)
  289. // Set password if they are not set.
  290. var configPassword []byte
  291. if a.config.Password != "" {
  292. configPassword = []byte(a.config.Password)
  293. }
  294. if configPassword != nil && a.password == nil {
  295. a.password = configPassword
  296. }
  297. if a.sshHostPassword == nil {
  298. a.sshHostPassword = a.password
  299. }
  300. if a.sshUserPassword == nil {
  301. a.sshUserPassword = a.password
  302. }
  303. // Automatically enable admin for all linked cas.
  304. if a.linkedCAToken != "" {
  305. a.config.AuthorityConfig.EnableAdmin = true
  306. }
  307. // Initialize step-ca Database if it's not already initialized with WithDB.
  308. // If a.config.DB is nil then a simple, barebones in memory DB will be used.
  309. if a.db == nil {
  310. if a.db, err = db.New(a.config.DB); err != nil {
  311. return err
  312. }
  313. }
  314. // Initialize key manager if it has not been set in the options.
  315. if a.keyManager == nil {
  316. var options kmsapi.Options
  317. if a.config.KMS != nil {
  318. options = *a.config.KMS
  319. }
  320. a.keyManager, err = kms.New(ctx, options)
  321. if err != nil {
  322. return err
  323. }
  324. a.keyManager = newInstrumentedKeyManager(a.keyManager, a.meter)
  325. }
  326. // Initialize linkedca client if necessary. On a linked RA, the issuer
  327. // configuration might come from majordomo.
  328. var linkedcaClient *linkedCaClient
  329. if a.config.AuthorityConfig.EnableAdmin && a.linkedCAToken != "" && a.adminDB == nil {
  330. linkedcaClient, err = newLinkedCAClient(a.linkedCAToken)
  331. if err != nil {
  332. return err
  333. }
  334. // If authorityId is configured make sure it matches the one in the token
  335. if id := a.config.AuthorityConfig.AuthorityID; id != "" && !strings.EqualFold(id, linkedcaClient.authorityID) {
  336. return errors.New("error initializing linkedca: token authority and configured authority do not match")
  337. }
  338. a.config.AuthorityConfig.AuthorityID = linkedcaClient.authorityID
  339. linkedcaClient.Run()
  340. }
  341. // Initialize the X.509 CA Service if it has not been set in the options.
  342. if a.x509CAService == nil {
  343. var options casapi.Options
  344. if a.config.AuthorityConfig.Options != nil {
  345. options = *a.config.AuthorityConfig.Options
  346. }
  347. // AuthorityID might be empty. It's always available linked CAs/RAs.
  348. options.AuthorityID = a.config.AuthorityConfig.AuthorityID
  349. // Configure linked RA
  350. if linkedcaClient != nil && options.CertificateAuthority == "" {
  351. conf, err := linkedcaClient.GetConfiguration(ctx)
  352. if err != nil {
  353. return err
  354. }
  355. if conf.RaConfig != nil {
  356. options.CertificateAuthority = conf.RaConfig.CaUrl
  357. options.CertificateAuthorityFingerprint = conf.RaConfig.Fingerprint
  358. options.CertificateIssuer = &casapi.CertificateIssuer{
  359. Type: conf.RaConfig.Provisioner.Type.String(),
  360. Provisioner: conf.RaConfig.Provisioner.Name,
  361. }
  362. // Configure the RA authority type if needed
  363. if options.Type == "" {
  364. options.Type = casapi.StepCAS
  365. }
  366. }
  367. // Remote configuration is currently only supported on a linked RA
  368. if sc := conf.ServerConfig; sc != nil {
  369. if a.config.Address == "" {
  370. a.config.Address = sc.Address
  371. }
  372. if len(a.config.DNSNames) == 0 {
  373. a.config.DNSNames = sc.DnsNames
  374. }
  375. }
  376. }
  377. // Set the issuer password if passed in the flags.
  378. if options.CertificateIssuer != nil && a.issuerPassword != nil {
  379. options.CertificateIssuer.Password = string(a.issuerPassword)
  380. }
  381. // Read intermediate and create X509 signer for default CAS.
  382. if options.Is(casapi.SoftCAS) {
  383. options.CertificateChain, err = pemutil.ReadCertificateBundle(a.config.IntermediateCert)
  384. if err != nil {
  385. return err
  386. }
  387. options.Signer, err = a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  388. SigningKey: a.config.IntermediateKey,
  389. Password: a.password,
  390. })
  391. if err != nil {
  392. return err
  393. }
  394. // If not defined with an option, add intermediates to the list of
  395. // certificates used for name constraints validation at issuance
  396. // time.
  397. if len(a.intermediateX509Certs) == 0 {
  398. a.intermediateX509Certs = append(a.intermediateX509Certs, options.CertificateChain...)
  399. }
  400. }
  401. a.x509CAService, err = cas.New(ctx, options)
  402. if err != nil {
  403. return err
  404. }
  405. // Get root certificate from CAS.
  406. if srv, ok := a.x509CAService.(casapi.CertificateAuthorityGetter); ok {
  407. resp, err := srv.GetCertificateAuthority(&casapi.GetCertificateAuthorityRequest{
  408. Name: options.CertificateAuthority,
  409. })
  410. if err != nil {
  411. return err
  412. }
  413. a.rootX509Certs = append(a.rootX509Certs, resp.RootCertificate)
  414. a.intermediateX509Certs = append(a.intermediateX509Certs, resp.IntermediateCertificates...)
  415. }
  416. }
  417. // Read root certificates and store them in the certificates map.
  418. if len(a.rootX509Certs) == 0 {
  419. a.rootX509Certs = make([]*x509.Certificate, 0, len(a.config.Root))
  420. for _, path := range a.config.Root {
  421. crts, err := pemutil.ReadCertificateBundle(path)
  422. if err != nil {
  423. return err
  424. }
  425. a.rootX509Certs = append(a.rootX509Certs, crts...)
  426. }
  427. }
  428. for _, crt := range a.rootX509Certs {
  429. sum := sha256.Sum256(crt.Raw)
  430. a.certificates.Store(hex.EncodeToString(sum[:]), crt)
  431. }
  432. a.rootX509CertPool = x509.NewCertPool()
  433. for _, cert := range a.rootX509Certs {
  434. a.rootX509CertPool.AddCert(cert)
  435. }
  436. // Read federated certificates and store them in the certificates map.
  437. if len(a.federatedX509Certs) == 0 {
  438. a.federatedX509Certs = make([]*x509.Certificate, 0, len(a.config.FederatedRoots))
  439. for _, path := range a.config.FederatedRoots {
  440. crts, err := pemutil.ReadCertificateBundle(path)
  441. if err != nil {
  442. return err
  443. }
  444. a.federatedX509Certs = append(a.federatedX509Certs, crts...)
  445. }
  446. }
  447. for _, crt := range a.federatedX509Certs {
  448. sum := sha256.Sum256(crt.Raw)
  449. a.certificates.Store(hex.EncodeToString(sum[:]), crt)
  450. }
  451. // Initialize HTTPClient with all root certs
  452. clientRoots := make([]*x509.Certificate, 0, len(a.rootX509Certs)+len(a.federatedX509Certs))
  453. clientRoots = append(clientRoots, a.rootX509Certs...)
  454. clientRoots = append(clientRoots, a.federatedX509Certs...)
  455. a.httpClient = newHTTPClient(a.wrapTransport, clientRoots...)
  456. if err != nil {
  457. return err
  458. }
  459. // Decrypt and load SSH keys
  460. var tmplVars templates.Step
  461. if a.config.SSH != nil {
  462. if a.config.SSH.HostKey != "" {
  463. signer, err := a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  464. SigningKey: a.config.SSH.HostKey,
  465. Password: a.sshHostPassword,
  466. })
  467. if err != nil {
  468. return err
  469. }
  470. // If our signer is from sshagentkms, just unwrap it instead of
  471. // wrapping it in another layer, and this prevents crypto from
  472. // erroring out with: ssh: unsupported key type *agent.Key
  473. switch s := signer.(type) {
  474. case *sshagentkms.WrappedSSHSigner:
  475. a.sshCAHostCertSignKey = s.Signer
  476. case crypto.Signer:
  477. a.sshCAHostCertSignKey, err = ssh.NewSignerFromSigner(s)
  478. default:
  479. return errors.Errorf("unsupported signer type %T", signer)
  480. }
  481. if err != nil {
  482. return errors.Wrap(err, "error creating ssh signer")
  483. }
  484. // Append public key to list of host certs
  485. a.sshCAHostCerts = append(a.sshCAHostCerts, a.sshCAHostCertSignKey.PublicKey())
  486. a.sshCAHostFederatedCerts = append(a.sshCAHostFederatedCerts, a.sshCAHostCertSignKey.PublicKey())
  487. }
  488. if a.config.SSH.UserKey != "" {
  489. signer, err := a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  490. SigningKey: a.config.SSH.UserKey,
  491. Password: a.sshUserPassword,
  492. })
  493. if err != nil {
  494. return err
  495. }
  496. // If our signer is from sshagentkms, just unwrap it instead of
  497. // wrapping it in another layer, and this prevents crypto from
  498. // erroring out with: ssh: unsupported key type *agent.Key
  499. switch s := signer.(type) {
  500. case *sshagentkms.WrappedSSHSigner:
  501. a.sshCAUserCertSignKey = s.Signer
  502. case crypto.Signer:
  503. a.sshCAUserCertSignKey, err = ssh.NewSignerFromSigner(s)
  504. default:
  505. return errors.Errorf("unsupported signer type %T", signer)
  506. }
  507. if err != nil {
  508. return errors.Wrap(err, "error creating ssh signer")
  509. }
  510. // Append public key to list of user certs
  511. a.sshCAUserCerts = append(a.sshCAUserCerts, a.sshCAUserCertSignKey.PublicKey())
  512. a.sshCAUserFederatedCerts = append(a.sshCAUserFederatedCerts, a.sshCAUserCertSignKey.PublicKey())
  513. }
  514. // Append other public keys and add them to the template variables.
  515. for _, key := range a.config.SSH.Keys {
  516. publicKey := key.PublicKey()
  517. switch key.Type {
  518. case provisioner.SSHHostCert:
  519. if key.Federated {
  520. a.sshCAHostFederatedCerts = append(a.sshCAHostFederatedCerts, publicKey)
  521. } else {
  522. a.sshCAHostCerts = append(a.sshCAHostCerts, publicKey)
  523. }
  524. case provisioner.SSHUserCert:
  525. if key.Federated {
  526. a.sshCAUserFederatedCerts = append(a.sshCAUserFederatedCerts, publicKey)
  527. } else {
  528. a.sshCAUserCerts = append(a.sshCAUserCerts, publicKey)
  529. }
  530. default:
  531. return errors.Errorf("unsupported type %s", key.Type)
  532. }
  533. }
  534. }
  535. // Configure template variables. On the template variables HostFederatedKeys
  536. // and UserFederatedKeys we will skip the actual CA that will be available
  537. // in HostKey and UserKey.
  538. //
  539. // We cannot do it in the previous blocks because this configuration can be
  540. // injected using options.
  541. if a.sshCAHostCertSignKey != nil {
  542. tmplVars.SSH.HostKey = a.sshCAHostCertSignKey.PublicKey()
  543. tmplVars.SSH.HostFederatedKeys = append(tmplVars.SSH.HostFederatedKeys, a.sshCAHostFederatedCerts[1:]...)
  544. } else {
  545. tmplVars.SSH.HostFederatedKeys = append(tmplVars.SSH.HostFederatedKeys, a.sshCAHostFederatedCerts...)
  546. }
  547. if a.sshCAUserCertSignKey != nil {
  548. tmplVars.SSH.UserKey = a.sshCAUserCertSignKey.PublicKey()
  549. tmplVars.SSH.UserFederatedKeys = append(tmplVars.SSH.UserFederatedKeys, a.sshCAUserFederatedCerts[1:]...)
  550. } else {
  551. tmplVars.SSH.UserFederatedKeys = append(tmplVars.SSH.UserFederatedKeys, a.sshCAUserFederatedCerts...)
  552. }
  553. if a.config.AuthorityConfig.EnableAdmin {
  554. // Initialize step-ca Admin Database if it's not already initialized using
  555. // WithAdminDB.
  556. if a.adminDB == nil {
  557. if linkedcaClient != nil {
  558. a.adminDB = linkedcaClient
  559. } else {
  560. a.adminDB, err = adminDBNosql.New(a.db.(nosql.DB), admin.DefaultAuthorityID)
  561. if err != nil {
  562. return err
  563. }
  564. }
  565. }
  566. provs, err := a.adminDB.GetProvisioners(ctx)
  567. if err != nil {
  568. return admin.WrapErrorISE(err, "error loading provisioners to initialize authority")
  569. }
  570. if len(provs) == 0 && !strings.EqualFold(a.config.AuthorityConfig.DeploymentType, "linked") {
  571. // Migration will currently only be kicked off once, because either one or more provisioners
  572. // are migrated or a default JWK provisioner will be created in the DB. It won't run for
  573. // linked or hosted deployments. Not for linked, because that case is explicitly checked
  574. // for above. Not for hosted, because there'll be at least an existing OIDC provisioner.
  575. var firstJWKProvisioner *linkedca.Provisioner
  576. if len(a.config.AuthorityConfig.Provisioners) > 0 {
  577. // Existing provisioners detected; try migrating them to DB storage.
  578. a.initLogf("Starting migration of provisioners")
  579. for _, p := range a.config.AuthorityConfig.Provisioners {
  580. lp, err := ProvisionerToLinkedca(p)
  581. if err != nil {
  582. return admin.WrapErrorISE(err, "error transforming provisioner %q while migrating", p.GetName())
  583. }
  584. // Store the provisioner to be migrated
  585. if err := a.adminDB.CreateProvisioner(ctx, lp); err != nil {
  586. return admin.WrapErrorISE(err, "error creating provisioner %q while migrating", p.GetName())
  587. }
  588. // Mark the first JWK provisioner, so that it can be used for administration purposes
  589. if firstJWKProvisioner == nil && lp.Type == linkedca.Provisioner_JWK {
  590. firstJWKProvisioner = lp
  591. a.initLogf("Migrated JWK provisioner %q with admin permissions", p.GetName())
  592. } else {
  593. a.initLogf("Migrated %s provisioner %q", p.GetType(), p.GetName())
  594. }
  595. }
  596. c := a.config
  597. if c.WasLoadedFromFile() {
  598. // The provisioners in the configuration file can be deleted from
  599. // the file by editing it. Automatic rewriting of the file was considered
  600. // to be too surprising for users and not the right solution for all
  601. // use cases, so we leave it up to users to this themselves.
  602. a.initLogf("Provisioners that were migrated can now be removed from `ca.json` by editing it")
  603. }
  604. a.initLogf("Finished migrating provisioners")
  605. }
  606. // Create first JWK provisioner for remote administration purposes if none exists yet
  607. if firstJWKProvisioner == nil {
  608. firstJWKProvisioner, err = CreateFirstProvisioner(ctx, a.adminDB, string(a.password))
  609. if err != nil {
  610. return admin.WrapErrorISE(err, "error creating first provisioner")
  611. }
  612. a.initLogf("Created JWK provisioner %q with admin permissions", firstJWKProvisioner.GetName())
  613. }
  614. // Create first super admin, belonging to the first JWK provisioner
  615. // TODO(hs): pass a user-provided first super admin subject to here. With `ca init` it's
  616. // added to the DB immediately if using remote management. But when migrating from
  617. // ca.json to the DB, this option doesn't exist. Adding a flag just to do it during
  618. // migration isn't nice. We could opt for a user to change it afterwards. There exist
  619. // cases in which creation of `step` could lock out a user from API access. This is the
  620. // case if `step` isn't allowed to be signed by Name Constraints or the X.509 policy.
  621. // We have protection for that when creating and updating a policy, but if a policy or
  622. // Name Constraints are in use at the time of migration, that could lock the user out.
  623. superAdminSubject := "step"
  624. if err := a.adminDB.CreateAdmin(ctx, &linkedca.Admin{
  625. ProvisionerId: firstJWKProvisioner.Id,
  626. Subject: superAdminSubject,
  627. Type: linkedca.Admin_SUPER_ADMIN,
  628. }); err != nil {
  629. return admin.WrapErrorISE(err, "error creating first admin")
  630. }
  631. a.initLogf("Created super admin %q for JWK provisioner %q", superAdminSubject, firstJWKProvisioner.GetName())
  632. }
  633. }
  634. // Load Provisioners and Admins
  635. if err := a.ReloadAdminResources(ctx); err != nil {
  636. return err
  637. }
  638. // The SCEP functionality is provided through an instance of
  639. // scep.Authority. It is initialized when the CA is started and
  640. // if it doesn't exist yet. It gets refreshed if it already
  641. // exists. If the SCEP authority is no longer required on reload,
  642. // it gets removed.
  643. // TODO(hs): reloading through SIGHUP doesn't hit these cases. This
  644. // is because an entirely new authority.Authority is created, including
  645. // a new scep.Authority. Look into this to see if we want this to
  646. // keep working like that, or want to reuse a single instance and
  647. // update that.
  648. switch {
  649. case a.requiresSCEP() && a.GetSCEP() == nil:
  650. if a.scepOptions == nil {
  651. options := &scep.Options{
  652. Roots: a.rootX509Certs,
  653. Intermediates: a.intermediateX509Certs,
  654. }
  655. // intermediate certificates can be empty in RA mode
  656. if len(a.intermediateX509Certs) > 0 {
  657. options.SignerCert = a.intermediateX509Certs[0]
  658. }
  659. // attempt to create the (default) SCEP signer if the intermediate
  660. // key is configured.
  661. if a.config.IntermediateKey != "" {
  662. if options.Signer, err = a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  663. SigningKey: a.config.IntermediateKey,
  664. Password: a.password,
  665. }); err != nil {
  666. return err
  667. }
  668. // TODO(hs): instead of creating the decrypter here, pass the
  669. // intermediate key + chain down to the SCEP authority,
  670. // and only instantiate it when required there. Is that possible?
  671. // Also with entering passwords?
  672. // TODO(hs): if moving the logic, try improving the logic for the
  673. // decrypter password too? Right now it needs to be entered multiple
  674. // times; I've observed it to be three times maximum, every time
  675. // the intermediate key is read.
  676. _, isRSAKey := options.Signer.Public().(*rsa.PublicKey)
  677. if km, ok := a.keyManager.(kmsapi.Decrypter); ok && isRSAKey {
  678. if decrypter, err := km.CreateDecrypter(&kmsapi.CreateDecrypterRequest{
  679. DecryptionKey: a.config.IntermediateKey,
  680. Password: a.password,
  681. }); err == nil {
  682. // only pass the decrypter down when it was successfully created,
  683. // meaning it's an RSA key, and `CreateDecrypter` did not fail.
  684. options.Decrypter = decrypter
  685. // intermediate certificates can be empty in RA mode
  686. if len(options.Intermediates) > 0 {
  687. options.DecrypterCert = options.Intermediates[0]
  688. }
  689. }
  690. }
  691. }
  692. a.scepOptions = options
  693. }
  694. // provide the current SCEP provisioner names, so that the provisioners
  695. // can be validated when the CA is started.
  696. a.scepOptions.SCEPProvisionerNames = a.getSCEPProvisionerNames()
  697. // create a new SCEP authority
  698. scepAuthority, err := scep.New(a, *a.scepOptions)
  699. if err != nil {
  700. return err
  701. }
  702. if a.validateSCEP {
  703. // validate the SCEP authority
  704. if err := scepAuthority.Validate(); err != nil {
  705. a.initLogf("failed validating SCEP authority: %v", err)
  706. }
  707. }
  708. // set the SCEP authority
  709. a.scepAuthority = scepAuthority
  710. case !a.requiresSCEP() && a.GetSCEP() != nil:
  711. // clear the SCEP authority if it's no longer required
  712. a.scepAuthority = nil
  713. case a.requiresSCEP() && a.GetSCEP() != nil:
  714. // update the SCEP Authority with the currently active SCEP
  715. // provisioner names and revalidate the configuration.
  716. a.scepAuthority.UpdateProvisioners(a.getSCEPProvisionerNames())
  717. if err := a.scepAuthority.Validate(); err != nil {
  718. log.Printf("failed validating SCEP authority: %v\n", err)
  719. }
  720. }
  721. // Load X509 constraints engine.
  722. //
  723. // This is currently only available in CA mode.
  724. if size := len(a.intermediateX509Certs); size > 0 {
  725. last := a.intermediateX509Certs[size-1]
  726. constraintCerts := make([]*x509.Certificate, 0, size+1)
  727. constraintCerts = append(constraintCerts, a.intermediateX509Certs...)
  728. for _, root := range a.rootX509Certs {
  729. if bytes.Equal(last.RawIssuer, root.RawSubject) && bytes.Equal(last.AuthorityKeyId, root.SubjectKeyId) {
  730. constraintCerts = append(constraintCerts, root)
  731. }
  732. }
  733. a.constraintsEngine = constraints.New(constraintCerts...)
  734. }
  735. // Load x509 and SSH Policy Engines
  736. if err := a.reloadPolicyEngines(ctx); err != nil {
  737. return err
  738. }
  739. // Configure templates, currently only ssh templates are supported.
  740. if a.sshCAHostCertSignKey != nil || a.sshCAUserCertSignKey != nil {
  741. a.templates = a.config.Templates
  742. if a.templates == nil {
  743. a.templates = templates.DefaultTemplates()
  744. }
  745. if a.templates.Data == nil {
  746. a.templates.Data = make(map[string]interface{})
  747. }
  748. a.templates.Data["Step"] = tmplVars
  749. }
  750. // Start the CRL generator, we can assume the configuration is validated.
  751. if a.config.CRL.IsEnabled() {
  752. // Default cache duration to the default one
  753. if v := a.config.CRL.CacheDuration; v == nil || v.Duration <= 0 {
  754. a.config.CRL.CacheDuration = config.DefaultCRLCacheDuration
  755. }
  756. // Start CRL generator
  757. if err := a.startCRLGenerator(); err != nil {
  758. return err
  759. }
  760. }
  761. // JWT numeric dates are seconds.
  762. a.startTime = time.Now().Truncate(time.Second)
  763. // Set flag indicating that initialization has been completed, and should
  764. // not be repeated.
  765. a.initOnce = true
  766. return nil
  767. }
  768. // initLogf is used to log initialization information. The output
  769. // can be disabled by starting the CA with the `--quiet` flag.
  770. func (a *Authority) initLogf(format string, v ...any) {
  771. if !a.quietInit {
  772. log.Printf(format, v...)
  773. }
  774. }
  775. // GetID returns the define authority id or a zero uuid.
  776. func (a *Authority) GetID() string {
  777. const zeroUUID = "00000000-0000-0000-0000-000000000000"
  778. if id := a.config.AuthorityConfig.AuthorityID; id != "" {
  779. return id
  780. }
  781. return zeroUUID
  782. }
  783. // GetDatabase returns the authority database. If the configuration does not
  784. // define a database, GetDatabase will return a db.SimpleDB instance.
  785. func (a *Authority) GetDatabase() db.AuthDB {
  786. return a.db
  787. }
  788. // GetAdminDatabase returns the admin database, if one exists.
  789. func (a *Authority) GetAdminDatabase() admin.DB {
  790. return a.adminDB
  791. }
  792. // GetConfig returns the config.
  793. func (a *Authority) GetConfig() *config.Config {
  794. return a.config
  795. }
  796. // GetBackdate returns the [time.Duration] representing the
  797. // amount of time that is to be subtracted from the current
  798. // time when issuing a new certificate.
  799. func (a *Authority) GetBackdate() *time.Duration {
  800. if a.config == nil || a.config.AuthorityConfig == nil || a.config.AuthorityConfig.Backdate == nil {
  801. return nil
  802. }
  803. return &a.config.AuthorityConfig.Backdate.Duration
  804. }
  805. // GetInfo returns information about the authority.
  806. func (a *Authority) GetInfo() Info {
  807. ai := Info{
  808. StartTime: a.startTime,
  809. RootX509Certs: a.rootX509Certs,
  810. DNSNames: a.config.DNSNames,
  811. }
  812. if a.sshCAUserCertSignKey != nil {
  813. ai.SSHCAUserPublicKey = ssh.MarshalAuthorizedKey(a.sshCAUserCertSignKey.PublicKey())
  814. }
  815. if a.sshCAHostCertSignKey != nil {
  816. ai.SSHCAHostPublicKey = ssh.MarshalAuthorizedKey(a.sshCAHostCertSignKey.PublicKey())
  817. }
  818. return ai
  819. }
  820. // IsAdminAPIEnabled returns a boolean indicating whether the Admin API has
  821. // been enabled.
  822. func (a *Authority) IsAdminAPIEnabled() bool {
  823. return a.config.AuthorityConfig.EnableAdmin
  824. }
  825. // Shutdown safely shuts down any clients, databases, etc. held by the Authority.
  826. func (a *Authority) Shutdown() error {
  827. if a.crlTicker != nil {
  828. a.crlTicker.Stop()
  829. close(a.crlStopper)
  830. }
  831. if err := a.keyManager.Close(); err != nil {
  832. log.Printf("error closing the key manager: %v", err)
  833. }
  834. return a.db.Shutdown()
  835. }
  836. // CloseForReload closes internal services, to allow a safe reload.
  837. func (a *Authority) CloseForReload() {
  838. if a.crlTicker != nil {
  839. a.crlTicker.Stop()
  840. close(a.crlStopper)
  841. }
  842. if err := a.keyManager.Close(); err != nil {
  843. log.Printf("error closing the key manager: %v", err)
  844. }
  845. if client, ok := a.adminDB.(*linkedCaClient); ok {
  846. client.Stop()
  847. }
  848. }
  849. // IsRevoked returns whether or not a certificate has been
  850. // revoked before.
  851. func (a *Authority) IsRevoked(sn string) (bool, error) {
  852. // Check the passive revocation table.
  853. if lca, ok := a.adminDB.(interface {
  854. IsRevoked(string) (bool, error)
  855. }); ok {
  856. return lca.IsRevoked(sn)
  857. }
  858. return a.db.IsRevoked(sn)
  859. }
  860. // requiresSCEP iterates over the configured provisioners
  861. // and determines if at least one of them is a SCEP provisioner.
  862. func (a *Authority) requiresSCEP() bool {
  863. for _, p := range a.config.AuthorityConfig.Provisioners {
  864. if p.GetType() == provisioner.TypeSCEP {
  865. return true
  866. }
  867. }
  868. return false
  869. }
  870. // getSCEPProvisionerNames returns the names of the SCEP provisioners
  871. // that are currently available in the CA.
  872. func (a *Authority) getSCEPProvisionerNames() (names []string) {
  873. for _, p := range a.config.AuthorityConfig.Provisioners {
  874. if p.GetType() == provisioner.TypeSCEP {
  875. names = append(names, p.GetName())
  876. }
  877. }
  878. return
  879. }
  880. // GetSCEP returns the configured SCEP Authority
  881. func (a *Authority) GetSCEP() *scep.Authority {
  882. return a.scepAuthority
  883. }
  884. // HasACMEProvisioner returns true if at least one ACME provisioner is configured.
  885. func (a *Authority) HasACMEProvisioner() bool {
  886. for _, p := range a.config.AuthorityConfig.Provisioners {
  887. if p.GetType() == provisioner.TypeACME {
  888. return true
  889. }
  890. }
  891. return false
  892. }
  893. func (a *Authority) startCRLGenerator() error {
  894. if !a.config.CRL.IsEnabled() {
  895. return nil
  896. }
  897. // Check that there is a valid CRL in the DB right now. If it doesn't exist
  898. // or is expired, generate one now
  899. _, ok := a.db.(db.CertificateRevocationListDB)
  900. if !ok {
  901. return errors.Errorf("CRL Generation requested, but database does not support CRL generation")
  902. }
  903. // Always create a new CRL on startup in case the CA has been down and the
  904. // time to next expected CRL update is less than the cache duration.
  905. if err := a.GenerateCertificateRevocationList(); err != nil {
  906. return errors.Wrap(err, "could not generate a CRL")
  907. }
  908. a.crlStopper = make(chan struct{}, 1)
  909. a.crlTicker = time.NewTicker(a.config.CRL.TickerDuration())
  910. go func() {
  911. for {
  912. select {
  913. case <-a.crlTicker.C:
  914. log.Println("Regenerating CRL")
  915. if err := a.GenerateCertificateRevocationList(); err != nil {
  916. log.Printf("error regenerating the CRL: %v", err)
  917. }
  918. case <-a.crlStopper:
  919. return
  920. }
  921. }
  922. }()
  923. return nil
  924. }