ca.go 21 KB

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