ca.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. package ca
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/tls"
  6. "crypto/x509"
  7. "fmt"
  8. "log"
  9. "net"
  10. "net/http"
  11. "net/url"
  12. "reflect"
  13. "strings"
  14. "sync"
  15. "time"
  16. "github.com/go-chi/chi/v5"
  17. "github.com/go-chi/chi/v5/middleware"
  18. "github.com/pkg/errors"
  19. "github.com/smallstep/certificates/acme"
  20. acmeAPI "github.com/smallstep/certificates/acme/api"
  21. acmeNoSQL "github.com/smallstep/certificates/acme/db/nosql"
  22. "github.com/smallstep/certificates/api"
  23. "github.com/smallstep/certificates/authority"
  24. "github.com/smallstep/certificates/authority/admin"
  25. adminAPI "github.com/smallstep/certificates/authority/admin/api"
  26. "github.com/smallstep/certificates/authority/config"
  27. "github.com/smallstep/certificates/cas/apiv1"
  28. "github.com/smallstep/certificates/db"
  29. "github.com/smallstep/certificates/internal/metrix"
  30. "github.com/smallstep/certificates/logging"
  31. "github.com/smallstep/certificates/monitoring"
  32. "github.com/smallstep/certificates/scep"
  33. scepAPI "github.com/smallstep/certificates/scep/api"
  34. "github.com/smallstep/certificates/server"
  35. "github.com/smallstep/nosql"
  36. "go.step.sm/cli-utils/step"
  37. "go.step.sm/crypto/x509util"
  38. )
  39. type options struct {
  40. configFile string
  41. linkedCAToken string
  42. quiet bool
  43. password []byte
  44. issuerPassword []byte
  45. sshHostPassword []byte
  46. sshUserPassword []byte
  47. database db.AuthDB
  48. x509CAService apiv1.CertificateAuthorityService
  49. tlsConfig *tls.Config
  50. }
  51. func (o *options) apply(opts []Option) {
  52. for _, fn := range opts {
  53. fn(o)
  54. }
  55. }
  56. // Option is the type of options passed to the CA constructor.
  57. type Option func(o *options)
  58. // WithConfigFile sets the given name as the configuration file name in the CA
  59. // options.
  60. func WithConfigFile(name string) Option {
  61. return func(o *options) {
  62. o.configFile = name
  63. }
  64. }
  65. // WithX509CAService provides the x509CAService to be used for signing x509 requests
  66. func WithX509CAService(svc apiv1.CertificateAuthorityService) Option {
  67. return func(o *options) {
  68. o.x509CAService = svc
  69. }
  70. }
  71. // WithPassword sets the given password as the configured password in the CA
  72. // options.
  73. func WithPassword(password []byte) Option {
  74. return func(o *options) {
  75. o.password = password
  76. }
  77. }
  78. // WithSSHHostPassword sets the given password to decrypt the key used to sign
  79. // ssh host certificates.
  80. func WithSSHHostPassword(password []byte) Option {
  81. return func(o *options) {
  82. o.sshHostPassword = password
  83. }
  84. }
  85. // WithSSHUserPassword sets the given password to decrypt the key used to sign
  86. // ssh user certificates.
  87. func WithSSHUserPassword(password []byte) Option {
  88. return func(o *options) {
  89. o.sshUserPassword = password
  90. }
  91. }
  92. // WithIssuerPassword sets the given password as the configured certificate
  93. // issuer password in the CA options.
  94. func WithIssuerPassword(password []byte) Option {
  95. return func(o *options) {
  96. o.issuerPassword = password
  97. }
  98. }
  99. // WithDatabase sets the given authority database to the CA options.
  100. func WithDatabase(d db.AuthDB) Option {
  101. return func(o *options) {
  102. o.database = d
  103. }
  104. }
  105. // WithTLSConfig sets the TLS configuration to be used by the HTTP(s) server
  106. // spun by step-ca.
  107. func WithTLSConfig(t *tls.Config) Option {
  108. return func(o *options) {
  109. o.tlsConfig = t
  110. }
  111. }
  112. // WithLinkedCAToken sets the token used to authenticate with the linkedca.
  113. func WithLinkedCAToken(token string) Option {
  114. return func(o *options) {
  115. o.linkedCAToken = token
  116. }
  117. }
  118. // WithQuiet sets the quiet flag.
  119. func WithQuiet(quiet bool) Option {
  120. return func(o *options) {
  121. o.quiet = quiet
  122. }
  123. }
  124. // CA is the type used to build the complete certificate authority. It builds
  125. // the HTTP server, set ups the middlewares and the HTTP handlers.
  126. type CA struct {
  127. auth *authority.Authority
  128. config *config.Config
  129. srv *server.Server
  130. insecureSrv *server.Server
  131. metricsSrv *server.Server
  132. opts *options
  133. renewer *TLSRenewer
  134. compactStop chan struct{}
  135. }
  136. // New creates and initializes the CA with the given configuration and options.
  137. func New(cfg *config.Config, opts ...Option) (*CA, error) {
  138. ca := &CA{
  139. config: cfg,
  140. opts: new(options),
  141. compactStop: make(chan struct{}),
  142. }
  143. ca.opts.apply(opts)
  144. return ca.Init(cfg)
  145. }
  146. // Init initializes the CA with the given configuration.
  147. func (ca *CA) Init(cfg *config.Config) (*CA, error) {
  148. // Set password, it's ok to set nil password, the ca will prompt for them if
  149. // they are required.
  150. opts := []authority.Option{
  151. authority.WithPassword(ca.opts.password),
  152. authority.WithSSHHostPassword(ca.opts.sshHostPassword),
  153. authority.WithSSHUserPassword(ca.opts.sshUserPassword),
  154. authority.WithIssuerPassword(ca.opts.issuerPassword),
  155. }
  156. if ca.opts.linkedCAToken != "" {
  157. opts = append(opts, authority.WithLinkedCAToken(ca.opts.linkedCAToken))
  158. }
  159. if ca.opts.database != nil {
  160. opts = append(opts, authority.WithDatabase(ca.opts.database))
  161. }
  162. if ca.opts.quiet {
  163. opts = append(opts, authority.WithQuietInit())
  164. }
  165. if ca.opts.x509CAService != nil {
  166. opts = append(opts, authority.WithX509CAService(ca.opts.x509CAService))
  167. }
  168. var meter *metrix.Meter
  169. if ca.config.MetricsAddress != "" {
  170. meter = metrix.New()
  171. opts = append(opts, authority.WithMeter(meter))
  172. }
  173. webhookTransport := http.DefaultTransport.(*http.Transport).Clone()
  174. opts = append(opts, authority.WithWebhookClient(&http.Client{Transport: webhookTransport}))
  175. auth, err := authority.New(cfg, opts...)
  176. if err != nil {
  177. return nil, err
  178. }
  179. ca.auth = auth
  180. var tlsConfig *tls.Config
  181. var clientTLSConfig *tls.Config
  182. if ca.opts.tlsConfig != nil {
  183. // try using the tls Configuration supplied by the caller
  184. log.Print("Using tls configuration supplied by the application")
  185. tlsConfig = ca.opts.tlsConfig
  186. clientTLSConfig = ca.opts.tlsConfig
  187. } else {
  188. // default to using the step-ca x509 Signer Interface
  189. log.Print("Building new tls configuration using step-ca x509 Signer Interface")
  190. tlsConfig, clientTLSConfig, err = ca.getTLSConfig(auth)
  191. if err != nil {
  192. return nil, err
  193. }
  194. }
  195. webhookTransport.TLSClientConfig = clientTLSConfig
  196. // Using chi as the main router
  197. mux := chi.NewRouter()
  198. handler := http.Handler(mux)
  199. insecureMux := chi.NewRouter()
  200. insecureHandler := http.Handler(insecureMux)
  201. // Add HEAD middleware
  202. mux.Use(middleware.GetHead)
  203. insecureMux.Use(middleware.GetHead)
  204. // Add regular CA api endpoints in / and /1.0
  205. api.Route(mux)
  206. mux.Route("/1.0", func(r chi.Router) {
  207. api.Route(r)
  208. })
  209. // Mount the CRL to the insecure mux
  210. insecureMux.Get("/crl", api.CRL)
  211. insecureMux.Get("/1.0/crl", api.CRL)
  212. // Add ACME api endpoints in /acme and /1.0/acme
  213. dns := cfg.DNSNames[0]
  214. u, err := url.Parse("https://" + cfg.Address)
  215. if err != nil {
  216. return nil, err
  217. }
  218. port := u.Port()
  219. if port != "" && port != "443" {
  220. dns = fmt.Sprintf("%s:%s", dns, port)
  221. }
  222. // ACME Router is only available if we have a database.
  223. var acmeDB acme.DB
  224. var acmeLinker acme.Linker
  225. if cfg.DB != nil {
  226. acmeDB, err = acmeNoSQL.New(auth.GetDatabase().(nosql.DB))
  227. if err != nil {
  228. return nil, errors.Wrap(err, "error configuring ACME DB interface")
  229. }
  230. acmeLinker = acme.NewLinker(dns, "acme")
  231. mux.Route("/acme", func(r chi.Router) {
  232. acmeAPI.Route(r)
  233. })
  234. // Use 2.0 because, at the moment, our ACME api is only compatible with v2.0
  235. // of the ACME spec.
  236. mux.Route("/2.0/acme", func(r chi.Router) {
  237. acmeAPI.Route(r)
  238. })
  239. }
  240. // Admin API Router
  241. if cfg.AuthorityConfig.EnableAdmin {
  242. adminDB := auth.GetAdminDatabase()
  243. if adminDB != nil {
  244. acmeAdminResponder := adminAPI.NewACMEAdminResponder()
  245. policyAdminResponder := adminAPI.NewPolicyAdminResponder()
  246. webhookAdminResponder := adminAPI.NewWebhookAdminResponder()
  247. mux.Route("/admin", func(r chi.Router) {
  248. adminAPI.Route(
  249. r,
  250. adminAPI.WithACMEResponder(acmeAdminResponder),
  251. adminAPI.WithPolicyResponder(policyAdminResponder),
  252. adminAPI.WithWebhookResponder(webhookAdminResponder),
  253. )
  254. })
  255. }
  256. }
  257. var scepAuthority *scep.Authority
  258. if ca.shouldServeSCEPEndpoints() {
  259. // get the SCEP authority configuration. Validation is
  260. // performed within the authority instantiation process.
  261. scepAuthority = auth.GetSCEP()
  262. // According to the RFC (https://tools.ietf.org/html/rfc8894#section-7.10),
  263. // SCEP operations are performed using HTTP, so that's why the API is mounted
  264. // to the insecure mux.
  265. scepPrefix := "scep"
  266. insecureMux.Route("/"+scepPrefix, func(r chi.Router) {
  267. scepAPI.Route(r)
  268. })
  269. // The RFC also mentions usage of HTTPS, but seems to advise
  270. // against it, because of potential interoperability issues.
  271. // Currently I think it's not bad to use HTTPS also, so that's
  272. // why I've kept the API endpoints in both muxes and both HTTP
  273. // as well as HTTPS can be used to request certificates
  274. // using SCEP.
  275. mux.Route("/"+scepPrefix, func(r chi.Router) {
  276. scepAPI.Route(r)
  277. })
  278. }
  279. // helpful routine for logging all routes
  280. //dumpRoutes(mux)
  281. //dumpRoutes(insecureMux)
  282. // Add monitoring if configured
  283. if len(cfg.Monitoring) > 0 {
  284. m, err := monitoring.New(cfg.Monitoring)
  285. if err != nil {
  286. return nil, err
  287. }
  288. handler = m.Middleware(handler)
  289. insecureHandler = m.Middleware(insecureHandler)
  290. }
  291. // Add logger if configured
  292. if len(cfg.Logger) > 0 {
  293. logger, err := logging.New("ca", cfg.Logger)
  294. if err != nil {
  295. return nil, err
  296. }
  297. handler = logger.Middleware(handler)
  298. insecureHandler = logger.Middleware(insecureHandler)
  299. }
  300. // Create context with all the necessary values.
  301. baseContext := buildContext(auth, scepAuthority, acmeDB, acmeLinker)
  302. ca.srv = server.New(cfg.Address, handler, tlsConfig)
  303. ca.srv.BaseContext = func(net.Listener) context.Context {
  304. return baseContext
  305. }
  306. // only start the insecure server if the insecure address is configured
  307. // and, currently, also only when it should serve SCEP endpoints.
  308. if ca.shouldServeInsecureServer() {
  309. // TODO: instead opt for having a single server.Server but two
  310. // http.Servers handling the HTTP and HTTPS handler? The latter
  311. // will probably introduce more complexity in terms of graceful
  312. // reload.
  313. ca.insecureSrv = server.New(cfg.InsecureAddress, insecureHandler, nil)
  314. ca.insecureSrv.BaseContext = func(net.Listener) context.Context {
  315. return baseContext
  316. }
  317. }
  318. if meter != nil {
  319. ca.metricsSrv = server.New(ca.config.MetricsAddress, meter, nil)
  320. ca.metricsSrv.BaseContext = func(net.Listener) context.Context {
  321. return baseContext
  322. }
  323. }
  324. return ca, nil
  325. }
  326. // shouldServeInsecureServer returns whether or not the insecure
  327. // server should also be started. This is (currently) only the case
  328. // if the insecure address has been configured AND when a SCEP
  329. // provisioner is configured or when a CRL is configured.
  330. func (ca *CA) shouldServeInsecureServer() bool {
  331. switch {
  332. case ca.config.InsecureAddress == "":
  333. return false
  334. case ca.shouldServeSCEPEndpoints():
  335. return true
  336. case ca.config.CRL.IsEnabled():
  337. return true
  338. default:
  339. return false
  340. }
  341. }
  342. // buildContext builds the server base context.
  343. func buildContext(a *authority.Authority, scepAuthority *scep.Authority, acmeDB acme.DB, acmeLinker acme.Linker) context.Context {
  344. ctx := authority.NewContext(context.Background(), a)
  345. if authDB := a.GetDatabase(); authDB != nil {
  346. ctx = db.NewContext(ctx, authDB)
  347. }
  348. if adminDB := a.GetAdminDatabase(); adminDB != nil {
  349. ctx = admin.NewContext(ctx, adminDB)
  350. }
  351. if scepAuthority != nil {
  352. ctx = scep.NewContext(ctx, scepAuthority)
  353. }
  354. if acmeDB != nil {
  355. ctx = acme.NewContext(ctx, acmeDB, acme.NewClient(), acmeLinker, nil)
  356. }
  357. return ctx
  358. }
  359. // Run starts the CA calling to the server ListenAndServe method.
  360. func (ca *CA) Run() error {
  361. var wg sync.WaitGroup
  362. errs := make(chan error, 1)
  363. if !ca.opts.quiet {
  364. authorityInfo := ca.auth.GetInfo()
  365. log.Printf("Starting %s", step.Version())
  366. log.Printf("Documentation: https://u.step.sm/docs/ca")
  367. log.Printf("Community Discord: https://u.step.sm/discord")
  368. if step.Contexts().GetCurrent() != nil {
  369. log.Printf("Current context: %s", step.Contexts().GetCurrent().Name)
  370. }
  371. log.Printf("Config file: %s", ca.getConfigFileOutput())
  372. baseURL := fmt.Sprintf("https://%s%s",
  373. authorityInfo.DNSNames[0],
  374. ca.config.Address[strings.LastIndex(ca.config.Address, ":"):])
  375. log.Printf("The primary server URL is %s", baseURL)
  376. log.Printf("Root certificates are available at %s/roots.pem", baseURL)
  377. if len(authorityInfo.DNSNames) > 1 {
  378. log.Printf("Additional configured hostnames: %s",
  379. strings.Join(authorityInfo.DNSNames[1:], ", "))
  380. }
  381. for _, crt := range authorityInfo.RootX509Certs {
  382. log.Printf("X.509 Root Fingerprint: %s", x509util.Fingerprint(crt))
  383. }
  384. if authorityInfo.SSHCAHostPublicKey != nil {
  385. log.Printf("SSH Host CA Key: %s\n", bytes.TrimSpace(authorityInfo.SSHCAHostPublicKey))
  386. }
  387. if authorityInfo.SSHCAUserPublicKey != nil {
  388. log.Printf("SSH User CA Key: %s\n", bytes.TrimSpace(authorityInfo.SSHCAUserPublicKey))
  389. }
  390. }
  391. wg.Add(1)
  392. go func() {
  393. defer wg.Done()
  394. ca.runCompactJob()
  395. }()
  396. if ca.insecureSrv != nil {
  397. wg.Add(1)
  398. go func() {
  399. defer wg.Done()
  400. errs <- ca.insecureSrv.ListenAndServe()
  401. }()
  402. }
  403. if ca.metricsSrv != nil {
  404. wg.Add(1)
  405. go func() {
  406. defer wg.Done()
  407. errs <- ca.metricsSrv.ListenAndServe()
  408. }()
  409. }
  410. wg.Add(1)
  411. go func() {
  412. defer wg.Done()
  413. errs <- ca.srv.ListenAndServe()
  414. }()
  415. // wait till error occurs; ensures the servers keep listening
  416. err := <-errs
  417. wg.Wait()
  418. return err
  419. }
  420. // Stop stops the CA calling to the server Shutdown method.
  421. func (ca *CA) Stop() error {
  422. close(ca.compactStop)
  423. if ca.renewer != nil {
  424. ca.renewer.Stop()
  425. }
  426. if err := ca.auth.Shutdown(); err != nil {
  427. log.Printf("error stopping ca.Authority: %+v\n", err)
  428. }
  429. var insecureShutdownErr error
  430. if ca.insecureSrv != nil {
  431. insecureShutdownErr = ca.insecureSrv.Shutdown()
  432. }
  433. secureErr := ca.srv.Shutdown()
  434. if insecureShutdownErr != nil {
  435. return insecureShutdownErr
  436. }
  437. return secureErr
  438. }
  439. // Reload reloads the configuration of the CA and calls to the server Reload
  440. // method.
  441. func (ca *CA) Reload() error {
  442. cfg, err := config.LoadConfiguration(ca.opts.configFile)
  443. if err != nil {
  444. return errors.Wrap(err, "error reloading ca configuration")
  445. }
  446. logContinue := func(reason string) {
  447. log.Println(reason)
  448. log.Println("Continuing to run with the original configuration.")
  449. log.Println("You can force a restart by sending a SIGTERM signal and then restarting the step-ca.")
  450. }
  451. // Do not allow reload if the database configuration has changed.
  452. if !reflect.DeepEqual(ca.config.DB, cfg.DB) {
  453. logContinue("Reload failed because the database configuration has changed.")
  454. return errors.New("error reloading ca: database configuration cannot change")
  455. }
  456. newCA, err := New(cfg,
  457. WithPassword(ca.opts.password),
  458. WithSSHHostPassword(ca.opts.sshHostPassword),
  459. WithSSHUserPassword(ca.opts.sshUserPassword),
  460. WithIssuerPassword(ca.opts.issuerPassword),
  461. WithLinkedCAToken(ca.opts.linkedCAToken),
  462. WithQuiet(ca.opts.quiet),
  463. WithConfigFile(ca.opts.configFile),
  464. WithDatabase(ca.auth.GetDatabase()),
  465. )
  466. if err != nil {
  467. logContinue("Reload failed because the CA with new configuration could not be initialized.")
  468. return errors.Wrap(err, "error reloading ca")
  469. }
  470. if ca.insecureSrv != nil {
  471. if err = ca.insecureSrv.Reload(newCA.insecureSrv); err != nil {
  472. logContinue("Reload failed because insecure server could not be replaced.")
  473. return errors.Wrap(err, "error reloading insecure server")
  474. }
  475. }
  476. if ca.metricsSrv != nil {
  477. if err = ca.metricsSrv.Reload(newCA.metricsSrv); err != nil {
  478. logContinue("Reload failed because metrics server could not be replaced.")
  479. return errors.Wrap(err, "error reloading metrics server")
  480. }
  481. }
  482. if err = ca.srv.Reload(newCA.srv); err != nil {
  483. logContinue("Reload failed because server could not be replaced.")
  484. return errors.Wrap(err, "error reloading server")
  485. }
  486. // 1. Stop previous renewer
  487. // 2. Safely shutdown any internal resources (e.g. key manager)
  488. // 3. Replace ca properties
  489. // Do not replace ca.srv
  490. if ca.renewer != nil {
  491. ca.renewer.Stop()
  492. }
  493. ca.auth.CloseForReload()
  494. ca.auth = newCA.auth
  495. ca.config = newCA.config
  496. ca.opts = newCA.opts
  497. ca.renewer = newCA.renewer
  498. return nil
  499. }
  500. // get TLSConfig returns separate TLSConfigs for server and client with the
  501. // same self-renewing certificate.
  502. func (ca *CA) getTLSConfig(auth *authority.Authority) (*tls.Config, *tls.Config, error) {
  503. // Create initial TLS certificate
  504. tlsCrt, err := auth.GetTLSCertificate()
  505. if err != nil {
  506. return nil, nil, err
  507. }
  508. // Start tls renewer with the new certificate.
  509. // If a renewer was started, attempt to stop it before.
  510. if ca.renewer != nil {
  511. ca.renewer.Stop()
  512. }
  513. ca.renewer, err = NewTLSRenewer(tlsCrt, auth.GetTLSCertificate)
  514. if err != nil {
  515. return nil, nil, err
  516. }
  517. ca.renewer.Run()
  518. var serverTLSConfig *tls.Config
  519. if ca.config.TLS != nil {
  520. serverTLSConfig = ca.config.TLS.TLSConfig()
  521. } else {
  522. serverTLSConfig = &tls.Config{
  523. MinVersion: tls.VersionTLS12,
  524. }
  525. }
  526. // GetCertificate will only be called if the client supplies SNI
  527. // information or if tlsConfig.Certificates is empty.
  528. // When client requests are made using an IP address (as opposed to a domain
  529. // name) the server does not receive any SNI and may fallback to using the
  530. // first entry in the Certificates attribute; by setting the attribute to
  531. // empty we are implicitly forcing GetCertificate to be the only mechanism
  532. // by which the server can find it's own leaf Certificate.
  533. serverTLSConfig.Certificates = []tls.Certificate{}
  534. clientTLSConfig := serverTLSConfig.Clone()
  535. serverTLSConfig.GetCertificate = ca.renewer.GetCertificateForCA
  536. clientTLSConfig.GetClientCertificate = ca.renewer.GetClientCertificate
  537. // initialize a certificate pool with root CA certificates to trust when doing mTLS.
  538. certPool := x509.NewCertPool()
  539. // initialize a certificate pool with root CA certificates to trust when connecting
  540. // to webhook servers
  541. rootCAsPool, err := x509.SystemCertPool()
  542. if err != nil {
  543. return nil, nil, err
  544. }
  545. for _, crt := range auth.GetRootCertificates() {
  546. certPool.AddCert(crt)
  547. rootCAsPool.AddCert(crt)
  548. }
  549. // adding the intermediate CA certificates to the pool will allow clients that
  550. // do mTLS but don't send an intermediate to successfully connect. The intermediates
  551. // added here are used when building a certificate chain.
  552. intermediates := tlsCrt.Certificate[1:]
  553. for _, certBytes := range intermediates {
  554. cert, err := x509.ParseCertificate(certBytes)
  555. if err != nil {
  556. return nil, nil, err
  557. }
  558. certPool.AddCert(cert)
  559. rootCAsPool.AddCert(cert)
  560. }
  561. // Add support for mutual tls to renew certificates
  562. serverTLSConfig.ClientAuth = tls.VerifyClientCertIfGiven
  563. serverTLSConfig.ClientCAs = certPool
  564. clientTLSConfig.RootCAs = rootCAsPool
  565. return serverTLSConfig, clientTLSConfig, nil
  566. }
  567. // shouldServeSCEPEndpoints returns if the CA should be
  568. // configured with endpoints for SCEP. This is assumed to be
  569. // true if a SCEPService exists, which is true in case at
  570. // least one SCEP provisioner was configured.
  571. func (ca *CA) shouldServeSCEPEndpoints() bool {
  572. return ca.auth.GetSCEP() != nil
  573. }
  574. //nolint:unused // useful for debugging
  575. func dumpRoutes(mux chi.Routes) {
  576. // helpful routine for logging all routes
  577. walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
  578. fmt.Printf("%s %s\n", method, route)
  579. return nil
  580. }
  581. if err := chi.Walk(mux, walkFunc); err != nil {
  582. fmt.Printf("Logging err: %s\n", err.Error())
  583. }
  584. }
  585. func (ca *CA) getConfigFileOutput() string {
  586. if ca.config.WasLoadedFromFile() {
  587. return ca.config.Filepath()
  588. }
  589. return "loaded from token"
  590. }
  591. // runCompactJob will run the value log garbage collector if the nosql database
  592. // supports it.
  593. func (ca *CA) runCompactJob() {
  594. caDB, ok := ca.auth.GetDatabase().(*db.DB)
  595. if !ok {
  596. return
  597. }
  598. compactor, ok := caDB.DB.(nosql.Compactor)
  599. if !ok {
  600. return
  601. }
  602. // Compact database at start.
  603. runCompact(compactor)
  604. // Compact database every minute.
  605. ticker := time.NewTicker(time.Minute)
  606. defer ticker.Stop()
  607. for {
  608. select {
  609. case <-ca.compactStop:
  610. return
  611. case <-ticker.C:
  612. runCompact(compactor)
  613. }
  614. }
  615. }
  616. // runCompact executes the compact job until it returns an error.
  617. func runCompact(c nosql.Compactor) {
  618. for err := error(nil); err == nil; {
  619. err = c.Compact(0.7)
  620. }
  621. }