ca.go 22 KB

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