4
0

ca.go 21 KB

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