4
0

ca.go 21 KB

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