ca.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  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 {
  231. acmeDB, err = acmeNoSQL.New(auth.GetDatabase().(nosql.DB))
  232. if err != nil {
  233. return nil, fmt.Errorf("error configuring ACME DB interface: %w", err)
  234. }
  235. acmeLinker = acme.NewLinker(dns, "acme")
  236. mux.Route("/acme", func(r chi.Router) {
  237. acmeAPI.Route(r)
  238. })
  239. // Use 2.0 because, at the moment, our ACME api is only compatible with v2.0
  240. // of the ACME spec.
  241. mux.Route("/2.0/acme", func(r chi.Router) {
  242. acmeAPI.Route(r)
  243. })
  244. }
  245. // Admin API Router
  246. if cfg.AuthorityConfig.EnableAdmin {
  247. adminDB := auth.GetAdminDatabase()
  248. if adminDB != nil {
  249. acmeAdminResponder := adminAPI.NewACMEAdminResponder()
  250. policyAdminResponder := adminAPI.NewPolicyAdminResponder()
  251. webhookAdminResponder := adminAPI.NewWebhookAdminResponder()
  252. mux.Route("/admin", func(r chi.Router) {
  253. adminAPI.Route(
  254. r,
  255. adminAPI.WithACMEResponder(acmeAdminResponder),
  256. adminAPI.WithPolicyResponder(policyAdminResponder),
  257. adminAPI.WithWebhookResponder(webhookAdminResponder),
  258. )
  259. })
  260. }
  261. }
  262. var scepAuthority *scep.Authority
  263. if ca.shouldServeSCEPEndpoints() {
  264. // get the SCEP authority configuration. Validation is
  265. // performed within the authority instantiation process.
  266. scepAuthority = auth.GetSCEP()
  267. // According to the RFC (https://tools.ietf.org/html/rfc8894#section-7.10),
  268. // SCEP operations are performed using HTTP, so that's why the API is mounted
  269. // to the insecure mux.
  270. scepPrefix := "scep"
  271. insecureMux.Route("/"+scepPrefix, func(r chi.Router) {
  272. scepAPI.Route(r)
  273. })
  274. // The RFC also mentions usage of HTTPS, but seems to advise
  275. // against it, because of potential interoperability issues.
  276. // Currently I think it's not bad to use HTTPS also, so that's
  277. // why I've kept the API endpoints in both muxes and both HTTP
  278. // as well as HTTPS can be used to request certificates
  279. // using SCEP.
  280. mux.Route("/"+scepPrefix, func(r chi.Router) {
  281. scepAPI.Route(r)
  282. })
  283. }
  284. // helpful routine for logging all routes
  285. //dumpRoutes(mux)
  286. //dumpRoutes(insecureMux)
  287. // Add monitoring if configured
  288. if len(cfg.Monitoring) > 0 {
  289. m, err := monitoring.New(cfg.Monitoring)
  290. if err != nil {
  291. return nil, err
  292. }
  293. handler = m.Middleware(handler)
  294. insecureHandler = m.Middleware(insecureHandler)
  295. }
  296. // Add logger if configured
  297. var legacyTraceHeader string
  298. if len(cfg.Logger) > 0 {
  299. logger, err := logging.New("ca", cfg.Logger)
  300. if err != nil {
  301. return nil, err
  302. }
  303. legacyTraceHeader = logger.GetTraceHeader()
  304. handler = logger.Middleware(handler)
  305. insecureHandler = logger.Middleware(insecureHandler)
  306. }
  307. // always use request ID middleware; traceHeader is provided for backwards compatibility (for now)
  308. handler = requestid.New(legacyTraceHeader).Middleware(handler)
  309. insecureHandler = requestid.New(legacyTraceHeader).Middleware(insecureHandler)
  310. // Create context with all the necessary values.
  311. baseContext := buildContext(auth, scepAuthority, acmeDB, acmeLinker)
  312. ca.srv = server.New(cfg.Address, handler, tlsConfig)
  313. ca.srv.BaseContext = func(net.Listener) context.Context {
  314. return baseContext
  315. }
  316. // only start the insecure server if the insecure address is configured
  317. // and, currently, also only when it should serve SCEP endpoints.
  318. if ca.shouldServeInsecureServer() {
  319. // TODO: instead opt for having a single server.Server but two
  320. // http.Servers handling the HTTP and HTTPS handler? The latter
  321. // will probably introduce more complexity in terms of graceful
  322. // reload.
  323. ca.insecureSrv = server.New(cfg.InsecureAddress, insecureHandler, nil)
  324. ca.insecureSrv.BaseContext = func(net.Listener) context.Context {
  325. return baseContext
  326. }
  327. }
  328. if meter != nil {
  329. ca.metricsSrv = server.New(ca.config.MetricsAddress, meter, nil)
  330. ca.metricsSrv.BaseContext = func(net.Listener) context.Context {
  331. return baseContext
  332. }
  333. }
  334. return ca, nil
  335. }
  336. // shouldServeInsecureServer returns whether or not the insecure
  337. // server should also be started. This is (currently) only the case
  338. // if the insecure address has been configured AND when a SCEP
  339. // provisioner is configured or when a CRL is configured.
  340. func (ca *CA) shouldServeInsecureServer() bool {
  341. switch {
  342. case ca.config.InsecureAddress == "":
  343. return false
  344. case ca.shouldServeSCEPEndpoints():
  345. return true
  346. case ca.config.CRL.IsEnabled():
  347. return true
  348. default:
  349. return false
  350. }
  351. }
  352. // buildContext builds the server base context.
  353. func buildContext(a *authority.Authority, scepAuthority *scep.Authority, acmeDB acme.DB, acmeLinker acme.Linker) context.Context {
  354. ctx := authority.NewContext(context.Background(), a)
  355. if authDB := a.GetDatabase(); authDB != nil {
  356. ctx = db.NewContext(ctx, authDB)
  357. }
  358. if adminDB := a.GetAdminDatabase(); adminDB != nil {
  359. ctx = admin.NewContext(ctx, adminDB)
  360. }
  361. if scepAuthority != nil {
  362. ctx = scep.NewContext(ctx, scepAuthority)
  363. }
  364. if acmeDB != nil {
  365. ctx = acme.NewContext(ctx, acmeDB, acme.NewClient(), acmeLinker, nil)
  366. }
  367. return ctx
  368. }
  369. // Run starts the CA calling to the server ListenAndServe method.
  370. func (ca *CA) Run() error {
  371. if !ca.opts.quiet {
  372. authorityInfo := ca.auth.GetInfo()
  373. log.Printf("Starting %s", step.Version())
  374. log.Printf("Documentation: https://u.step.sm/docs/ca")
  375. log.Printf("Community Discord: https://u.step.sm/discord")
  376. if step.Contexts().GetCurrent() != nil {
  377. log.Printf("Current context: %s", step.Contexts().GetCurrent().Name)
  378. }
  379. log.Printf("Config file: %s", ca.getConfigFileOutput())
  380. baseURL := fmt.Sprintf("https://%s%s",
  381. authorityInfo.DNSNames[0],
  382. ca.config.Address[strings.LastIndex(ca.config.Address, ":"):])
  383. log.Printf("The primary server URL is %s", baseURL)
  384. log.Printf("Root certificates are available at %s/roots.pem", baseURL)
  385. if len(authorityInfo.DNSNames) > 1 {
  386. log.Printf("Additional configured hostnames: %s",
  387. strings.Join(authorityInfo.DNSNames[1:], ", "))
  388. }
  389. for _, crt := range authorityInfo.RootX509Certs {
  390. log.Printf("X.509 Root Fingerprint: %s", x509util.Fingerprint(crt))
  391. }
  392. if authorityInfo.SSHCAHostPublicKey != nil {
  393. log.Printf("SSH Host CA Key: %s\n", bytes.TrimSpace(authorityInfo.SSHCAHostPublicKey))
  394. }
  395. if authorityInfo.SSHCAUserPublicKey != nil {
  396. log.Printf("SSH User CA Key: %s\n", bytes.TrimSpace(authorityInfo.SSHCAUserPublicKey))
  397. }
  398. }
  399. eg := new(errgroup.Group)
  400. eg.Go(func() error {
  401. ca.runCompactJob()
  402. return nil
  403. })
  404. if ca.insecureSrv != nil {
  405. eg.Go(func() error {
  406. return ca.insecureSrv.ListenAndServe()
  407. })
  408. }
  409. if ca.metricsSrv != nil {
  410. eg.Go(func() error {
  411. return ca.metricsSrv.ListenAndServe()
  412. })
  413. }
  414. eg.Go(func() error {
  415. return ca.srv.ListenAndServe()
  416. })
  417. _, _ = daemon.SdNotify(true, daemon.SdNotifyReady)
  418. err := eg.Wait()
  419. _, _ = daemon.SdNotify(true, daemon.SdNotifyStopping)
  420. // if the error is not the usual HTTP server closed error, it is
  421. // highly likely that an error occurred when starting one of the
  422. // CA servers, possibly because of a port already being in use or
  423. // some part of the configuration not being correct. This case is
  424. // handled by stopping the CA in its entirety.
  425. if !errors.Is(err, http.ErrServerClosed) {
  426. log.Println("shutting down due to startup error ...")
  427. if stopErr := ca.Stop(); stopErr != nil {
  428. err = fmt.Errorf("failed stopping CA after error occurred: %w: %w", err, stopErr)
  429. } else {
  430. err = fmt.Errorf("stopped CA after error occurred: %w", err)
  431. }
  432. }
  433. return err
  434. }
  435. // Stop stops the CA calling to the server Shutdown method.
  436. func (ca *CA) Stop() error {
  437. close(ca.compactStop)
  438. if ca.renewer != nil {
  439. ca.renewer.Stop()
  440. }
  441. if err := ca.auth.Shutdown(); err != nil {
  442. log.Printf("error stopping ca.Authority: %+v\n", err)
  443. }
  444. // Concurrently shutdown services
  445. var eg errgroup.Group
  446. if ca.insecureSrv != nil {
  447. eg.Go(func() error {
  448. return ca.insecureSrv.Shutdown()
  449. })
  450. }
  451. if ca.metricsSrv != nil {
  452. eg.Go(func() error {
  453. return ca.metricsSrv.Shutdown()
  454. })
  455. }
  456. if ca.srv != nil {
  457. eg.Go(func() error {
  458. return ca.srv.Shutdown()
  459. })
  460. }
  461. // Return first error
  462. return eg.Wait()
  463. }
  464. // Reload reloads the configuration of the CA and calls to the server Reload
  465. // method.
  466. func (ca *CA) Reload() error {
  467. _, _ = daemon.SdNotify(true, daemon.SdNotifyReloading)
  468. cfg, err := config.LoadConfiguration(ca.opts.configFile)
  469. if err != nil {
  470. return fmt.Errorf("error reloading ca configuration: %w", err)
  471. }
  472. logContinue := func(reason string) {
  473. log.Println(reason)
  474. log.Println("Continuing to run with the original configuration.")
  475. log.Println("You can force a restart by sending a SIGTERM signal and then restarting the step-ca.")
  476. }
  477. // Do not allow reload if the database configuration has changed.
  478. if !reflect.DeepEqual(ca.config.DB, cfg.DB) {
  479. logContinue("Reload failed because the database configuration has changed.")
  480. return errors.New("error reloading ca: database configuration cannot change")
  481. }
  482. newCA, err := New(cfg,
  483. WithPassword(ca.opts.password),
  484. WithSSHHostPassword(ca.opts.sshHostPassword),
  485. WithSSHUserPassword(ca.opts.sshUserPassword),
  486. WithIssuerPassword(ca.opts.issuerPassword),
  487. WithLinkedCAToken(ca.opts.linkedCAToken),
  488. WithQuiet(ca.opts.quiet),
  489. WithConfigFile(ca.opts.configFile),
  490. WithDatabase(ca.auth.GetDatabase()),
  491. )
  492. if err != nil {
  493. logContinue("Reload failed because the CA with new configuration could not be initialized.")
  494. return fmt.Errorf("error reloading ca: %w", err)
  495. }
  496. if ca.insecureSrv != nil {
  497. if err = ca.insecureSrv.Reload(newCA.insecureSrv); err != nil {
  498. logContinue("Reload failed because insecure server could not be replaced.")
  499. return fmt.Errorf("error reloading insecure server: %w", err)
  500. }
  501. }
  502. if ca.metricsSrv != nil {
  503. if err = ca.metricsSrv.Reload(newCA.metricsSrv); err != nil {
  504. logContinue("Reload failed because metrics server could not be replaced.")
  505. return fmt.Errorf("error reloading metrics server: %w", err)
  506. }
  507. }
  508. if err = ca.srv.Reload(newCA.srv); err != nil {
  509. logContinue("Reload failed because server could not be replaced.")
  510. return fmt.Errorf("error reloading server: %w", err)
  511. }
  512. // 1. Stop previous renewer
  513. // 2. Safely shutdown any internal resources (e.g. key manager)
  514. // 3. Replace ca properties
  515. // Do not replace ca.srv
  516. if ca.renewer != nil {
  517. ca.renewer.Stop()
  518. }
  519. ca.auth.CloseForReload()
  520. ca.auth = newCA.auth
  521. ca.config = newCA.config
  522. ca.opts = newCA.opts
  523. ca.renewer = newCA.renewer
  524. _, _ = daemon.SdNotify(true, daemon.SdNotifyReady)
  525. return nil
  526. }
  527. // get TLSConfig returns separate TLSConfigs for server and client with the
  528. // same self-renewing certificate.
  529. func (ca *CA) getTLSConfig(auth *authority.Authority) (*tls.Config, *tls.Config, error) {
  530. // Create initial TLS certificate
  531. tlsCrt, err := auth.GetTLSCertificate()
  532. if err != nil {
  533. return nil, nil, err
  534. }
  535. // Start tls renewer with the new certificate.
  536. // If a renewer was started, attempt to stop it before.
  537. if ca.renewer != nil {
  538. ca.renewer.Stop()
  539. }
  540. ca.renewer, err = NewTLSRenewer(tlsCrt, auth.GetTLSCertificate)
  541. if err != nil {
  542. return nil, nil, err
  543. }
  544. ca.renewer.Run()
  545. var serverTLSConfig *tls.Config
  546. if ca.config.TLS != nil {
  547. serverTLSConfig = ca.config.TLS.TLSConfig()
  548. } else {
  549. serverTLSConfig = &tls.Config{
  550. MinVersion: tls.VersionTLS12,
  551. }
  552. }
  553. // GetCertificate will only be called if the client supplies SNI
  554. // information or if tlsConfig.Certificates is empty.
  555. // When client requests are made using an IP address (as opposed to a domain
  556. // name) the server does not receive any SNI and may fallback to using the
  557. // first entry in the Certificates attribute; by setting the attribute to
  558. // empty we are implicitly forcing GetCertificate to be the only mechanism
  559. // by which the server can find it's own leaf Certificate.
  560. serverTLSConfig.Certificates = []tls.Certificate{}
  561. clientTLSConfig := serverTLSConfig.Clone()
  562. serverTLSConfig.GetCertificate = ca.renewer.GetCertificateForCA
  563. clientTLSConfig.GetClientCertificate = ca.renewer.GetClientCertificate
  564. // initialize a certificate pool with root CA certificates to trust when doing mTLS.
  565. certPool := x509.NewCertPool()
  566. // initialize a certificate pool with root CA certificates to trust when connecting
  567. // to webhook servers
  568. rootCAsPool, err := x509.SystemCertPool()
  569. if err != nil {
  570. return nil, nil, err
  571. }
  572. for _, crt := range auth.GetRootCertificates() {
  573. certPool.AddCert(crt)
  574. rootCAsPool.AddCert(crt)
  575. }
  576. // adding the intermediate CA certificates to the pool will allow clients that
  577. // do mTLS but don't send an intermediate to successfully connect. The intermediates
  578. // added here are used when building a certificate chain.
  579. intermediates := tlsCrt.Certificate[1:]
  580. for _, certBytes := range intermediates {
  581. cert, err := x509.ParseCertificate(certBytes)
  582. if err != nil {
  583. return nil, nil, err
  584. }
  585. certPool.AddCert(cert)
  586. rootCAsPool.AddCert(cert)
  587. }
  588. // Add support for mutual tls to renew certificates
  589. serverTLSConfig.ClientAuth = tls.VerifyClientCertIfGiven
  590. serverTLSConfig.ClientCAs = certPool
  591. clientTLSConfig.RootCAs = rootCAsPool
  592. return serverTLSConfig, clientTLSConfig, nil
  593. }
  594. // shouldServeSCEPEndpoints returns if the CA should be
  595. // configured with endpoints for SCEP. This is assumed to be
  596. // true if a SCEPService exists, which is true in case at
  597. // least one SCEP provisioner was configured.
  598. func (ca *CA) shouldServeSCEPEndpoints() bool {
  599. return ca.auth.GetSCEP() != nil
  600. }
  601. //nolint:unused // useful for debugging
  602. func dumpRoutes(mux chi.Routes) {
  603. // helpful routine for logging all routes
  604. walkFunc := func(method string, route string, _ http.Handler, _ ...func(http.Handler) http.Handler) error {
  605. fmt.Printf("%s %s\n", method, route)
  606. return nil
  607. }
  608. if err := chi.Walk(mux, walkFunc); err != nil {
  609. fmt.Printf("Logging err: %s\n", err.Error())
  610. }
  611. }
  612. func (ca *CA) getConfigFileOutput() string {
  613. if ca.config.WasLoadedFromFile() {
  614. return ca.config.Filepath()
  615. }
  616. return "loaded from token"
  617. }
  618. // runCompactJob will run the value log garbage collector if the nosql database
  619. // supports it.
  620. func (ca *CA) runCompactJob() {
  621. caDB, ok := ca.auth.GetDatabase().(*db.DB)
  622. if !ok {
  623. return
  624. }
  625. compactor, ok := caDB.DB.(nosql.Compactor)
  626. if !ok {
  627. return
  628. }
  629. // Compact database at start.
  630. runCompact(compactor)
  631. // Compact database every minute.
  632. ticker := time.NewTicker(time.Minute)
  633. defer ticker.Stop()
  634. for {
  635. select {
  636. case <-ca.compactStop:
  637. return
  638. case <-ticker.C:
  639. runCompact(compactor)
  640. }
  641. }
  642. }
  643. // runCompact executes the compact job until it returns an error.
  644. func runCompact(c nosql.Compactor) {
  645. for err := error(nil); err == nil; {
  646. err = c.Compact(0.7)
  647. }
  648. }